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



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 2012 Hosting, ASP.NET 4.5 Hosting, ASP.NET MVC 4 Hosting, ASP.NET MVC 5 Hosting and SQL 2014 Hosting.


Tag cloud

Sign in