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



European ASP.NET Hosting :: Changing ASP.net Temporary Files Folder

clock August 30, 2011 06:35 by author Scott

One of my client was having problems with the small space on the C drive on a server machine which was hosting a ASP.net application. There were few errors in the server error about “No enough space”.Though I would say that in ideal situation it would be best to increase the space on the C: drive as most of the other Operating System related applications also reply on the free space on C: drive, when there is no other easy way of increasing the space on C: drive, administrator can relocate the temporary files folder created by ASP.net.

Please note that ASP.net create a compile version of the site and stores it in its default temporary ASP.net folder. This is usually %Windows Install Folder%\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files (For ASP.Net 2.0). This folder can grow very fast in case web server has large ASP.net sites hosted on that server. Fortunately, ASP.net provides a simple way to change this location. This is stored in the web.config file and can defined in the Global web.config (placed at %Windows Install Folder%Microsoft.NET\Framework\v2.0.50727\CONFIG). To change this path add the new full folder path in the Compilation section of the configuration file. Here is a sample of how this looks like (this must be under System.Web section):

<compilation tempDirectory=“E:\ASP.Net Temporary Folder\” debug=“false“>

One can find the documentation of all different sections of ASP.net configuration file at:
http://msdn2.microsoft.com/en-us/library/b5ysx397(VS.71).aspx

In case when Internet is not available, or you just need a quick reference, there is also a small helpful file in the configuration folder. This file is named “web.config.comments” and is in the CONFIG folder of the ASP.net framework folder.



European ASP.NET 4 Hosting :: Error Handling Mechanisms in ASP.NET Application

clock August 29, 2011 17:25 by author Scott

In ASP.NET application we need to consider below factors while creating error handling ability in system

- Show User friendly message in UI
- Log all detail level error
- Log error process should be very simple and generic so there are minimum chances of the error comes in log generation process and that should be easy to accessible to each user.

i.e. if we are storing login in database and error comes related to database connectivity then we never get any kind of logs and also that is difficult to retrieve that log

Show User Friendly message in UI:


Add below tags in your web.config file



Also need to add Errorpage.aspx and pagenotfound.aspx(if required) with user friendly messages.

Log all detail level error

For maintain each error log we need to add below code in global.asax page in Application_Error event.


void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError().GetBaseException();
string PageUrl = Request.Url.ToString();

string strLogFile = Server.MapPath(@"~\ErrorLog\LogFile_" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + ".txt");
ErrorHnadling.ErrorHandling(ex, strLogFile, Request.Form.ToString(), PageUrl);
}

So when ever error occurs this event fires and error is logged.


Error Log Process

We have implemented error log process in Errorhadling class with errorhandling methods with all error details.

We are storing error in text file with predefine web root folder with todays date as naming convention so any time user can access that file data by browsing it by web directory (with predefine name by date)

Below are the class for error handling.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
/* Created By : Amit Patel
* Created Date : 21th Feb 2011
* Description : Error Handling for application level
*/
namespace Common
{
public class ErrorHnadling
{
///
/// Log Exception Log file (log file is maintain based on Date
///

/// Exception Message
/// Log File
/// Request Form name
/// Query String Name
public static void ErrorHandling(Exception ex, string strLogFile, string strFormName, string strQueryString)
{

StreamWriter oSW;
if (File.Exists(strLogFile))
{
oSW = new StreamWriter(strLogFile, true);
}
else
{
oSW = File.CreateText(strLogFile);
}

oSW.WriteLine("================================" + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString() + "================================");
oSW.WriteLine("MESSAGE : " + ex.Message);
oSW.WriteLine("SOURCE : " + ex.Source);
oSW.WriteLine("TARGETSITE : " + ex.TargetSite);
oSW.WriteLine("STACKTRACE : " + ex.StackTrace);
oSW.WriteLine("INNEREXCEPTION : " + ex.InnerException);
oSW.WriteLine("FORM : " + strFormName);
oSW.WriteLine("QUERYSTRING : " + strQueryString);
oSW.Close();
}
///
/// Log Exception Log file (log file is maintain based on Date
///

/// Exception Message
/// Log File
/// Request Form name
/// Query String Name
/// Data for Error Handling (user id or any other session variable
public static void ErrorHandling(Exception ex, string strLogFile, string strFormName, string strQueryString, string strData)
{

StreamWriter oSW;
if (File.Exists(strLogFile))
{
oSW = new StreamWriter(strLogFile, true);
}
else
{
oSW = File.CreateText(strLogFile);
}

oSW.WriteLine("================================" + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString() + "================================");
oSW.WriteLine("MESSAGE : " + ex.Message);
oSW.WriteLine("SOURCE : " + ex.Source);
oSW.WriteLine("TARGETSITE : " + ex.TargetSite);
oSW.WriteLine("STACKTRACE : " + ex.StackTrace);
oSW.WriteLine("INNEREXCEPTION : " + ex.InnerException);
oSW.WriteLine("FORM : " + strFormName);
oSW.WriteLine("QUERYSTRING : " + strQueryString);
oSW.WriteLine("Data : " + strData);
oSW.Close();
}
}
}

Also we have added another method to capture application/session related data. That will help if any specific error comes on special data or specific user.

Hope you will enjoy with code to trace any error in production application.



European ASP.NET 3.5 Hosting :: Using the DataContractJsonSerializer in .NET 3.5

clock August 24, 2011 08:23 by author Scott

In ASP.NET AJAX Extensions v1.0 for ASP.NET 2.0 there is the JavaScriptSerializer class that provides JSON serialization and deserialization functionality. However, in .NET 3.5 the JavaScriptSerializer has been marked obsolete. The new object to use for JSON serialization in .NET 3.5 is the DataContractJsonSerliaizer object. I'm still new to the DataContractJsonSerializer, but here's a summary of what I've learned so far...

Object to Serialize

Here's a simple Person object with First Name and Last Name properties.

public class Person
{
    public Person() { }
    public Person(string firstname, string lastname)
    {
        this.FirstName = firstname;
        this.LastName = lastname;
    }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}


Now in order to serialize our object to JSON using the DataContractJsonSerializer we must either mark it with the Serializable attribute or the DataContract attribute. If we mark the class with the DataContract attribute, then we must mark each property we want serialized with the DataMember attribute.

/// Marked with the Serializable Attribute

[Serializable]
public class Person
{
    public Person() { }
    public Person(string firstname, string lastname)
    {
        this.FirstName = firstname;
        this.LastName = lastname;
    }
    public string FirstName { get; set; }
    public string LastName { get; set; }

}

/// Marked with the DataContact Attribute
[DataContract]
public class Person
{
    public Person() { }
    public Person(string firstname, string lastname)
    {
        this.FirstName = firstname;
        this.LastName = lastname;
    }

    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }
}


Serialization Code

Here's the most basic code to serialize our object to JSON:

Person myPerson = new Person("Scott", "Walker");

/// Serialize to JSON
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myPerson.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, myPerson);
string json = Encoding.Default.GetString(ms.ToArray());


Our resulting JSON looks like this:

/// Result of Person class marked as Serializable
{"<FirstName>k__BackingField":"Scott","<LastName>k__BackingField":"Walker"}


/// Result of Person class marked as DataContract with
/// each Property marked as DataMember
{"FirstName":"Scott","LastName":"Walker"}


As you can see the first serialization with the class marked with the Serializable attribute isn't quite what we were expecting, but is still JSON. This serialization actually isn't compatible with the client-side JSON Serializer in ASP.NET AJAX.

As you can see the second serialization with the class marked with the DataContract attribute is exactly what we were expecting, and is the same JSON that the old JavaScriptSerializer object would have generated. This is the method of JSON serialization using the DataContractJsonSerializer that you'll need to do if you are going to pass the resulting JSON down to the client to be consumed with ASP.NET AJAX.

Deserialization Code

Here's the most basic code to deserialize our object from JSON:

Person myPerson = new Person();

MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myPerson.GetType());
myPerson = serializer.ReadObject(ms) as Person;
ms.Close();


Controlling the property names in the resulting JSON

When using the DataContract and DataMember attributes, you can tell the DataMember attribute the specific name you want that property to have within the JSON serialization by setting its "Name" named parameter.

Here's an example that will give the name of "First" to the "FirstName" property within the JSON serialization:

[DataMember(Name = "First")]
public string FirstName { get; set; }


The resulting JSON looks like this:

{"First":"Scott","LastName":"Walker"}

Here's the code for some Helper methods using Generics to do all the dirty work for you

using
System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

public class JSONHelper
{
    public static string Serialize<T>(T obj)
    {
        System.Runtime.Serialization.Json.DataContractJsonSerializer
serializer = new
System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
        MemoryStream ms = new MemoryStream();
        serializer.WriteObject(ms, obj);
        string retVal = Encoding.Default.GetString(ms.ToArray());
        ms.Dispose();
        return retVal;
    }

    public static T Deserialize<T>(string json)
    {
        T obj = Activator.CreateInstance<T>();
        MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
        System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
        obj = (T)serializer.ReadObject(ms);
        ms.Close();
        ms.Dispose();
        return obj;
    }
}

/// Our Person object to Serialize/Deserialize to JSON
[DataContract]
public class Person
{
    public Person() { }
    public Person(string firstname, string lastname)
    {
        this.FirstName = firstname;
        this.LastName = lastname;
    }

    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }
}


What Assembly References does my application need for this?

From the namespace that contains DataContractJsonSerializer you can probably tell that you need to add a reference to the System.Runtime.Serialization assembly. However, you also need to add a reference to the System.ServiceModel.Web assembly.



European ASP.NET 4 Hosting :: How to Integrate Google Maps with ASP.NET Page

clock August 8, 2011 08:16 by author Scott

This tutorial will describe how to integrate google maps to ASP.NET page.

1. Register Google Maps API key

You can download it from here
http://www.google.com/apis/maps/

2. Download the SubGurim Google Maps wrapper dll

Then, you need to download google maps wrapper at
http://en.googlemaps.subgurim.net/descargar.aspx.

3. Set up your aspx page

This is for the example:

<p style="text-align:right; margin-right:300px">
    Street Address:
    <asp:textbox ID="txtStreetAddress" runat="server" Width="150px" /><br />
    Suburb:
    <asp:textbox ID="txtSuburb" runat="server" Width="150px" /><br />
    Country:
    <asp:textbox ID="txtCountry" runat="server" Width="150px" /><br /><br />
    <asp:Button Text="Show Map" ID="lnkShowMap" runat="server" />
</p>

You need to add your Google API key to your web.config file like so:

<appSettings>
    <add key="googlemaps.subgurim.net" value="YourGoogleMapsAPIKeyHere" />
</appSettings>

And finally, you need to register the SubGurim wrapper at the top of your page (or in your web.config if you have a number of pages that display maps):

<%@ Register Assembly="GMaps" Namespace="Subgurim.Controles" TagPrefix="cc1" %>

4. Add code to display the map

Protected Sub lnkShowMap_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        Handles lnkShowMap.Click
    Dim strFullAddress As String
    Dim sMapKey As String =
    ConfigurationManager.AppSettings("googlemaps.subgurim.net")
    Dim GeoCode As Subgurim.Controles.GeoCode

    ' Combine our address fields to create the full address.  The street,
    ' suburb and country should be seperated by  periods (.)
    strFullAddress = txtStreetAddress.Text & ". " & txtSuburb.Text
        & ". " & txtCountry.Text

    ' Work out the longitude and latitude
    GeoCode = GMap1.geoCodeRequest(strFullAddress, sMapKey)
    Dim gLatLng As New
Subgurim.Controles.GLatLng(GeoCode.Placemark.coordinates.lat,

        GeoCode.Placemark.coordinates.lng)
    ' Display the map
    GMap1.setCenter(gLatLng, 16, Subgurim.Controles.GMapType.GTypes.Normal)
    Dim oMarker As New Subgurim.Controles.GMarker(gLatLng)
    GMap1.addGMarker(oMarker)
End Sub

Done.  Great JOB.



European ASP.NET 4 Hosting :: Repeater within ASP.NET 2.0 Gridview

clock August 1, 2011 06:48 by author Scott

This article and code snippet here shows how to bind a repeater control and Gridview control to a relational data so the GridView and the Repeater control show related data.

Inserting a Repeater within Gridview is an easy task but to bind the headline in the GridViewand data items correspond to the particular head line into a Repeater control is a little bit trickier job. According to a requirement, I have to bind company name as headline and top four news of the company as its data items under the headline, again next company name and top four news of respective company and so on.

Here, I have to use a repeater control to bind news while I am binding company name in grid view. We can also make the company name as link button which on click, will navigate to corresponding page. For this we have to pass navigate URL for a company dynamically. We can do this by writing code in OnRowDataBound event of gridview. We can also make news row as link.

Mechanism

Take a GridView control and set its AutoGenerateColumns="False".  Put a label control within the GridView to bind company name. You can also use its BoundField.

Now, within the same ItemTemplate, place a repeater control and put one more label control within this repeater control to bind news of respective company. If you are using different ItemTemplate, then it will bind in another column, otherwise it will bind in the same column but in different rows as shown in fig. below.

Now it is your choice, whether you are interested to bind in same or different column. Here, I have used div tag, to separate company and their news rows. The div tag gives one more advantage i.e. we can apply CSS to a particular div for richer UI.

The complete source code is here.

      <div style="width:400px; font-family:Arial; font-size:small">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="100%" GridLines="None">
            <Columns>
                <asp:TemplateField>
                <ItemTemplate>
                    <div style="color:Blue;font-weight:bold">
                        <asp:Label ID="Label1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"compname") %>'></asp:Label>
                    </div>
                    <asp:Repeater ID="Repeater1" runat="server" DataSource='<%#DataBinder.Eval(Container, "DataItem.InnerVal") %>'>
                    <ItemTemplate>
                    <div style="padding-left:20px; padding-top:5px">
                        <asp:Label ID="Label2" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"news") %>'></asp:Label>
                    </div>
                   
                    </ItemTemplate>
                    </asp:Repeater>
                    <div style="text-align:right">
                        <asp:HyperLink ID="link" runat="server">More</asp:HyperLink>
                    </div>
                </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>

It is obvious that we have to write some code in code behind to get the data from database.

I have used a stored procedure that returns two tables, i.e. for company name and news section. 

Now I am making a relation between these two tables in a DataSet, with column 'compname'.  And finally, binding the data in data controls.  

Here is the code on the page load event handler. As you can see from the binddat method, I get data in a DataSet from the database, sets a relation and sets the DataSource property of the GridView control to the DataSet. Rest data binding is done in the above ASP.NET code.

       protected void Page_Load(object sender, EventArgs e)
    {
        binddata();
    }

    // Function to bind data in data controls..
    public void binddata()
    {
        string str = "Data Source=VS-NAVINCHANDRA\\SQLEXPRESS;Initial Catalog=dbNavin;Integrated Security=SSPI"; // your connection string here
        SqlConnection con = new SqlConnection(str);
        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter("getCompNews", con); // name of your stored procedure,
        da.Fill(ds);

        ds.Relations.Add("InnerVal", ds.Tables[0].Columns["compname"], ds.Tables[1].Columns["compname"]);   // making a relation between two tables.
        GridView1.DataSource = ds.Tables[0];
        GridView1.DataBind();
    }

On clicking 'More' link button, it should redirect to page which shows all the news of that particular company. So, we have to set NavigateUrl property for this control dynamically. To do this, write the code given below. As I have passed company name in query string, you can very easily access respective company data from your table to display.

      protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HyperLink lnkMore = (HyperLink)e.Row.FindControl("link");
            Label lbl=(Label)e.Row.FindControl("Label1");
            lnkMore.NavigateUrl = "~/Company.aspx?cmp="+lbl.Text;
        }
    }

As I have mentioned for stored procedure, so you must create a stored procedure that returns tables. If you don't want to create it, just copy and paste the stored procedure given below and compile it. Make sure that your database contains all tables and respective columns.

      Create Procedure [dbo].[getCompNews]

               as
               begin
               create table #Temp
              (
               compname varchar(50),
               news varchar(150)
               )

               Insert into #Temp
               select a.compname, b.news from Company as a
               inner join  CompNews as b on a.CompId=b.CompId order by compname
 
              
Select distinct compname from #Temp
               select * from #Temp
               end
               drop table #Temp

Here I am using stored procedure instead of using direct sql query. Offcourse a stored procedure is much better than a query.



European ASP.NET 4 Hosting :: How to Create Custom Objects in ASP.NET 4.0 with C#

clock July 28, 2011 05:38 by author Scott

In this tutorial, we will be creating our own class that will represent a Person object, which we will store in a database. Within this class, we will create custom properties and methods to interact with that object. We will also show you how to use a collection class to group together these objects and handle them with ease.

To get started, we will create a new web application in Visual Studio. We will be working primarily with the Default.aspx page and a .cs file. So let us begin by adding the Class. Right-click the App_Code folder in the Solution Explorer (if you do not see it, right-click your solution and choose Add ASP.NET Folder > App_Code), and then choose Add New Item… We want to add a new Class; name it People.cs and click Ok. We should get something like this:

using
 System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
/// <summary>
/// Summary description for People
/// </summary>
public class People
{
public People()
{
//
// TODO: Add constructor logic here
//
}
}


First, let’s wrap the Class in a namespace. This makes it easier for us to keep our code together, especially when building bigger applications and grouping multiple classes in one namespace. Then rename the Class to Person – People will be the wrapper namespace; Person will be the class.

namespace
 ProgrammingHelp.People
{
    public class Person
    {
 
    }
}


The next thing to do will be to create the default constructor for the Class and set the Properties. The default constructor (public Person()) will instantiate an empty Person object, when called. It will look like this:

public Person()
{
}

We can wrap our Properties in a #region. We will need to specify all properties of our object, and set the default values and data types. We do this as follows:


#region properties
 
        /// <summary>
        /// Gets or sets PersonID. [Default value is 0].
        /// </summary>
        public Int32 PersonID
        {
            get
            {
                return _PersonID;
            }
            set
            {
                _PersonID = value;
            }
        }
        private Int32 _PersonID = 0;
 
        /// <summary>
        /// Gets or sets the First Name of the Person. [Default value is ''].
        /// </summary>
        public String FirstName
        {
            get
            {
                return _FirstName;
            }
            set
            {
                _FirstName = value;
            }
        }
        private String _FirstName = "";
 
        /// <summary>
        /// Gets or sets the Last Name of the Person. [Default value is ''].
        /// </summary>
        public String LastName
        {
            get
            {
                return _LastName;
            }
            set
            {
                _LastName = value;
            }
        }
        private String _LastName = "";
 
        /// <summary>
        /// Gets or sets the City of the Person. [Default value is ''].
        /// </summary>
        public String City
        {
            get
            {
                return _City;
            }
            set
            {
                _City = value;
            }
        }
        private String _City = "";
 
        /// <summary>
        /// Gets or sets DateTime the Person was added. [Default value is the current Date/Time].
        /// </summary>
        public DateTime DateTimeAdded
        {
            get
            {
                return _DateTimeAdded;
            }
            set
            {
                _DateTimeAdded = value;
            }
        }
        private DateTime _DateTimeAdded = DateTime.Now;
 
        /// <summary>
        /// Gets or sets the Age of the Person. [Default value is 0].
        /// </summary>
        public int Age
        {
            get
            {
                return _Age;
            }
            set
            {
                _Age = value;
            }
        }
        private int _Age = 0;
 
        #endregion

Notice we make the Properties public so that we can reference them outside of the class, and we set the defaults within the class, using Private. We also want to create a constructor that will instantiate a usable object. We can create many constructors that take various overloads. Let us start with the first, which will be used to build the object using a SqlDataReader. First, we will create a method that the constructor will use to parse the DataReader and set the object with the values:

private void SetObjectData(SqlDataReader theObjReader)
        {
           this._PersonID = Convert.ToInt32(theObjReader["PersonID"]);
           this._FirstName = theObjReader["FirstName"].ToString();
           this._LastName = theObjReader["LastName"].ToString();
           this._City = theObjReader["City"].ToString();
           this._Age = Convert.ToInt16(theObjReader["Age"]);
           this._DateTimeAdded = Convert.ToDateTime(theObjReader

         ["DateTimeAdded"]);
        }

We place all the Class’s methods below the Properties, and can use another #region to group them together. The SetObject method takes a parameter of a SqlDataReader, which is then used to set the properties of the object, using the correct data types as specified in the Properties. Now we can call this method using a constructor like so:


public Person(SqlDataReader theObjReader)
{
   SetObjectData(theObjReader);
}

This constructor will be used to build an object from a SqlDataReader. When this constructor is called, a SqlDataReader must be passed, and a Person object will be returned. However, we’re not always going to be able to use a SqlDataReader to build an object from. This constructor will be mainly used for internal methods, when retrieving records from the database and returning an object, for example:

A more common constructor to use would be one that takes the parameter of the object ID. This way, we can take that ID, pull the corresponding record from the database and then return the object. To do this, let’s add our database. Right-click the App_Data folder in Solution Explorer, then choose to Add New Item.. SQL Server Database. Give it a name and hit OK. Once opened, we want to create a new table People. We can do this straight in the Visual Studio environment using Server Explorer:



We will create the same columns as our Class Properties, with similar types – PersonID will be bigint; FirstName varchar(50); Age smallint, and DateTimeAdded datetime for example. Once saved, you can right-click the table and choose to Show Table Data. This will allow you to enter some sample data to test with. Add a test record or two.

In this example, we are going to illustrate how to use a custom class to make use of collections of data. Going back to our class, we will make a collection class of the existing Person class, which we can call People. To do this, we need to create a new class outside of the Person class, but within the namespace, and we need to inherit from the CollectionBase class. First thing to do is to make sure we have the following reference at the top of our code and declare the class like so:


using System.Collections;
//And the class we will be declaring

[Serializable]
public class People : CollectionBase
{
}

Now, similar to our Properties of the Person class, we will add Properties and Methods of the collection class:

[Serializable]
public class People : CollectionBase
{
    public int TotalRecords
    {
        get
        {
            return _TotalRecords;
        }
        set
        {
            _TotalRecords = value;
        }
    }
    protected int _TotalRecords = 0;
 
    public int Add(Person thePerson)
    {
        this.TotalRecords++;
        return List.Add(thePerson);
    }
 
    public void Insert(Int32 index, Person thePerson)
    {
        List.Insert(index, thePerson);
    }
 
    public void Remove(Person thePerson)
    {
        List.Remove(thePerson);
    }
 
    public bool Contains(Person thePerson)
    {
        return List.Contains(thePerson);
    }
 
    public int IndexOf(Person thePerson)
    {
        return List.IndexOf(thePerson);
    }
 
    public void CopyTo(Person[] array, int index)
    {
        List.CopyTo(array, index);
    }
 
    public Person this[int index]
    {
        get
        {
            return (Person)List[index];
        }
        set
        {
            List[index] = value;
        }
    }
}

Because we are inheriting from the CollectionBase class, a lot of the functionality is already there – we are simply customizing it for our Person class. Now to demonstrate how this works, we will create a method in our Person Class that will get all records (People) from the database, and return them in a People collection. So the method will look something like this:

public static People GetAllPeople()
{
People PeopleCollection = new People();
SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
try
{
SqlCommand cmd = new SqlCommand("sp_GetAllPeople", connection);
cmd.CommandType = CommandType.StoredProcedure;
 
connection.Open();
SqlDataReader objReader = cmd.ExecuteReader();
while (objReader.Read())
{
Person newPerson = new Person(objReader);
PeopleCollection.Add(newPerson);
}
objReader.Close();
connection.Close();
}
catch
{
connection.Close();
}
return PeopleCollection;
}

Notice that although they are two separate classes, we have full access to the People collection from the Person class. This is because they both reside in the same namespace. So we start by declaring an empty People collection, then define our connection string. Next, we use a try..catch to attempt to execute the Stored Procedure to retrieve all records from the database. Our Stored Procedure looks something like this:

ALTER PROCEDURE dbo.sp_GetAllPeople
 
AS
 
SELECT FROM People

Once the Stored Procedure is executed, we check to see if any records are returned, and if so, we call the Person constructor to set the new object with the SqlDataReader, and then add it to the new collection. Finally, once all records have been processed, we close the connection and the method will return the People collection it just built. The great thing about collections, is that we can assign them to the DataSource of ASP.NET Controls and their Properties can be used directly. For example, we will use this method to assign the collection to a Repeater’s DataSource, then display the Properties on the page. To do this, move to the Default.aspx page and add a Repeater control like so:

<asp:Repeater ID="repeater_People" runat="server">
            <HeaderTemplate>
                <table width="600">
                <tr>
                    <th width="100">ID</th><th width="150">Name</th>
                    <th width="100">City</th><th width="100">Age</th>

                    <th width="150">Added</th>
                </tr>
            </HeaderTemplate>
            <ItemTemplate>
                <tr>
                    <td><%# Eval("PersonID"%></td>
                    <td><%# Eval("FirstName"%> 

<%# Eval("LastName"%></td>
                    <td><%# Eval("City"%></td>
                    <td><%# Eval("Age"%></td>
                    <td><%# Eval("DateTimeAdded"%></td>
                </tr>
            </ItemTemplate>
            <FooterTemplate>
                </table>
            </FooterTemplate>
        </asp:Repeater>

Notice we are using the Property names to display to the page. We can assign the collection on page load, but first, we must remember to add the reference to the namespace then we can reference the method to get all People, and assign it to the repeater.

using ProgrammingHelp.People;
 
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindRepeater();
            SetDropDown();
        }
    }

Now if you run the page, the repeater should display the contents of your database table. This may seem like the long way around getting a few items to display in a repeater, and it is. Custom Objects, however, are extremely useful when using larger amounts of data across multiple pages.


Success!



ASP.NET 4 Hosting - ASPHostPortal :: ASP.NET 4.0 Web Forms Model

clock July 21, 2011 06:03 by author Scott

ASP.NET 4.0 platform is built up with various components Web Forms,ASP.NET MVC, Dynamic Data Controls and ASP.NET AJAX. It has the same foundation as in ASP.NET 3.5 SP1 but refined the above features. This post speaks about features in the Web Form model.

ASP.NET 4.0 features are nothing new, all are in 3.5 but this version gives more control over frequently used features.

Example: ASP.NET 4.0 Web Forms give developers more control over viewstate management, generation of Control ID’s, and HTML generated by some template based controls.

Control Over the Viewstate

Every developer knows that ASP.NET Viewstate burdens the page and waste of bandwidth. Same developers welcomed the ASP.NET MVC because of its complete absence of viewstate. If you ignore the viewstate on your page then you need to reload the data from server to controls.

The Viewstate is functional to Web Forms model, as it caches the contents from cache for control in the page.The overlooked feature is we can turnoff the viewstate for the page or control.The viewstate support is turned on for each page by default. The property EnableViewstate is defined is System.Web.UI.Control class and can be used to turn it on or off.

You can turn off the viewstate for ASP.NET page either declaratively or programmatically during the page’s life cycle.

void Page_Load(object sender,EventArgs e)
{
//Disable viewstate for the page and all of its child controls

this.EnableViewState = false;

....

}

Viewstate setting in ASP.NET has hierarchical nature, which means if the viewstate is enabled on the parent control, it can not be disabled on any of its child controls. You can disable the viewstate at page level and enable it in control level wherever it required.

ASP.NET 4.0 feature is you can enable viewstate at control level. In ASP.NET 4.0, the System.Web.UI.Control class exposes a new property named ViewStateMode:

public virtual ViewStateMode {get; set; }

ViewStateMode enumeration has the following values

Value

Description

Inherit

Inherits the value of ViewStateMode property from the parent control

Enabled

Enables viewstate for this control even if the parent control has set the viewstate property disabled.

Disabled

Disables viewstate for this control even if the parent control has set the viewstate property enabled.


Auto-Generated IDs

It is possible that rendered HTML can contain the same ID. When search for an element using getElementById, you will simply get an array of elements.Most data-bound controls generate their output by repeating the HTML for every data-bound item.


The sample generated Id string look like the following

ctl00$ContentPlaceHolder2$Gridview11$TextBox1

First issue might be with the length of the string, which repeated for several elements, makes the downloaded larger. Predicting the ID of a given control from script is difficult.

A frequently used technique for the above issue is

var btn = document.getElementById("<%=Button1.ClientID %> ");

ASP.NET 4.0 supports another option for autogenerated ids problem and developer can has greater control over generating the clientid of a control.

The System.Web.UI.Control Class now has a brand new property named ClientIDMode.

The ClientIDMode property values can be

Value

Description

Legacy

Indicates that ID should be generated as in earlier versions of ASP.NET

Static

ASP.NET doesn’t make any attempt to scope the client ID. The ID is assigned as-is.

Predictable

The ID is obtained by simply concatenating the ID of parent controls and ignoring master page’s parent elements.

Inherit

The control will use the same algorithm as its parent.


Consider the following code:

<asp:GridView ID="GridView1" runat="server"
              ClientIDMode = "Predictable"
              RowClientIdsuffix="CustomerID">
  ......

</asp:GridView>

In this case, each row of the grid is identified by one or more columns in the data source with a trailing index. Example

Panel1_GridView1_ALFKI_1

Finally, note that the ClientIDMode property affects only the ID attribute of the resulting HTML.

HTML Enhancements

In the early version of ASP.NET developer didn’t have much control over programmatically accessing the HTML tags of a Web Page.


In ASP.NET 4.0, the Page class exposes two new string properties to set some common tags in the <head> section of a page. The two properties are Keywords and Description. The Keywords and Description properties can also be set directly as attributes of the @Page directive as shown below

<%@ Page Language="c#"
    AutoEventWireup="true"
    CodeFile="Default.aspx.cs"
    Inherits="_Default"
    Keywords="ASP.NET, AJAX "
    Description="ASP.NET 4.0 WebForms" %>

Conclusion

ASP.NET 4.0 Web Forms contains a number of features that together can make it a bigger development platform. It is moreover a refinement of existing features.



European ASP.NET 4 Hosting :: How to Extend ASP.NET Web Pages - Create Your Own Helpers

clock July 20, 2011 05:54 by author Scott

The Beta1 version of WebMatrix comes with a number of Web Pages helpers to make your life simple. These include helpers to work with file uploading, images, email, caching, grids, Twitter feeds and a lot more. I suspect that as the product evolves towards full release, more will be added. Nevertheless, the developers of WebMatrix and Web Pages cannot anticipate every requirement, so there will be a time when you feel you need something extra. Adding your own helpers is quite easy, as this article shows.

One area where there is no helper currently is consuming RSS feeds. So I am going to build a helper that allows the user to display part of an RSS feed on a web page. The code that I will show here does the job, although it is far from perfect. Its purpose is to illustrate the main points involved in creating a helper, and not to be a production-ready example of how to produce an Rss reader. It lacks far too much exception handling for one thing, and I felt that adding too much would obscure the main thrust of this article. For that reason, I won't delve too deeply into the actual helper code, but I will draw attention to the key areas that should be considered when developing helpers.

The first thing to do is to add a new folder to the web site. This folder must be named "App_Code". Future versions of WebMatrix may offer this in something like an "Add New ASP.NET Folder" menu option at some stage, but that's not currently available.
App_Code is a special folder. ASP.NET will compile anything inside this the first time the site is run, and it will be available to other code throughout the site. Within that folder, add a new file. The type of file is a C# class file.



Call this file "RssReader.cs", and then remove all the code that's in it, then replace it with the following:

using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;

public static class RssReader
{
  public static HtmlString GetHtml(string url, int numberOfItems = 5,
                        bool showDescription = true, bool showDateCreated = true, int width = 300)
  {
    TagBuilder divTag = new TagBuilder("div");
    TagBuilder pTag = new TagBuilder("p");
    TagBuilder anchor = new TagBuilder("a");   

    var doc = XDocument.Load(url);
    XNamespace a10 = doc.Root.GetNamespaceOfPrefix("a10");
    var items = doc.Descendants("item").Select(feed => new
    {
      Title = feed.Element("title"),
      Link = a10 != null ? feed.Element(a10 + "link").Attribute("href").Value : feed.Element("link").Value,
      Date = feed.Element("pubDate"),
      Description = feed.Element("description")
    }).Take(numberOfItems);

    divTag.MergeAttribute("id", "rssDiv");
    divTag.MergeAttribute("style", "width:" + width + "px");
    foreach(var item in items)
    {
      anchor.InnerHtml = item.Title.Value;
      anchor.MergeAttribute("href", item.Link);
      pTag.InnerHtml = anchor.ToString();
      divTag.InnerHtml += pTag.ToString();
      if(showDateCreated)
      {
        TagBuilder pTag2 = new TagBuilder("p");
        DateTime dateValue;
        if(DateTime.TryParse(item.Date.Value, out dateValue))
        {
          pTag2.InnerHtml = dateValue.ToString("G");
        }
        divTag.InnerHtml += pTag2.ToString();
      }
      if(showDescription)
      {
        TagBuilder pTag3 = new TagBuilder("p");
        pTag3.InnerHtml = item.Description.Value;
        divTag.InnerHtml += pTag3.ToString();
      }
    }
    return new HtmlString(divTag.ToString());
  }
}

Right - before you pass out, let me explain how this code works. It's simple, really. The first 5 lines make certain namespaces available to the code so that when we reference items within them, we do not have to use their fully qualified name. You can see public static HtmlString near the beginning of the code. The fully qualified reference for HtmlString
is System.Web.Mvc.HtmlString, and without adding a using statement to make System.Web.Mvc available to the class file, we would have to type the fully qualified name every time we wanted to reference HtmlString. System.Web.Mvc also makes TagBuilder available in a short-handed fashion too.

You should also note that both the RssReader class and the GetHtml method are static. This means we do not have to create an instance of RssReader in order to call the GetHtml method from a web page or other code. This is typical of helper methods, and other utility methods in general.

The parameters for the GetHtml method are worth noting too. The first one is a required parameter. In other words, when the GetHtml method is called, you must pass a string as an argument. Ideally, that string will be a valid Uri pointing the the location of an RSS feed. There's no checking in the method to make sure it is. This is one of the missing pieces of exception management I mentioned earlier. The other 4 parameters are all optional. In other words, the caller does not need to provide any values for them. You can see they are optional as they have default values.
Optional parameters were added in C# 4.0, and are a terrific way to add flexibility without the need for creating multiple overloaded versions of the GetHtml method. Optional parameters must always be declared AFTER all required parameters (except for one case involving params arrays, but that's not important here).

The next thing of note is the 3 TagBuilder objects that are created. TagBuilder is a very useful class introduced with ASP.NET MVC if you ever want your helper to render html elements, along with HtmlString. TagBuilders allow you to specify an html tag such as a <p> for paragraph, or <input type="text" />, without having to fiddle around with building the string manually, which can be error prone, especially when trying to deal with embedded double quotes. HtmlString ensures that the resulting concoction of tags and html are rendered as html, rather than being html-encoded.

The RSS feed is obtained via the XDocument.Load() method, which is part of System.Xml.Linq. I'm not going to go into too much detail about
Linq To XML but it is a nice way to deal with XML, which is what an RSS feed is, once you get to grips with the basics of the subject (which I hope to do one day...). Suffice to say that assuming the Load method actually managed to retrieve the XML file (again, error checking should be in place there) some items are retrieved from it and used to build a collection of objects. How many objects are built depends on the value passed in to the numberOfItems parameter. If no value was provided, it will default to 5 items.

Now that we have a collection of objects, they are iterated through to build some html. The resulting RSS feed will be housed in a div element, with a width of 300px by default. This can be customised by the user if they choose to pass a value into the method. While iterating the collection, the code builds an html link from the item's Link property, and puts that into a paragraph element. Then it checks ot see if the caller decided to include the published date in their RSS Reader. If they did, or left the default value, this is added to another paragraph element. Finally if the showDescription value is true, item descriptions are added to another paragraph, before looping to the next item in the collection. Finally, the whole lot is returned to the caller as a string of Html.

Before showing how this code can be used in a cshtml file, I will take a second to review the key points about constructing helpers:

1. App_Code is the place for class files which need to be made available across the site
2. Helper classes and methods should invariably be static
3. HtmlStrings ensure that anything to be rendered by the browser is sent as Html
4. TagBuilders make building valid Html a lot easier
5. Optional parameters save a lot of code by reducing the need to create overloaded methods

Here are a couple of ways in which the helper can be called within a Web Pages file:

@RssReader.GetHtml("http://dotnet4europeanhosting.hostforlife.eu/rss")

@RssReader.GetHtml("http://dotnet4europeanhosting.hostforlife.eu/rss/", showDescription: false, width: 400, numberOfItems: 10)

The first line makes use of all default values applied to the optional parameters, while the second one changes the number of items to 10, increases the width of the housing div, and elects not to display descriptions. It leaves the helper to show the date. You should also notice that the optional parameters arguments are prefixed by the name of the parameter, and are not added to the method call in the order in which they appear in the method parameter list itself. Named parameters was also introduced in C# 4.0, and the link to Optional parameters provided earlier explains more about this too.



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