European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET 4 Hosting :: How to Fix "Could not load type" error message in Visual C# .NET

clock December 2, 2011 05:46 by author 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



European Visual Studio 2010 Hosting :: Data Schema Comparison in Visual Studio 2010

clock November 21, 2011 05:19 by author Scott

Visual Studio 2010  has some inbuilt functionality as a tool to compare the different schemas .Schema comparison is a powerful tool that is used to compare database schemas. In tips I will give some basic step to compare schemas in Visual Studio 2010

First launch the Schema Comparison tool from Data > Schema Compare > New Schema Comparison .

This will launch a New Schema Compare Tool where you can set Source and Target Schema



The result when source and target schema are same is displayed below



The result when source and target schema were somewhat different is displayed below



European ASP.NET 4 Hosting :: HTML Encoded Expressions in ASP.NET4

clock November 18, 2011 07:51 by author 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.



European ASP.NET 4.5 Hosting :: Visual Studio 2011 Preview - Server Side Event Handler Generation from ASP.NET Markup

clock November 11, 2011 06:08 by author Scott

Yes, Visual Studio 2011 will coming soon. This is really a great addition in Visual Studio 2011 Developer Preview for ASP.NET developers. If you are familiar with  WPF and XMAL development in Visual Studio, it should be well known for you, because  preview version of Visual Studio supports  generation of  event handler code from XMAL markup itself.  With Visual Studio 2011 developer preview, creating event handlers for ASP.NET controls have become significantly easy. You really don’t not need to write the event handler manually or  generating the even handler from design view.

In VS 2011 Developer preview, markup intellisense for all ASP.NET server-side events will show you list of exiting handlers and a value called “<Create New Event>” . Which means you can attach the event with some exiting event handler or  select “create New event” to generate an new  handler with the right signature in the code-behind file.



If there is no control Id provided, Visual Studio will consider the control id as “Unnamed” and will generate the event handler as shown in below.





If you are wondering  about what will happen if there are multiple controls  without ids, does Visual studio going to attach with same event handler? No, It will  append an incremental number with event handler name.



Visual Studio will generate Event handler name as <ControlName>_Click if control id is provided.





European ASP.NET Hosting :: How to Connect MySQL Server with .NET in C# or ASP.NET

clock November 8, 2011 05:18 by author 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



European ASP.NET 4 Hosting :: Dynamic Programming in C# 4.0

clock October 10, 2011 07:21 by author 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.



European ASP.NET 4 Hosting :: Binding data in XML file to GridView

clock October 6, 2011 08:39 by author 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



European ASP.NET 4 Hosting :: Session State in ASP.NET 4.0

clock September 27, 2011 06:20 by author 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.



European ASP.NET 4 Hosting :: Visualize Response.RedirectPermanent in ASP.NET 4

clock September 21, 2011 08:54 by author Scott

In ASP.NET 4.0 there are new features that enable developer to make SEO friendly websites very easily. And if you google out, you will find plenty of article which explain this feature. But I am more interested in Response.RedirectPermanent. As the name suggest it is used to redirect permanently moved resources to new location. And most of all articles on the net just explain this with some example. But how can we visualize that whether resource is redirected permanently or not. So here is the answer for that. I have used FireBug to examine the same.

Whenever we redirect with Response.Redirect, we can see following activity in FireBug console.



As we can see that page which issues Response.Redirect its response status code 302(Found) which means requested url(default.aspx) is found but it is temporarily moved to about.aspx. More information on HTTP status code can be found
here.

Now whenever we redirect with Response.RedirectPermanent, we can see following activity in FireBug console.



As we can see that page which issues Response.RedirectPermanent its response status code 301(Moved Permanently) which means requested url(default.aspx) is moved Permanently to about.aspx. 301 status code is used by search engine crawler to update search index to new moved information.

I hope information provided here would be more helpful to distinguish between Response.Redirect and Response.RedirectPermanent.



European ASP.NET 4 Hosting:: Raising Server side event from JavaScript in ASP.NET

clock September 16, 2011 06:34 by author 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.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in