ASP.NET inline expressions

17 Kas 2013 In: .net, ipucu
  • <% ... %>
  • <%= ... %>
  • <%@ ... %>
  • <%# ... %>
  • <%$ ... %>
  • <%-- ... %>
  • <%@ ... %>
 

<% ... %> embedded code blocks

The embedded code block is used to preserve backward compatibility with classical ASP. The code in the block can execute programming statements and call functions in the current page class during the page-rendering phase.

The following example demonstrates an ASP.NET page that has sample Microsoft Visual Basic .NET code in an embedded code block to display the results of a loop:
<%@ Page Language="VB" %>
<html>
<body>
<form id="form1" runat="server">
<% For i As Integer = 16 To 24 Step 2%>
<div style="font-size: <% Response.Write(i)%>">
Hello World<br />
</div>
<% Next%>
</form>
</body>
</html>
Because an embedded code block is always mixed with the HTML source, it is difficult for developers to read and maintain them. 

For more information about embedded code blocks in ASP.NET Web pages, visit the following Microsoft Developer Network (MSDN) Web site:

<%= ... %> displaying expression

The <%= ... %>displaying expression is an equivalent of the embedded code block that contains only the Response.Write(…) statement. This is the simplest way to display information such as a single string, an int variable, or a constant. 

For example, the following sample code displays the current time:
<%@ Page Language="VB" %>
<html>
<body>
<form id="form1" runat="server">
<%=DateTime.Now.ToString() %>
</form>
</body>
</html>
Remember that the displaying expression cannot be used in the attributes of server controls. This is because the .NET Framework directly compiles the whole expression instead of the displaying content as the value to the attribute.

For more information about how to display information from ASP.NET, visit the following MSDN Web site:

<%@ ... %> directive expression

The directive expression is the syntax that specifies settings that are used by the page and by user control compilers when they process ASP.NET Web Form (.aspx) pages and User Control (.ascx) files.

The ASP.NET page framework supports the following directives:
@ Page Defines page-specific attributes that are used by the ASP.NET page parser and compiler. Can be included only in .aspx files. 
*This directive name can be used only in ASP.NET Web Form pages.
@ Control Defines control-specific attributes that are used by the ASP.NET page parser and compiler. Can be included only in .ascx files (user controls). 
*This directive name can be used only in User Control files.
@ Import Explicitly imports a namespace into a page or into a user control.
@ Implements Declaratively indicates that a page or a user control implements a specified .NET Framework interface.
@ Register Associates aliases with namespaces and with class names. This enables user controls and custom server controls to be rendered when they are included in a requested page or user control.
@ Assembly Links an assembly to the current page during compilation. It makes all the assembly's classes and interfaces available for use on the page.
@ Master Identifies an ASP.NET master page.
@ WebHandler Identifies an ASP.NET IHttpHandler page.
@ PreviousPageType Provides a way to obtain strong typing against the previous page as accessed through the PreviousPageproperty.
@ MasterType Assigns a class name to the Master property of an ASP.NET page. Provides a way to create a strongly typed reference to the ASP.NET master page.
@ OutputCache Declaratively controls the output caching policies of a page or of a user control.
@ Reference Declaratively links a page or user control to the current page or user control.
For more information about directive syntax, visit the following MSDN Web site:

<%# ... %> data-binding expression

The data-binding expression creates binding between a server control property and a data source when the control’s DataBindmethod of this server control is called on the page. 

The following example shows how to use the data-binding expression to bind the string from a function to the Text property of a label:
<%@ Page Language="VB" %>
<script runat="server">
Protected Function SayHello() As String
Return "Hello World"
End Function
Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs)
lblHello.DataBind()
End Sub
</script>
<html>
<body>
<form id="form1" runat="server">
<asp:Label ID="lblHello" runat="server" Text="<%# SayHello%>"></asp:Label>
</form>
</body>
</html>
For more information about data-binding expression syntax, visit the following MSDN Web site:

<%$ ... %> expression builder

The expression builder is used to set values of control properties based on the information that is contained in an application's configuration or resource files. The following is the basic syntax of the expression builder:
<%$ Expression Prefix: Expression Value %>
The dollar sign ($) indicates to ASP.NET that the following expression is an expression builder. The expression prefix defines the kind of expression, such as AppSettingsConnectionStrings, or Resources. Additionally, you can create and define your own expression builder. The expression value that follows the colon (:) is what ASP.NET will actually use as the value of a certain property.

The following demo shows how to use the expression builder to obtain the copyright of a Web site from the AppSettings node in the Web.config file and how to then set the copyright information as the value of the Literal’s Text property.

The AppSettings node in Web.config file:
<appSettings>
<add key="copyright" value="(c) Copyright 2009 WebSiteName.com"/>
</appSettings>
The expression builder in the ASP.NET Web Form page:
<div id="footer">
<asp:Literal ID="Literal1" runat="server" Text="<%$ AppSettings: copyright %>"></asp:Literal>
</div>
For more information about ASP.NET expressions, visit the following MSDN Web site:

<%-- ... -- %> server-side comments block

The server-side comments block lets developers embed code comments in any location of the HTML source of ASP.NET Web Form pages (except for within <script> code blocks). Any content between the opening and closing tags of the server-side comments block will not be processed on the server or rendered on the resulting page.

The following code example shows how to use the server-side comments block in an ASP.NET page:
<%@ Page Language="VB" %>
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim strName As String
strName = Session("userName")
lblUserName.Text = strName
End Sub
</script>
<html>
<body>
<form id="form1" runat="server">
<%-- Label for UserName --%>
<asp:Label ID="lblUserName" runat="server" Text=""></asp:Label>
</form>
</body>
</html>
 

 Başka bir kaynakdan : 

 
 
 <%      %>

these tags what we talk about. It comes from ASP classic style and it used in PHP and JSP too for the same reason "Writing Server Side Code ".

Note: you must know that we can't use it in code behind (Page.aspx.cs ) .

inline Code and  Page Life cycle :

When the page call its Render Method after the PreRenderComplete Event completed the compiler will Execute this Code and embedded it into Render method which accept HtmlTextWriter  as a single parameter  like the following :

protected override void Render(HtmlTextWriter writer)
 {
     base.Render(writer);
}

Let us see the forms you may have seen:

 Page Directive

<%@ Page Language="C#"  %>

Rendering Code

<% Response.Write("Hello World!");  %>

<%= SayHello("Ahmed") %>

<%: DateTime.Now.ToString()  %>

Expression Syntax

<%$ ConnectionStrings:ConnStrFromWebConfig  %>

<%$ AppSettings:ValueFromWebConfig  %>

<%$ Resources:Resource, Arabic  %>

<%$ RouteValue:year  %>

<%$ YourExpressionPrefix : Any   %>

Data Binding  Syntax

<%# Eval("Name")  %>

<%# Bind("Name")  %>

<%# XPath ("Name")  %>

Comment Server

<%-- <asp:Label runat="server" Text="Label"></asp:Label>-- %>

Let us do it in details :

Directive

We use directive to specify settings used by page and user control Compiler . we use it to say hi complier this file is ...... .each directive can have number of attributes as you need.

each directive start with @ . ASP.Net introduced number of Directive as following :

@Page
 : used on .aspx files only and you can use only one  directive inside a file . 

<%
@ Page Language="C#" %>

<%@ Page Language="C#" CodeFile="Default2.aspx.cs" Inherits="Default2"  %>

Note that we are  using Codefile to pass the file name of code behind and inherits to pass class Name.

 

@Control : used only in .ascx files (user control)

<%@ Control Language="C#" ClassName="WebUserControl"  %>

 

@Import :  used for name space declaration and only when we write code inside script tags,I mean that if we use code behind we don't need it because we will use "Using Directive" (C#) or " Imports " (VB.net)

<%@ Import Namespace="System.Data"  %>

 

@Assembly :  used to Links an Assembly(.DLL or .CS and .VB ) to that page and user control .

DLL files like this

<%@ Assembly Name="CustomFile"  %>

(without .dll extension )

Class files like this :

<%@ Assembly src="Csharp.cs"   %>

<%@ Assembly src="Csharp.vb"   %>

Note: we are using Name attribute with dll files and src with class files.

 

@Register : used to register Controls (User Controls and Custom Server Controls) to page and user control.

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp"  %>

<%@ Register src="WebUserControl.ascx"   tagname="WebUserControl" tagprefix="uc1" %>

 

Note :we are using Name attribute when using assembly and using src when user control.

@Implements : used when we want to implement an Interface . and this Directive  takes only one attribute "Interface" .

<%@ Implements Interface="IWebParts"  %>

 

@Reference : used to indicate that the source file of the page or user control  should dynamically compiled and linked to the current page .

<%@ Reference Control ="~/WebUserControl.ascx"  %>

<%@ Reference Page="~/Default2.aspx"  %>

<%@ Reference VirtualPath ="anyfile.any"  %>

 

@OutPutCache : used when we need to put a page or user control in the cache.

<%@ OutputCache Duration ="900" VaryByParam ="none"  %>

Note: both attributes ( Duration and VarybyParam ) are required .

 

@Master : used to decalre page as Master page.

<%@ Master Language="C#"  %>

 

@MasterType : used to reference Master Page when we need to access master page through  Master Property .

<%@ MasterType VirtualPath ="~/MasterPage.master"   %>

 

@PreviousPage : used when need to access previous page through PreviousPage Property .

<%@ PreviousPageType VirtualPath ="~/Default4.aspx"   %>

 

@Application : used to declare the global application file .(global.asax)

<%@ Application Language="C#"   %>

 

@WebService : used to declare the web service file .(.asmx)

<%@ WebService Language="C#" CodeBehind="~/App_Code/WebService.cs" Class="WebService"   %>

 

@WebHandler: used to declare the generic handler file (.ashx)

<%@ WebHandler Language="C#" Class="Handler"  %>

 

@ServiceHost : used by WCF (Windows Communication Foundation) .

<%@ ServiceHost Language="C#" Debug="true" Service="Service" CodeBehind="~/App_Code/Service.cs" %>

 

Rendering Code

Render code tags like Response.write Method. Here an example : using for Looping

    <div>

         <% for(int i = 0 ; i <5; i++){  %>

             Hello World ! <br />

           <%  } %>

    </div>

output the following :

Hello World !

Hello World !

Hello World !

Hello World !

Hello World !

 you can use it to execute a method but this time we use " = " to get out of Response.write to an Expression and =  is used to resolve an expression and return its value to the block

<%@ Page Language="C#"   %>

<script runat="server">

    string message = "I Can Do it ";


    string SayHello(string name)
    {
        return "Hello  " + name;
    }   

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Test Page </title>

</head>

<body>

    <form id="form1" runat="server">

    <div>
         <%= SayHello("Ahmed") %>
         <br />
         <br />
         <%="Message variable = " + message %>
    </div>
   </form>
</body>
</html>

it will output string say "Hello Ahmed " and also gets the value of message variable .

Note : this code blocks render nothing (no html controls ) . try it yourself . browse this code in the browser and Right click to View source .

Html Encoding output in ASP.Net 4

It provides a concise way to automatically HTML encode content and then render it as output

  <%:DateTime.Now.ToString () %>

You can learn more here :

we can also use it to embedded Server Side code in Client Side Code (Java Script)

what about calling Server side Method from Client Side Method . Let us do it :

take a look at this code

<%@ Page Language="C#"   %>

<script runat="server">
    string SayHello(string name)
    {
        return "Hello  " + name;
    }    
</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
    <title>Test Page </title>
    <script type="text/javascript" >
        function SayAny() {
            alert(' <%= SayHello("ahmed") %>');
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
         <br />
        <input type="submit" onclick="SayAny()" value="Say Hello" />
        <br />
    </div>
    </form>
</body>
</html>

 it do what you expect : showing alert message .

Sometimes we have a problem when passig control id to client side code like this

var txt = document.getElementById("TextBox1");

and this happened when we work with container like master page or when we want to find control inside Data contorls Like GridView ,DataList ,Repeater ,and so on. this happens because the control has been changed to something like "container_ControlId". and to solve this issue we can use server side blocks like the following :

var txt = document.getElementById("<%=TextBox1.ClientID %>");

you can use alert message to display the value of this TextBox like this :

alert(txt.value);

Expression Syntax :

Get Connection String Section :

<%$ ConnectionStrings:ConnStrFromWebConfig %>

after we set connection strings in web.config file then we need to use data source controls ,Like the following :

Example

<asp:SqlDataSource ID="SqlDataSource2"   runat="server"  ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
        SelectCommand="SELECT * FROM [Categories]">
</asp:SqlDataSource>

Notice: connectionstring is the name of connection string section inside Web.Config Like following :

Web.config :
<connectionStrings>
    <add name="ConnectionString" 
            connectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NORTHWND.MDF;
                                        Integrated Security=True;User Instance=True"
            providerName = "System.Data.SqlClient" />
 </connectionStrings>

Get AppSettings Section 

<%$ AppSettings:ValueFromWebConfig %>

after we set AppSettings section in web.config file you can call it using key name to return its value .

Web.config 

<appSettings>
        <add key ="KeyName" value ="This Value Is Ahmed"/>
</appSettings>

Default.aspx

<asp:Label Text="<%$ AppSettings :Keyname  %>" runat="server" />

Get a value from Global Resource File (.resx )

<%$ Resources:Resource, Arabic  %>

Let us take an example switching between two Language (Arabic and English ).

  • Create two files (Resource.resx , Resource.ar-eg.resx ) and put them in App_GlobalResources folder.
  • Define a key with name "Greeting" in both resource files.

              Note : the "greeting" key will have two different value for Arabic and English .

  • Create test page.aspx and drag a label control and drop down list control. so ,your aspx code will be like this :

<div>
    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
       <asp:ListItem Value="ar-eg">Arabic</asp:ListItem>
       <asp:ListItem Value="en-us">English</asp:ListItem>
    </asp:DropDownList>
    <br />
    <br />
    <asp:Label ID="Label1" runat="server" Text="<%$ Resources:Resource, Greeting %>"> </asp:Label>    
</div>

Note :

Resources >> Say " I am working with resource files ".

Resource >> say "I am the resource file name without extension".

Greeting >> say " I am the Key which my value will be displayed"

now we have two values for "Arabic" and "English" we can switch between them. what will happen if we select English or Arabic ? ok, we need some code to change Language and Current Culture .let us go to next step:

  • We need to override IntializeCulture Method as following :

protected override void InitializeCulture()
    {
        if (Request["DropDownlist1"] != null)
       {
            string lang = Request["DropDownlist1"];
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(lang );
            Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.CreateSpecificCulture(lang );
        }
    }

Now you can select your Language from drop down list control and see that the related content will be displayed.

Routing

ASP.Net Routing is something about mapping URLs, Routing is available in ASP.Net web forms and ASP.Net MVC.Since .net framework 3.5. to use routing you need to create static method that take a parameter of RouteCollection data type inside global.asax file, then call these method in Application_Start event .

May you need more in Routing  so here you can take a look

http://msdn.microsoft.com/en-us/library/dd329551.aspx

Ok , what we want to say is we can use Expression Syntax to set URLs Like this :

<%$ RouteUrl:action=Edit , CategoryName=Cars%>

<%$ RouteValue:year %>

You need to understand what action and categoryName means? To do this refer to The above Link .

Exrpression Builder

<%$ YourExpressionPrefix : Any   %>

yes ,  you can create your Expression like mine : 
<div>
   <asp:Label Text="<%$ myCode:DateTime.Now %>" runat="server" />
</div>

to learn more about Expression Builder Click Here

Data Binding Syntax

<%# Eval("Name") %>

<%# Bind("Name")%>

<%# XPath ("Name") %>

We use embedded code in Data binding to set or get or in Other words to read and write to a data source .we have Two methods for  working with Data base (Eval and Bind ) and one for working with XML (XPath that stand of xml path ) .so , what is the different between Eval and bind ? Eval method is One way that means it is for reading and Bind method is Two way that means it is for Reading and writing  .

Example :  using eval method in grid view to display Images .

<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">

        <Columns>

            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />

            <asp:TemplateField>

                <ItemTemplate>

                    <asp:Image ID="Image2" runat="server" ImageUrl='<%# Eval("Path")  %>' Width="70" />

                </ItemTemplate>

            </asp:TemplateField>

        </Columns>

    </asp:GridView>

In the above example we use eval method to get path field from data base and pass It to ImageUrl Property.

try to use bind method in editing data.

XPath method:

Use it when working with Xml, we can use it to select element or attribute and get its value and it comes in many forms Like this :

Look at this file.xml. we use it to simplifies the following :

<?xml version="1.0" encoding="utf-8" ?>
<Links>
    <Link>
       <name>Microsoft</name>
       <Site>http://www.microsoft.com</Site>
   </Link>
   <Link>
       <name id="10" >Asp.net</name>
       <Site>http://www.asp.net</Site>
   </Link>
    <Link>
        <name id="20" >MSDN</name>
        <Site>http://www.msdn.com</Site>
    </Link>
</Links>   

<%# XPath ("Name") %>

get the value of the Name element .

output here will be as following : Microsot  ASP.Net  MSDN

<%# XPath("name[@id]") %>

Get the value of the name element which take an attribute  with name "Id"

output here will be as following : ASP.Net  MSDN

<%# XPath ("name[@id=\"10\"]") %>

Get the value of name element which take an attribute with name id that its value equal 10 .

 

output here will be as following : ASP.Net 

<%# XPath("name/@id") %>

Get the value of  Every  attribute which its name is 'id' that  was defined in "name" element .

output here will be as following : 10  20

Yes, it is give xml more funs .

Note :

When using your custom method as Binding Expression Remember to call Databind Method . this question I meet it in Asp.Net forums and that is my answer "call Databind method to that control "

Example : Get Text  from the result of custom method .

<div>

      <asp:Button ID="SomethingBtn" Text="<%# ServerSideMethod()  %>" runat="server" />

</div>

So when we try to view it in browser the button wouldn't display any text . because we need to call Data bind method for that button Like this :

protected void Page_Load(object sender, EventArgs e)

    {

        Somethingbtn.DataBind();

    }

And finally I want to say that you can use all or one of them Like this :

<%# Eval("Id","~/default.aspx?id={0}")  %>

<%# "Your Name Is :" + Eval("Name") %>

<%# SayHello( Eval("Name").ToString () ) %>

And More ...........

Last thing is Comment Server 

We can use it to put  a comment where the comment is not allowed  .

Example :

<div>

<%-- <asp:Button ID="Button2" runat="server" Text="Button"  />--%>

</div>

 Resource : Ahmed Moosa

 
 
 
 
Repeater içerisinde Visible kontrolu için  Visible='<%# string.Equals(Session["state"].ToString(), "A")%>' 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 <script type="text/javascript">
        function DisableButtons() {
            $('#loading').show();
        }

        function oki() {
            $('#loading').hide();
        }
        window.onbeforeunload = DisableButtons;
        window.onload = oki;
    </script>

    <style>
        .ShadowNone {
            text-shadow: none;
            font-size: 14px;
            font-weight: 600;
            text-align: right;
        }

        #loading {
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            position: fixed;
            display: block;
            opacity: 0.7;
            background-color: #fff;
            z-index: 999;
            text-align: center;
        }

        #loading-image {
            position: absolute;
            z-index: 1000;
            left: 45%;
            top: 45%;
        }
    </style>


///-----------------------------------------------///

 <div id="loading" style="display: none;">
        <img id="loading-image" src="images/loading.gif" alt="Yükleniyor..." />
 </div>

AJAX ile async işlemler

3 Eki 2013 In: .net, ipucu

ASP.NET de async işlem yapabilmek için JQueryden faydalanmanız gerekiyor.
Bunu 2 yöntem ile yapmak mümkün

1. ScriptManager
2. JQuery methodları ile

2. methoda daha dogal geldiginden işlemlerimizi onunla gerçekleştiricez.

a) İlk olarak .cs tarafında methodumuzu yazalım :

[System.Web.Services.WebMethod]
        public static string Kaydet(string a,string b)
        {
            string result = "OK : " + a + " - ";
            return result;
        } 


b) Şimdi JQuery kütüphaneleri eklediginizi düşünerek hemen HTML kontrolün çağıracagı JS methoda oluşturalım :

     function Kaydetsene(a,b) {
    $.ajax({
        type: "POST",
        url: "sevkiyatci.aspx/Kaydet",
        data: "{a:'aaaa',b:'bb'}",
        contentType: "application/json;",
        dataType: "json",
        success: function(response) { alert("OK : "+ response.d);},
        failure: function(response) { alert("HATA : "+ response.d);}
    });
}

 

c) Son alarakda methodu control üzerindeki bi event ile çagırıyoruz

 OnClick='<%# Eval("Fat_No","Kaydetsene(\"{0}\",\"2\");") %>'  

 OnClick='<%# "Kaydetsene(\"" + Eval("Fat_No") + "\",\"2\");" %>' 

 

 

//-----digerleri------

var k = $('[id$=lbl_kim]').attr('title');
var params = "{'Kimden':'"+k+"'}";

$('#okun').text('0');

setTimeout("GetMSJsayisi();", 10000);

 

// digerleri iki - eger farklı ise

  <system.webServer>

    <validation validateIntegratedModeConfiguration="false"/>

    <modules>

      <remove name="ScriptModule"/>

      <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

    </modules>

    <handlers>

      <remove name="WebServiceHandlerFactory-Integrated"/>

      <remove name="ScriptHandlerFactory"/>

      <remove name="ScriptHandlerFactoryAppServices"/>

      <remove name="ScriptResource"/>

      <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

      <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

      <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

    </handlers>

  </system.webServer> 

 

 

//----------------- dropdownlist

JavaScript ile:

var e = document.getElementById("elementId");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;

jQuery ile:

$("#elementId :selected").text(); // The text content of the selected option
$("#elementId").val(); // The value of the selected option

 

 

IIS de bir ASP.NET hatası

1 Eki 2013 In: .net, ipucu

 

 Hata bu:

The current identity (NT AUTHORITY\NETWORK SERVICE) does not have write access to 'c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files'.

 

Çözüm : 

Sunucuda çalışan Asp.Net versiyonuna ait klasörde  Ör : C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

 aspnet_regiis -ga "NT Authority\Network Service"

veya

 aspnet_regiis -ga IUSR_<machinename>

 

Bitti gitti... 

 Silent repair on 64 bit computer with .Net Framework version 4.0.30319 :

%windir%\Microsoft.NET\Framework64\v4.0.30319\SetupCache\Client\setup.exe /repair /x86 /x64 /ia64 /parameterfolder Client /q /norestart
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe –i
 
 
 
 

Zaman Hatası

13 Ağu 2012 In: .net, ipucu

The security timestamp is invalid because its creation time ('2012-08-13T08:03:31.882Z') is in the future. Current time is '2012-08-13T07:54:50.894Z' and allowed clock skew is '00:05:00'.

 
Eger bu hatayı alıyorsanız büyük olasılık tarih saat ayarlarınızda bir sorun var. Düzeltmek için server in tarih saat ayarlarından internet time e göre senkronize edin ve bir restart sorununuz düzelsin. 
 
Lakin sunucuda Internet Time Tab yoksa missing ile veyahut no internet time tab diyorsanız büyük olasılık cihazınız domainde . Hayırlı olsun o zman yapılması gereken, CMD ye :
 
w32tm /config /syncfromflags:MANUAL /manualpeerlist:time.nist.gov
w32tm /config /update
w32tm /resync 
 
 
hayırlı olsun 1-2 dakika içinde sync olur. Ama servislerinde saglıklı çalışması için ör MSSQLSVR restart şart.
 
 
Eger size
The computer did not resync because no time data was available.
 
hatası alırsanız "Services.msc" den "Windows Time" servisini bir kere durdurup yeniden başlatın ve "w32tm /resync" yeniden çalıştırın.  ve sonuç "The command completed successfully."
 
 
 

Export your data to Excel file

13 Eyl 2011 In: .net

(GridView üzerindeki verilerinizi Excel dosyasına C# ile aktarma işlemi, önce gridview i oluşturup databind yapıp, gerekli dosyayı oluşturabilir )

 

         public static void Export(string fileName, GridView gv)

       {

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
            HttpContext.Current.Response.ContentType = "application/ms-excel";

            using (StringWriter sw = new StringWriter())

            {

                using (HtmlTextWriter htw = new HtmlTextWriter(sw))

                {

                    Table table = new Table();

                    if (gv.HeaderRow != null)

                    {

                        GVUtils.PrepareControlForExport(gv.HeaderRow);

                        table.Rows.Add(gv.HeaderRow);

                    }

                    foreach (GridViewRow row in gv.Rows)

                    {

                        GVUtils.PrepareControlForExport(row);

                        table.Rows.Add(row);

                    }

 

                    if (gv.FooterRow != null)

                    {

                        GVUtils.PrepareControlForExport(gv.FooterRow);

                        table.Rows.Add(gv.FooterRow);

                    }

                    table.RenderControl(htw);

                    HttpContext.Current.Response.Write(sw.ToString());

                    HttpContext.Current.Response.End();

                }

            }

        }

 

        private static void PrepareControlForExport(Control control)

        {

            for (int i = 0; i < control.Controls.Count; i++)

            {

                Control current = control.Controls[i];

                if (current is LinkButton)

                {

                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));

                }

 

                else if (current is ImageButton)

                {

                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));

                }

 

                else if (current is HyperLink)

                {

                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));

                }

 

                else if (current is DropDownList)

                {

                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));

                }

 

                else if (current is CheckBox)

                {

                    control.Controls.Remove(current);

                    control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));

                }

 

                if (current.HasControls())

                {

                    GVUtils.PrepareControlForExport(current);

                }

            }

        } 

Import data from excel file in ASP.NET

13 Ağu 2011 In: .net

Excel dosyasınden C# ile veri okuma ASP.NET içerisinde, Excel dosyanın içinedeki tüm sayfaları gezebilir, içerisindeki kolon isimlerine göre sizin DB update veya insert yapabilirsiniz.

 

if (FileUpload1.HasFile)

            {

                try

                {

                    int uk = 0,yk=0;

                    lbl_durum.Text = "";

                    String ext = System.IO.Path.GetExtension(FileUpload1.FileName);

                    if (ext.ToLower() != ".xls" )

                    {

                        lbl_durum.Text = "Uzantı yanlış.";

                        return;

                    }

                    string path = string.Concat(Server.MapPath("~/ExcelFiles/FromUsers/" + FileUpload1.FileName));

                    FileUpload1.SaveAs(path);

 

                    // Connection String to Excel Workbook

                    string excelConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Extended Properties='Excel 8.0;HDR=Yes'", path);

                    using (OleDbConnection connection = new OleDbConnection(excelConnectionString))

                    {

                        try

                        {

                            connection.Open();

                            DataTable dt = new DataTable();

                            dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                            if (dt == null)

                            {

                                lbl_durum.Text = "Dosyanın içinde sayfa yok.";

                                return;

                            }

 

                            String[] excelSheets = new String[dt.Rows.Count];

                            int t = 0;

                            //excel data saves in temp file here.

                            foreach (DataRow row in dt.Rows)

                            {

                                excelSheets[t] = row["TABLE_NAME"].ToString();

                                t++;

                            }

 

                            OleDbDataAdapter adap = new OleDbDataAdapter("select * from [" + excelSheets[0] + "] WHERE UZM_ID>0", connection);

                            DataTable liste = new DataTable();

                            adap.Fill(liste);

 

                            for (int i = 0; i < liste.Rows.Count; i++)

                            {

                                string up = "";

                                if (liste.Rows[i]["UZM_ID"].ToString() == "") break;

                                for (int j = 0; j < liste.Columns.Count; j++)

                                {

                                    if (liste.Columns[j].ColumnName == "UZM_ID" || liste.Columns[j].ColumnName == "CDate")

                                    {

                                        continue;

                                    }

                                    if (liste.Rows[i][j].ToString() != "")

                                    {

                                        if (liste.Columns[j].ColumnName == "Disabled")

                                            up += liste.Columns[j].ColumnName + "=" + liste.Rows[i][j].ToString() + ", ";

                                        else

                                            up += liste.Columns[j].ColumnName + "='" + liste.Rows[i][j].ToString() + "', ";

                                    }

                                    else

                                        if (liste.Rows[i][j].ToString() == "NULL")

                                        {

                                            up += liste.Columns[j].ColumnName + "=NULL, ";

                                        }

                                }

                                if (up.EndsWith(", ")) up = up.Substring(0, up.Length - 2);

 

                                if(up.Length>0)

                                    if ("" != SQLCalistir_N("UPDATE Uzmanlar SET " + up + " WHERE UZM_ID='" + liste.Rows[i]["UZM_ID"] + "'"))

                                        uk++;

                            }

 

                            lbl_durum.Text += " " + uk.ToString() + " kayıt üzerinde güncellenme yapıldı. ";

 

                            //yeni eklenecekler

                            adap = new OleDbDataAdapter("select * from [" + excelSheets[0] + "] WHERE UZM_ID=0", connection);

                            liste = new DataTable();

                            adap.Fill(liste);

 

                            for (int i = 0; i < liste.Rows.Count; i++)

                            {

                                string fld = "";

                                string dgr = "";

                                for (int j = 0; j < liste.Columns.Count; j++)

                                {

                                    if (liste.Columns[j].ColumnName == "UZM_ID" || liste.Columns[j].ColumnName == "CDate" || liste.Columns[j].ColumnName == "Disabled")

                                    {

                                        continue;

                                    }

                                    if (liste.Rows[i][j].ToString() != "")

                                    {

                                            fld += liste.Columns[j].ColumnName+ ", ";

                                            dgr += "'" + liste.Rows[i][j].ToString() + "', "; 

                                    }

                                }

 

                                if (fld.EndsWith(", ")) fld = fld.Substring(0, fld.Length - 2);

                                if (dgr.EndsWith(", ")) dgr = dgr.Substring(0, dgr.Length - 2);

 

                                if ("" != SQLCalistir_N("INSERT INTO Uzmanlar ("+fld+") VALUES ("+dgr+")"))

                                    yk++;

                            }

 

                            lbl_durum.Text += " " + yk.ToString() + " kayıt yeni eklendi. ";

 

                        }

                        catch (Exception ex)

                        {

                            lbl_durum.Text = ex.Message;

                        }

                    }

                }

                catch (Exception ex)

                {

                    lbl_durum.Text = ex.Message;

                }

            }

        } 

 

 

 

 

 

Ben Kimim ?

Celiker BahceciMerhabalar, ben Çeliker BAHÇECİ. 2004 den beri özel sektörde bilgisayar mühendisligi ve egitmenlik yapıyorum. Yine aynı yılın Ekim ayından beri sitemde .Net ile programlama ve hayat görüşüm ile ilgili makalelerimi yayınlıyorum. Blogum dışında Yazgelistir.com, mobilnedir.com gibi ineta kapsamındaki bir çok siteye Microsoft teknolojileri ile ilgili yazılar yazmaktayım.
Bu site ile sizinde hayatınızı anlamlandırmanızda bir parça katkımın olması dilegiyle...