December 2, 2011 05:46 by
Scott
Sometimes when you browse to an .aspx page, you may receive one of the following error messages:
Could not load type 'Namespace.Global'.
-or-
Could not load type 'Namespace.PageName'.
In this turorial I will show you how to fix it. This is caused by These errors occur if the .aspx page or the Global.asax page contains a reference to a code-behind module and if the application has not been built.
SOLUTION
· Use the C# command line compiler (CSC.exe) to run the following command:
csc /t:library /r:System.web.dll /out:mydll.dll myfile.cs
· In Microsoft Visual Studio .NET, click Build on the Build menu.
Hope it help
November 21, 2011 05:19 by
Scott
November 18, 2011 07:51 by
Scott
Today I would like to discuss an interesting feature that is available only in ASP.NET4. It is primarily used in MVC3 applications.
ASP.NET 4.0 comes with a Encoded Expressions <%: expression %> that will automatically convert string into html encoded. Now we can replace all occurrences of <%= %> with <%: %>.
SO what is the difference between these two? Are they same?
No they are not. The main difference is when you use the new syntax our code get encoded. Any html script in side do not gets executed by the browser.
It is just treated as content. In the previous versions you might be using Server.HtmlEncode(<%=expression %>).
So this new syntax does exactly same function as this method. We can use HtmlString type to indicate encoding is unnecessary.
Proof of Concept
I have created a Test method that returns string and that string has some HTML characters like < > to be encoded
public static string Test()
{
return "alert('Hello World!!! returns javascript'); HTML Encoded expression";
}
Now add 2 aspx pages. In the first page add this code.
<DIV>
<form id="form1" runat="server">
<strong><%: Test()%></strong>
</form>
</div>
</DIV>
Now In the Second aspx page use this syntax
<DIV>
<form id="form1" runat="server">
<strong><%= Test()%></strong>
</form>
</div>
</DIV>
Run this pages on the browser one after the other. Now if you observe, first page gives a just text where as 2nd page is not encoded it returns the script alert message along with text . And look at the viewsource you can see the difference exactly.
Advantages
- General security threats for ASP.Net Web applications are Cross-site script injection attacks and HTML encoding attacks. This feature is nice handy way to eliminate javascript injection in your web applications.
- Now it is easy to replace <%=exp %> to <%:exp%> and make your code or data more secured.
- Now We do not need to specify Validate-Request to validate HTML Scripts in ASP.NET, which you may be doing it in web.config or pagelevel
Is it not so interesting?. So start playing with the feature.
Hope this helps. Let me know if any questions are clarifications.
November 11, 2011 06:08 by
Scott
November 8, 2011 05:18 by
Scott
In this tutorial, I will show you how to connect to MySQL Server with .NET in C# or ASP.NET. What requirements do you need?
1. Please download MySQL Connector/Net.
2. After you add a reference to your project, it is probably in C:\Program Files\MySQL\MySQL Connector Net 5.0.7\Binaries\.NET 2.0 folder, add the MySql.Data.dll file as a reference.
3. Make your connection string, the following code will shows a standard MySQL connection string.
using MySql.Data.MySqlClient;
public static string GetConnectionString()
{
string connStr =
String.Format("server={0};user id={1}; password={2};
database=yourdb; pooling=false", "yourserver",
"youruser", "yourpass");
return connStr;
}
4. Then create an instance from MySql.Data.MySqlClient.MySqlConnection as shown below.
MySql.Data.MySqlClient.MySqlConnection mycon
= new MySqlConnection( GetConnectionString());
5. Then try to open the MySQL connection.
if(mycon .State != ConnectionState.Open)
try
{
mycon .Open();
}
catch (MySqlException ex)
{
throw (ex);
}
Simple right?? J
October 10, 2011 07:21 by
Scott
C# 4.0 supports Dynamic Programming by introducing new Dynamic Typed Objects. The type of these objects is resolved at run-time instead of compile-time. A new keyword dynamic is introduced to declare dynamic typed object. The keyword tells the compiler that everything to do with the object, declared as dynamic, should be done dynamically at the run-time using Dynamic Language Runtime(DLR). Remember dynamic keyword is different from var keyword. When we declare an object as var, it is resolved at compile-time whereas in case of dynamic the object type is dynamic and its resolved at run-time. Let’s do some coding to see advantage of Dynamic Typed Objects :)
A year back I wrote a code of setting property of an object using Reflection:
1: Assembly asmLib= Assembly.LoadFile(@"C:\temp\DemoClass\bin\Debug\DemoClass.dll");
2: Type demoClassType = asmLib.GetType("DemoClass.DemoClassLib");
3: object demoClassobj= Activator.CreateInstance(demoClassType);
4: PropertyInfo pInfo= demoClassType.GetProperty("Name");
5: pInfo.SetValue(demoClassobj, "Adil", null);
Notice line 3-5 creates instance of ‘demoClassType’ and set property ‘Name’ to ‘Adil’. Now with C# 4.0 line # 3-5 can be written as simple as:
dynamic dynamicDemoClassObj = Activator.CreateInstance(demoClassType);
dynamicDemoClassObj.Name = "Adil";
Simple isn’t it? Let’s see a slide from Anders Hejlsberg’s session at PDC 2008:
From the above slide, you can call method(s) such as x.ToString(), y.ToLower(), z.Add(1) etc and it will work smoothly :)
This feature is great and provides much flexibility for developers. In this post, we explore the dynamic typed object in C# 4.0. We will explore dynamic in detail and other features as well in the coming posts. Of course there are pros and cons of dynamic programming as well but where C# is going is something like having features of both static languages and dynamic languages.
October 6, 2011 08:39 by
Scott
Let say you have an XML file and you want to show the information (data in XML file) in GridView. Here, I am going to show you, how to DataBind asp:GridView to the data contained in an XML document.
A standard XML file will look like below:
<?xml version="1.0" encoding="utf-8" ?>
<Fruits>
<Fruit>
<id>1</id>
<name>Apple</name>
<color>Red</color>
</Fruit>
<Fruit>
<id>2</id>
<name>Mango</name>
<color>Yellow</color>
</Fruit>
</Fruits>
The entity in this file is a Fruit. Apparently, there are three columns (sub-nodes of Fruit node) named id, name and color. However, you can’t bind the data defined in this standard XML file directly to the GridView.
First you have to transform the XML data into a format understandable to GridView (e.g. tabular or rows collection format). You can transform a standard XML document into various formats (e.g. HTML markups) by using XSLT. XML document transformation to different XML formats using XSLT demonstrates a basic data transformation for an XML document and contains the transformation template definition for XSLT file.
Once you have applied a valid XML data tranformation, you can use XmlDataSource control to make a connection to your XML file and then bind it to GridView directly. Below is the markup code to bind a GridView to an XmlDataSource.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="XmlDataSource1">
<Columns>
<asp:BoundField DataField="name" HeaderText="Fruit Name" />
<asp:BoundField DataField="color" HeaderText="Fruit Color" />
</Columns>
</asp:GridView>
<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/XMLFile1.xml" TransformFile="~/XSLTFile1.xslt">
</asp:XmlDataSource>
Here, XMLFile1.xml is the actual XML file containg the data you want to bind GridView with and XSLTFile1.xslt is the file containing the desired transformation template.
That's all, I hope you have got an idea of
1. How to bind gridview to xml data
2. How to bind gridview to xml file
3. Binding gridview to xmldocument
4. How to modify XML file in order to make it appropriate for GridView DataSource
September 27, 2011 06:20 by
Scott
This post explains about Shrinking session state in ASP.NET 4.0.
ASP.NET Provides two options for storing session state for web applications.
1. Out of process session state
2. MS SQL server session state
In both the options session-state providers stores the data out side the web application worker process. Session state has to be serialized before it sends it to the external storage.
ASP.NET 4.0 introduces a new compression option for both out-of-process session state providers. We can set the compressionEnabled option in configuration file to true. ASP.NET will compress the session state by using the .NET Framework System.IO.Compression.GZipStream class.
We can configure the session state as follows
<sessionState
mode="SqlServer"
sqlConnectionString="data source=dbserver;Initial Catalog=aspnetstate"
allowCustomSqlDatabase="true"
compressionEnabled="true"
/>
Advantage: With this addition of attribute to web.config file there is substantial reduction in the size of serialized session-state data.
September 16, 2011 06:34 by
Scott
Well, knowing internal structure of an ASP.NET event system can always be an element of fun and interests. Recently I came across to a requirement to generate a server side event on a page directly from Javascript. There are a couple of approaches available with the existing models (like ICallbackEventHandler etc) but these will put additional pressure to the page and also does not use the existing code already present. So I thought to put a script that could use all the existing code and work similar to what happens in background.
You might know when a page is processed, it generates two hidden controls. viz. EventName and EventValue. The eventName is used to send the name of the event that the client is going to generate in the server side. As you know, ASP.NET is a stateless protocol. Hence everything that is genenrated in the server side to produce your page, will be disposed once it is done. Hence you need to postback the whole page again to communicate and during this phase, the ASP.NET server side page generates the respective events on various controls which is specified on the eventName.
The eventValue on the other hand will hold additional arguments that you need to send to the server for the particular event. The ASP.NET page will generate the event automatically during the rendering of the page in the server side.
Now here, I am going to build my own event so I need to do this myself. Lets see how :
public delegate void CustomEventHandler(string message);
public event CustomEventHandler public void OnCustomEventRaised(string message)
{
if (this.CustomEvent != null)
this.CustomEvent(message);
};
Say I have to generate this event from the client side. As this event is created totally by me, I need to configure it myself, such that it generates it when passed with special attribute. I personally thought it would be easier to understand this for a newbie if I write it under Page_Load, but you are free to generate this event as your wish (following your own pattern I guess). Now lets look the code to understand
First of all, I create two hidden field in the page with runat =”server”
<asp:HiddenField ID="hidEventName" runat="server" />
<asp:HiddenField ID="hidEventValue" runat="server" />
This will ensure that the hiddenfields will be available from server side. Now inside Page_Load, I write code to raise the event :
public void Page_Load(…)
{
if (hidEventName.Value == "CustomEvent")
{
hidEventName.Value = ""; //It is essential reset it and remove viewstate data
OnCustomEventRaised(hidEventValue.Value);
}
}
public void OnCustomEventRaised(string message)
{
if (this.CustomEvent != null)
this.CustomEvent(message);
}
So eventually I am raising the eventhandler once the page is posted back from the client side. Now to raise the event from the client side, let me add a javascript :
function RaiseEvent(pEventName, pEventValue) {
document.getElementById('<%=hidEventName.ClientID %>').value = pEventName;
document.getElementById('<%=hidEventValue.ClientID %>').value = pEventValue;
if (document.getElementById('<%=MyUpdatePanel.ClientID %>') != null) {
__doPostBack('<%=MyUpdatePanel.ClientID %>', '');
}
}
So basically I am posting back the whole page from the client side using the __doPostBack method already present for every page. Here I have used my UpdatePanelId to ensure that postback is generated from my UpdatePanel.
Now from javascript if I call :
RaiseEvent(‘CustomEvent’, ‘Hello from server’);
It will eventually call the server with my custom message.