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 Hosting :: How to Disable or Make a ListItem Non selectable ASP.Net DropDownList Using jQuery

clock December 5, 2011 08:19 by author Scott

Sometimes, we may want to add some ListItem that are not clickable or selectable in ASP.Net DropDownList.  The non selectable items will be an informational list items that may help users to understand the items. For example, consider a DropDownList that has list of states of different country. It will be user friendly if we have a non selectable country name before populating the list of states under that country. Something like below,



The below jQuery code will help you to do the same,

<script src="_scripts/jquery-1.4.1.min.js" type="text/javascript"></script>   
    <script type="text/javascript">      
        $(function() {
        $("#<% =DropDownList1.ClientID %> > option[value=Country]").attr("disabled", "disabled")          
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>   
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
            onselectedindexchanged="DropDownList1_SelectedIndexChanged">
            <asp:ListItem Text="Select your state" Value=""></asp:ListItem>
            <asp:ListItem Text="India" Value="Country"></asp:ListItem>
            <asp:ListItem Text="-Karnataka" Value="1"></asp:ListItem>
            <asp:ListItem Text="-TamilNadu" Value="2"></asp:ListItem>
            <asp:ListItem Text="-Maharastra" Value="3"></asp:ListItem>
            <asp:ListItem Text="-Kerala" Value="4"></asp:ListItem>
            <asp:ListItem Text="United States" Value="Country"></asp:ListItem>
            <asp:ListItem Text="-Alabama" Value="5"></asp:ListItem>
            <asp:ListItem Text="-Alaska" Value="6"></asp:ListItem>
            <asp:ListItem Text="-California" Value="7"></asp:ListItem>
            <asp:ListItem Text="-Florida" Value="8"></asp:ListItem>
        </asp:DropDownList>


The above jQuery code will disable all the list items that have Country as value and thus making it non selectable.
Happy Coding!!



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 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 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.



European ASP.NET 4 Hosting :: ASP.NET 4 and MySQL Membership Provider

clock September 12, 2011 07:09 by author Scott

Recently I had to setup an ASP.NET MVC 2 project which would utilize the built-in membership of ASP.NET. However, I didn't have access to a MS SQL database, so I had to use a MySQL data provider instead. The following is a quick guide on how to get it setup.

First, you need to download the MySQL Connector/Net from
this page. This makes it possible to connect to MySQL databases from .NET applications and gives you access to the ADO.NET interfaces. I choose to download the latest development release (at the time of writing) Connector/Net 6.3.3 beta, as this fully integrates with Visual Studio 2010 which the latest public release (6.2.3 at the time of writing) does not. Download BOTH the source (mysql-connector-net-6.3.3-src.zip) and the installation file (mysql-connector-net-6.3.3.zip). I will explain why in a second.

Once you've downloaded both files, extract them and install the connector. Now, normally when using the membership provider, the database tables/schemas are automatically created. The MySQL membership provider does this as well, unfortunately it just doesn't do it right. At least it didn't work for me. Instead, you have to create the databases semi-manually. Go to the location where you extracted the source and browse to the following folder "\MySql.Web\Providers\Properties". In this folder you will see a number of .sql files: schema1.sql, schema2.sql, schema3.sql, schema4.sql, schema5.sql and schema6.sql. Run each of these, in turn and starting with schema1.sql, against your MySQL database.

Now, fire up Visual Studio 2010 and open your application. Add a reference to MySql.Web.dll which can be found in the directory you installed the Connector, e.g. C:\Program Files\MySQL\MySQL Connector Net 6.3.3\Assemblies\v2.0

Next, unless you haven’t done this already, add your MySQL connection string to the configuration/connectionStrings element in the Web.config, e.g.:

<connectionStrings> 
    <add name="MySQLConn" connectionString="Server=SERVERADDRESS;Database=DATABASENAME;Uid=USERNAME;Pwd=PASSWORD;"/> 
</connectionStrings> 

Finally, open up your Web.config and add these lines to the <system.web> element:

<membership defaultProvider="MySqlMembershipProvider"> 
  <providers> 
    <clear/> 
    <add name="MySqlMembershipProvider"                   
   
 type="MySql.Web.Security.MySQLMembershipProvider,MySql.Web,Version=6.3.3.0,Culture=neutral,PublicKeyToken=c5687fc88969c44d"   

    autogenerateschema="true" connectionStringName="MySQLConn"   
    enablePasswordRetrieval="false" enablePasswordReset="true"   
    requiresQuestionAndAnswer="false" requiresUniqueEmail="false"   
    passwordFormat="Hashed" maxInvalidPasswordAttempts="5"   
    minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0"   
    passwordAttemptWindow="10" passwordStrengthRegularExpression=""   
    applicationName="/" /> 
  </providers> 
</membership> 

<profile defaultProvider="MySqlProfileProvider"> 
  <providers> 
    <clear/> 
    <add name="MySqlProfileProvider"   
    type="MySql.Web.Profile.MySQLProfileProvider,MySql.Web,Version=6.3.3.0,Culture=neutral,PublicKeyToken=c5687fc88969c44d"   
    connectionStringName="MySQLConn" applicationName="/" /> 
  </providers> 
</profile> 

<roleManager enabled="true" defaultProvider="MySqlRoleProvider"> 
  <providers> 
    <clear /> 
    <add name="MySqlRoleProvider"   
    type="MySql.Web.Security.MySQLRoleProvider,MySql.Web,Version=6.3.3.0,Culture=neutral,PublicKeyToken=c5687fc88969c44d"   
    connectionStringName="MySQLConn" applicationName="/" /> 
  </providers> 
</roleManager> 

Now, you've (hopefully) got a fully working MySQL membership provider. To test it, go to Project > ASP.NET Configuration and go to the Security tab. Here you should be able to manage users and roles.


NOTE: Make sure you enter the correct connectionstring name, version number and PublicKeyToken in the Web.config.



European ASP.NET Hosting :: Create Membership tables in another database than the standard aspnetdb.mdf

clock September 8, 2011 06:55 by author Scott

When you start creating a new ASP.NET 2.0 site with Visual Studio 2005 or Visual Web Developer Express (VWD) and want to start using it you'll notice that a new file in the App_Data folder gets created besides your own database, namely the aspnetdb.mdf file. This extra database holds all the tables and stored procedures to let Membership, Roles, Profile etc run smoothly.

However a problem arises when you don't want to use that dedicated new database when you want to deploy to your live webserver, certainly not when you use a host that only offers one database and charges you extra for another database. Luckely you can control things more when using the dedicated
aspnet_regsql tool that ships with the .NET 2.0 framework.

What I'm about to describe in this article is how to use that tool to generate a SQL script that you can use to run on your other database with a tool like SQL Server Management Studio (SSMS). In this example I'll be using the installed Northwind database on my localhost developer machine.

Just start up a new DOS box by going to Start | Run and type in cmd followed by enter. In Windows Vista you push the blue windows logo button and in the field with the text Start Search you type in cmd followed by ctrl + shift + enter. The reason for that combination is that you must run it under Admin privileges or else the to be generated file doesn't get writed to disk.
A new DOS box will appear and you just navigate to the following directory/folder:

Windows\Microsoft.NET\Framework\v2.0.50727\

If you're not used to using DOS you can navigate to it by typing this in the DOS box: cd \windows\Microsoft.net\framework\v2.0.50727 followed by enter.

Then you type in this line: aspnet_regsql.exe -E -S localhost -d Northwind -A all -sqlexportonly c:\membership.sql again followed by enter. At the location c:\ a new file gets generated: membership.sql.



The Northwind name in the parameter list is later on used to set the db name in the generated sql file: SET @dbname = N'Northwind'

Once generated you can use/tweak this file to be used in SSMS to get executed and to install everything needed in the database.

Ok, up untill now we focussed on getting everything ready on the database side but we also have to let our ASP.NET 2.0 application know that we're pointing out to another database than the default one. The solution for this is to override the default settings for the LocalSqlServer connectionstring which can be found in the machine.config file.

<add name="LocalSqlServer"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />

To override that you open the web.config file in your application which can be normally found in the root of the application. Go to the <connectionStrings> element.


<connectionStrings>
    <remove name="LocalSqlServer"/>
    <add name="LocalSqlServer" connectionString="The connection string to your
                         (new) database" providerName="System.Data.SqlClient" />
</connectionStrings>

Notice the second line where you call the remove statement. This is needed in order to be able to override the LocalSqlServer connection string!

If you're in need of a little help to get your connection string right there's a dedicated site: http://www.connectionstrings.com/.

If you're interested in creating one dedicated database for multiple applications you can also check out Scott Guthrie's post: Configuring ASP.NET 2.0 Application Services to use SQL Server 2000 or SQL Server 2005.



About HostForLIFE.eu

HostForLIFE.eu 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 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in