Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, March 27, 2017

Efficient way of performing filtering, sorting and pagination with MongoDB C#

Problem: I run into issue where pagination was bringing almost all the rows from the collection and then doing pagination.  In other words it is doing in memory pagination which is inefficient.  Recommendation:  In order to do MongoDB pagination: avoid using LINQ Query.

Solution:
With following way you can easily and efficiently do filtering, sorting and pagination on mongoDB collection.  Below code snippet will bring back only records which are required.  Example:  If pageSize is 10 it will only bring back 10 records.  This code is tested on over 12 million records and it is working efficiently.  I am open for any comment/suggestion to make it more robust.

Note:  It uses predicate way of writing lambda expression.

C# code for filtering, sorting and pagination on MongoDB Collection

//Get MongoDB Collection
var collection = database.GetCollection("Member");


//Query the collection with criteria formed as lambda expression.
var filter = Builders
                 .Filter
                 .Where
                   (
                          a => a.City == "Ahmedabad" &&
                          a.DateOfBirth < DateTime.Now.AddYears(-18)
                    );


//Build sort definition based on your need
var sort = new SortDefinitionBuilder()
                       .Descending(x => x.DateOfJoin);


//Apply Pagination and return back list of records.
var resultSet = collection
                     .Find(filter)
                     .Sort(sort)
                     .Skip(pageSize * (currPage - 1))
                     .Limit(pageSize).ToList();


Sunday, May 02, 2010

Tweet Posting from Asp.net using OAuth - Twitterizer Tutorial

Twitter Tweet Posting from Asp.net Web Application using OAuth.

Main Steps
1) Create Twitter Application.
2) Post Tweet from Asp.net Website using Twitterizer Api

Now, lets understand each steps in more details, step by step.

Create Twitter Application
1) Open http://twitter.com/apps/new
2) Login to twitter and Fill the Application Information as follow.























 - Choose Image for your Twitter Application.
 - Fill in Twitter Application Name.
 - Description of Twitter Application
 - Fill in Application Website name, Organization























- Choose Application Type as "Browser" as we are developing asp.net website to post tweet.
- Callback Url is url where twitter would redirect after authentication.
    - Fill in rest of details as shown in figure and your Twitter Application is ready to use.























Now, lets begin the important part, how to post tweet.

Post Tweet from Asp.net Website using Twitterizer Api
1) Create Asp.net Application
2) Download Twitterizer
3) Add Reference of Twitterizer.dll files to newly created asp.net web application
4) Copy Consumer Key and Consumer Secret generated from Twitter Application.
5) Add Consumer Key and Consumer Secret to web.config file inside AppSettings

    
    

6) In .aspx page arrange the controls as shown in figure.















7) Paste following code in "Authenticate User" Button Click event

protected void btnAuthenticate_Click(object sender, EventArgs e)
{
    // add these to web.config or your preferred location
    var consumerKey = ConfigurationManager.AppSettings["consumerKey"];
    var consumerSecret = ConfigurationManager.AppSettings["consumerSecret"];
    
    //If User is not valid user
    if (Request.QueryString["oauth_token"] == null)
    {
        //Step 1: Get Request Token
        OAuthTokenResponse RequestToken 
= OAuthUtility.GetRequestToken(consumerKey,                                                 consumerSecret);

        //Step 2: Redirect User to Requested Token
        Response.Redirect("http://twitter.com/oauth/authorize?oauth_token=" 
+ RequestToken.Token);
    }
    else
    {
        //For Valid User
        string Oauth_Token = Request.QueryString["oauth_token"].ToString();
        var accessToken = OAuthUtility.GetAccessToken(consumerKey,
                                              consumerSecret,
                                              Oauth_Token);

        lblMessage.Text = "Hello " 
+ accessToken.ScreenName 
+ ", Welcome to Go4Sharepoint.com Twitter App";

        lblMessage.Text += "
Token: "
+ accessToken.Token; lblMessage.Text += "
TokenSecret: "
+ accessToken.TokenSecret; lblMessage.Text += "
UserId: "
+ accessToken.UserId; } }

8) Now run the application and try to click on "Authenticate User" button, it will redirect you to twitter website authenticate user and return back to your asp.net website.


















Click on Authenticate User button.













Press on Allow button after you enter your twitter login account details




















9) Create OAuthToken Object and Post Tweet.
protected void btnPostTweet_Click(object sender, EventArgs e)
{
    // add these to web.config or your preferred location
    var consumerKey = ConfigurationManager.AppSettings["consumerKey"];
    var consumerSecret = ConfigurationManager.AppSettings["consumerSecret"];
    
    OAuthTokens accessToken = new OAuthTokens();
    accessToken.AccessToken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    accessToken.AccessTokenSecret = "xxxxxxxxxxxxxxxxxxxx";
    accessToken.ConsumerKey = consumerKey;
    accessToken.ConsumerSecret = consumerSecret;

    TwitterStatus TweetStatus = new TwitterStatus(accessToken);
    TweetStatus.Update(txtTweet.Text + " - http://www.Go4Sharepoint.com");                        
}

10) Type in your Message and Press "Shout on Twitter" button























Now, check your twitter account (Example here: http://twitter.com/aspnetmvp )

















Check out Live Demo of Tweet Posting from Asp.net

Sunday, October 11, 2009

DataView.Table - Problem to Persist Sort or Filter View

I was trying to Sort data with DataView and was trying to convert Dataview to table. I have notice even though view is sorted, when you try to convert it to table it would return only default sort.


Example:
//I was trying to perform something as following
DataTable dtGrid = GetData();
DataView dvSort = new DataView(dtGrid);
dvSort.Sort = "CreationDate DESC";
dtGrid = dvSort.Table; //Will Not Persist Sort Order

In above example even though view is in sorted order, when i tried to convert it to table it would return only default view. In order to get Sorted view (Persist Sort order) instead of using DataView.Table you should use DataView.ToTable() method

So if you changed above code with following it would start working as expected.

DataTable dtGrid = GetData();
DataView dvSort = new DataView(dtGrid);
dvSort.Sort = "CreationDate DESC";
dtGrid = dvSort.ToTable(); //Persist Sort Order

Monday, January 19, 2009

VS.Net 2010 Videos and Features

VS.Net 2010 and .Net FX 4.0 Videos

VS.Net 2010 Features Overview
- Visual Studio 2010 Overview, Jason Zander
- Key Themes for Visual Studio 2010, Soma
- Lab Management in Visual Studio Team System 2010

Languages Day
- C# 4.0 Implementation and Design Questions, Anders Hejlsberg
- VB 10, Lucian Wischik- C++ 10: 10 is the new 6, Amit Mohindra

The IDE
- Being Code-Focused with Visual Studio 2010, Karen Liu
- Test-Driven Development and Visual Studio 2010, Karen Liu
- Future of Visual Studio Extensibility, Rico Mariani

Concurrency and Parallelism
- Parallel Extensions to the .NET Framework 4.0, Stephen Toub
- Parallel Patterns Library (Native Parallelism), Rick Molloy
- Parallel Debugging Tools in Visual Studio 2010, Daniel Moth

Web Tools
- Sharepoint Development with Visual Studio 2010, Reza Chitsaz
- Web Development and Deployment with Visual Studio 2010, Vishal Joshi

Wednesday, December 10, 2008

Reflection in C# - List of Class Name, Method Name

Reflection is way through which we can identify metadata about assembly runtime.
Example: We have a .Net Assembly file (.dll file), which consist of 2 Class Definition and 10 Method Names, We can get information about classes and method name list through reflection.

Few Examples of Reflection

Loading Assembly FileAssembly assem = Assembly.LoadFrom(sAssemblyFileName);

Get List of Class Name.
Type[] types = assem.GetTypes();

Get List of Method Name


foreach (Type cls in types)
{
try
{
//Add Namespace Name
arrl.Add(cls.FullName);

//Add Class Name
if(cls.IsAbstract)
arrl.Add("Abstract Class:" + cls.Name.ToString());
else if(cls.IsPublic)
arrl.Add("Public Class:" + cls.Name.ToString());
else if(cls.IsSealed)
arrl.Add("Sealed Class:" + cls.Name.ToString());


MemberInfo[] methodName = cls.GetMethods();
foreach (MemberInfo method in methodName)
{
if (method.ReflectedType.IsPublic)
arrl.Add("\tPublic - " + method.Name.ToString());
else
arrl.Add("\tNon-Public - " + method.Name.ToString());
}
}
catch (System.NullReferenceException)
{
Console.WriteLine("Error msg");
}
}


A Sample Application Showing Good Usage of Reflection in .Net
Following application shows how to identify list of Classes and Method in any .Net Assembly file with the help of .Net Reflection. For an example I am using Ajax Assembly filename to list all its classname and method name.



Step 1: Design a web form consisting of following controls.
Label – Shows text “Assembly File Name”
Textbox – Taking Input Assembly File Name.
Listbox – For displaying list of Class Names and Method Names
Button – On Button Click Event Display List of Class Name and Method Name

Step 2: Write following code on Button_Click Event.


private void btnListMethodName_Click(object sender, EventArgs e)
{
string sAssemblyFileName = txtAssemblyFileName.Text;

if (sAssemblyFileName.Length != 0)
{
Assembly assem = Assembly.LoadFrom(sAssemblyFileName);
Type[] types = assem.GetTypes();
ArrayList arrl = new ArrayList();
foreach (Type cls in types)
{
try
{
//Add Class Name
arrl.Add(cls.FullName);
if(cls.IsAbstract)
arrl.Add("Abstract Class:" + cls.Name.ToString());
else if(cls.IsPublic)
arrl.Add("Public Class:" + cls.Name.ToString());
else if(cls.IsSealed)
arrl.Add("Sealed Class:" + cls.Name.ToString());

MemberInfo[] methodName = cls.GetMethods();
foreach (MemberInfo method in methodName)
{
//arrl.Add("\t" + method.Name.ToString());
if (method.ReflectedType.IsPublic)
arrl.Add("\tPublic - " + method.Name.ToString());
else
arrl.Add("\tNon-Public - " + method.Name.ToString());
}
}
catch (System.NullReferenceException)
{
Console.WriteLine("Error msg");
}
}

//Dump Data to NotePad File
FileStream fs = new FileStream(@"c:\myData.txt", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
for (int i = 0; i < arrl.Count; i++)
{
lstInfo.Items.Add(arrl[i].ToString());
sw.WriteLine(arrl[i].ToString());
}
sw.Flush();
sw.Close();
}
}

Monday, September 08, 2008

C++ to C# Converter Utility

C++ to C# Converter Utility

For migration project from C++ to C# Converter, a online utility might be helpful for getting startup stuff ready.

Check out C++ to C# Converter

Saturday, August 30, 2008

Finding Distance based on Zipcode or City Name for USA

Finding Distance based on Zipcode or City Name for USA
A really good article sharing how to find distance between two zip codes or cities of USA.

For whom this article is useful

  • It finds distance in miles between two zipcodes of USA.
  • It finds distance in miles between two cities of USA.
  • Finding County based on city or zipcode name.
  • Free Zipcode database of USA
  • Article is written in C#
Finding Distance based on Zipcode or City Name for USA

Note: When you will download the Zipcode of USA Cities and Import to SQL Server, it append inverted comma to data, to remove that you might need to run following update cursor script. Remember you need to change name of column as mentioned in script.

DECLARE c1 CURSOR READ_ONLY
FOR
select ZipCode,Latitude,Longitude,City,State,County,ZipClass from Zip_Codes

declare @ZipCodeOriginal varchar(50)
declare @ZipCode varchar(50)
declare @Latitude varchar(50)
declare @Longitude varchar(50)
declare @City varchar(50)
declare @State varchar(50)
declare @County varchar(50)
declare @ZipClass varchar(50)

open c1
FETCH NEXT FROM c1
Into @ZipCode,@Latitude,@Longitude,@City,@State,@County,@ZipClass
WHILE @@FETCH_STATUS = 0

BEGIN
set @ZipCodeOriginal = @ZipCode
set @ZipCode = substring(@ZipCode,2,len(@ZipCode) - 2)
set @Latitude = substring(@Latitude,2,len(@Latitude) - 2)
set @Longitude = substring(@Longitude,2,len(@Longitude) - 2)
set @City = substring(@City,2,len(@City) - 2)
set @State = substring(@State,2,len(@State) - 2)
set @County = substring(@County,2,len(@County) - 2)
set @ZipClass = substring(@ZipClass,2,len(@ZipClass) - 2)


--Update
update Zip_Codes
set ZipCode=@ZipCode,
Latitude = @Latitude,
Longitude = @Longitude,
City = @City,
State = @State,
County = @County,
ZipClass = @ZipClass
where
--Uniqueness Checking
ZipCode = @ZipCodeOriginal


FETCH NEXT FROM c1
Into @ZipCode,@Latitude,@Longitude,@City,@State,@County,@ZipClass
END
CLOSE c1
DEALLOCATE c1

Saturday, June 21, 2008

Finding Country from Visitors IP in Asp.net

Finding Country Details from Visitors IP in Asp.net, C#

I want to develop a functionality which gives me

  • Visitor's Country details in Asp.net
  • Display Flag of Visitors Country based on Visitors IP Address
  • Gives Information about Visitors Country Currency Information
  • It should also provide Capital details of Visitors Country based on Visitors IP Address.

IP to Country Details

So lets understand step by step how we can Find Visitors Country Details based on Visitors IP Address

Step 1: Finding Visitor's IP Address in Asp.net, C# Code.

You can use following Code to find Visitors IP Address in Asp.net


string VisitorsIPAddr = string.Empty;
//Users IP Address.
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
//To get the IP address of the machine and not the proxy
VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
}

Step2: Finding Country based on Visitors IP Address.

To implement this functionality i have taken help of Code Project IP to Country Code developed by GameWatch Project

This is very well explained and explanatory code to implement. Let show you how I have use this code to Find Country Information from Visitors IP Address.

Download the Sourcecode file available with that code: Direct Download Link

  • Open folder util in zip file i.e. iptocountry_src\iptocountry\src\Utils, this folder contains 3 Class Files and One folder Net.
  • Now Add a new Class Library in your Website project and Add a this class file. Also create folder Net and include 2 class files in it.
After adding class library project your solution explorer looks like following:



Adding Resource File in your Web Application.
  • Now Open folder util in zip file i.e. iptocountry_src\iptocountry\resources, this folder contains 4 Resource Files add this file in your web application by creating new folder name IP2CountryResource
  • So by now your solution explorer should be looking as under.


Now next step would be how to add the resource file and access the classes to find country from given IP address details.
  • Add reference to Class Library Project in your web application.
  • Add following code on page where you want to display IP to country details.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using GameWatch.Utils;
using GameWatch.Utils.Net;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
public IPToCountry Ip2Country = new IPToCountry();

protected void Page_Load(object sender, EventArgs e)
{
string sApplicationPath = Server.MapPath("~");

LoadIpCountryTable(sApplicationPath + @"\IP2CountryResource\apnic.latest");
LoadIpCountryTable(sApplicationPath + @"\IP2CountryResource\arin.latest");
LoadIpCountryTable(sApplicationPath + @"\IP2CountryResource\lacnic.latest");
LoadIpCountryTable(sApplicationPath + @"\IP2CountryResource\ripencc.latest");

#region Finding Visitors IP Address
string VisitorsIPAddr = string.Empty;
//Users IP Address.
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
//To get the IP address of the machine and not the proxy
VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
}
#endregion

string VisitorsCountry = Ip2Country.GetCountry(VisitorsIPAddr);
lblVisitorsIP.Text = VisitorsIPAddr;
lblCountry.Text = VisitorsCountry;
}

public void LoadIpCountryTable(string name)
{
FileStream s = new FileStream(name, FileMode.Open);
StreamReader sr = new StreamReader(s);
Ip2Country.Load(sr);
sr.Close();
s.Close();
}
}

Now, lets understand how can we display visitors country flag and find visitors countries information.

Step 3: Displaying Visitors Country Information.
  • Displaying Flag from IP Address
  • Displaying Country Information from IP Address (i.e. Country Currency, Capital and few other information.)

Download Country details available in Excel File Format, and Download Zip Package consisting Flags of all countries shared as Free Resource by IP2Location.com

http://www.ip2location.com/free.asp

Import the Excel File format containing details of all countries in SQL Server Database (Choose database of your choice, I have used SQL Server 2005). For Importing excel file right click the database, choose tasks and than choose import data...



Than follow the wizard steps and table would be created.

Now, Add one more folder to VS.Net Web application and named it Flags
And add all the flags available with zip file you downloaded, so after adding all the flags .gif file solution explorer look as follow.



now add the code for accessing data from database based on country code you get from given IP Address.

Select Record based on TLD field, where TLD field is country code you receive from above code.

Sample Query.

SELECT DISTINCT [TLD], [Country], [FIPS104], [ISO2], [ISO3], [ISONo], [Capital], [Regions], [Currency], [CurrencyCode], [Population] FROM [Countries] WHERE ([TLD] = @TLD)

So now ones you are done with data access code you assign the available data source to DetailsView control. (Note: I have skip the data access code, You can refer this article if you are facing problem.)

Now just one line of code to actually display image in above code.

imgCountryFlag.ImageUrl = @"~/Flags/" + VisitorsCountry + ".gif";

Wednesday, June 11, 2008

Random Password Generation

I have previously written article on how to Generate Registration Image on Fly

Enhancing the same password generation logic so that it would be useful for generating random password using C# code.



public static string GetRandomPassword(int length)
{
char[] chars = "$%#@!*abcdefghijklmnopqrstuvwxyz1234567890?;:ABCDEFGHIJKLMNOPQRSTUVWXYZ^&".ToCharArray();
string password = string.Empty;
Random random = new Random();

for (int i = 0; i < length; i++)
{
int x = random.Next(1,chars.Length);
//Don't Allow Repetation of Characters
if (!password.Contains(chars.GetValue(x).ToString()))
password += chars.GetValue(x);
else
i--;
}
return password;
}

Its a simple logic instead by generating a random number between 1 and Length of characters. It also checks that same character is not repeated in generated password and finally return the randomly generated password string of desired length.

Thursday, December 13, 2007

Best C-Sharp.Net Blog

Best C#.Net Blog as Compiled by Timm Martin of DevTopics.com.

Read Original Post

Tuesday, November 06, 2007

Site Navigation control in asp.net

There are three Site Navigation control in asp.net 2.0

  • SiteMapPath Control
  • Menu Control
  • Treeview Control
Before using Site Navigation control let go through overview of web.sitemap, which is used as datasource to assign this control.

What is Web.SiteMap and How to Create Web.SiteMap file?
Web.SiteMap file is an XML File, which contains details of navigation that is followed by navigation control.

For Creating Web.SiteMap file
- Right click the project in solution explorer and add new item.
- Select Site Map from the add new item dialog.
- It will create "web.sitemap" file in your root directory


A Sample format of Site Map






Here, siteMapNode contains following properties.
Url - describes URL to be redirect on node click.
Title - describes Text to be displayed on node.
Description - describes Text to be displayed as Tooltip.

For creating sub node, create a siteMapNode inside parent siteMapNode.
A sample web.sitemap file displaying contries and its associated cities of sales region.


















Understanding SiteMapPath Control
SiteMapPath control automatically uses web.sitemap file located in the root of your application.

Drag and drop, SiteMapPath control and it will automatically display naviagation path paved by web.sitemap file.

Example Figure1:


Example Figure2:




Understanding TreeView Control
TreeView control display data in hierarchical order.

Drag an drop the TreeView control on to webform, note TreeView control doesn't use web.sitemap as default datasource, you need to assign it explicitly.



Select "New data source" and select sitemap and press ok.



That's it you are done.



Displaying checkbox with treeview control, you can assign "ShowCheckBox" property of TreeView control to either
  • All - Checkbox to all node.
  • Root - Checkbox to root node.
  • Parent - Checkbox to parent node.
  • Leaf - Checkbox to leaf node.
  • None - No Checkbox



Displaying Selected node code in Treeview control
protected void btnSelected_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach (TreeNode node in TreeView1.CheckedNodes)
{
sb.Append(node.Text + "
");
}
Response.Write("You have selected following node:
" + sb.ToString());
}




Understanding Menu Control
Like TreeView Control you need to explicitly assign data source to menu control.


Select "New data source" and select sitemap and press ok.



That's it you are done.

Bydefault menu control display root node, which generally contains single node, so you may choose option "StaticDisplayLevels" Property to 2 to display node from 2nd level...

Example, here i am displaying node from 2nd level so my StaticDisplayLevels will be 2.

Wednesday, October 31, 2007

What is XML DOM (Document Object Model)

Why is XML DOM?
XML is a standard by which two incompatible system can communicate. XML DOM works with XML data in your application. It is used to read, write and modify XML document programatically.


Understanding Nodes in XML Document


Node type

Description

Root

This node type is the container for all the nodes and is also known as the document root.

Element

This node type represents element nodes.

Attribute

This node type represents the attributes of an element node.

Text

This node type represents the text that belongs to a particular node or to an attribute.



Example of XML Document, employee.xml



Ajay
Thakur
08/09/1968
04/01/1992
2010 Stanley Dr., Charlotte, NJ 08830

2100
HR Manager
12


Ganesh
Patil
01/12/1972
06/01/2000
7862 Freepoint Pkwy, Tampa, NJ 08820

1400
Software Professional
4




Understanding XML Document
  • Every XML Document contains a single root element that contains all other nodes of the XML Document. Here is a root element.
  • XML Element is a Record which contains information. Here
  • XML Element Attribute further describe the Record details. Here etc are XML Element Attributes.

What is XML Document Object?
XMLDocument provides an in-memory representation of and XML document.

Example of XML Document
Create a Asp.net Website
Create a XML Document and name it employee.xml

Loading of XML Document
You can load xml document using XMLDocument object's load method

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
XmlDocument EmpXMLDoc = new XmlDocument();
string XMLDocPath = Server.MapPath("Employee.xml");
EmpXMLDoc.Load(XMLDocPath);
Response.Write(EmpXMLDoc.InnerText.ToString());
}
}


Saving XML Document
You can save XML Document with XMLDocument.Save method
Example: XMLDocument.Save("Employee.xml");


Read XML Document and display on WebPage
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
XmlDocument EmpXMLDoc = new XmlDocument();
string XMLDocPath = Server.MapPath("Employee.xml");
EmpXMLDoc.Load(XMLDocPath);

//Read XML Document //Note: Begin for ChildNode[1]
foreach (XmlNode node1 in EmpXMLDoc.ChildNodes[1])
{
foreach (XmlNode node2 in node1.ChildNodes)
{
Response.Write("" + node2.Name + ": " + node2.InnerText + " ");
}
Response.Write("
");
}
}
}

//Output

Wednesday, October 03, 2007

Error Handling in .Net with Example

Error Handling in .Net with Easy Example and Step by Step guide.

What is Exception?
An exception is unexpected error or problem.

What is Exception Handling?
Method to handle error and solution to recover from it, so that program works smoothly.

What is try Block?

  • try Block consist of code that might generate error.
  • try Block must be associated with one or more catch block or by finally block.
  • try Block need not necessarily have a catch Block associated with it but in that case it must have a finally Block associate with it.
Example of try Block

Format1
try
{
//Code that might generate error
}
catch(Exception errror)
{
}

Format2
try
{
//Code that might generate error
}
catch(ExceptionA errror)
{
}
catch(ExceptionB error)
{
}

Format3
try
{
//Code that might generate error
}
finally
{
}


What is catch Block?
  • catch Block is used to recover from error generated in try Block.
  • In case of multiple catch Block, only the first matching catch Block is executed.
  • when you write multiple catch block you need to arrange them from specific exception type to more generic type.
  • When no matching catch block are able to handle exception, the default behavior of web page is to terminate the processing of the web page.
Example of catch Block

Format1
try
{
//Code that might generate error
}
catch(Exception errror)
{
//Code that handle errors occurred in try block
}


Format2
try
{
//Code that might generate error
}
catch(DivideByZeroException errror)
{
//Code that handle errors occurred in try block
//Note: It is most specific error we are trying to catch
}
catch(Exception errror)
{
//Code that handle errors occurred in try block
//Note: It is not specific error in hierarchy
}
catch
{
//Code that handle errors occurred in try block
//Note: It is least specific error in hierarchy
}


Explain finally Block?
  • finally Block contains the code that always executes, whether or not any exception occurs.
  • When to use finally Block? - You should use finally block to write cleanup code. i.e. you can write code to close files, database connections, etc.
  • Only One finally block is associated with try block.
  • finally block must appear after all the catch block.
  • If there is a transfer control statement such as goto, break or continue in either try or catch block the transfer happens only after the code in the finally block is executed.
  • If you use transfer control statement in finally block, you will receive compile time error.
Example of finally Block

Format1
try
{
//Code that might generate error
}
catch(Exception errror)
{
//Code that handles error and have solution to recover from it.
}
finally
{
//Code to dispose all allocated resources.
}

Format2
try
{
//Code that might generate error
}
finally
{
//Code to dispose all allocated resources.
}


Explain throw statement?
  • A throw statement is used to generate exception explicitly.
  • Avoid using throw statement as it degrades the speed.
  • throw statement is generally used in recording error in event log or sending an email notification about the error.
Example of throw statement
try
{
//Code that might generate error
}
catch(Exception errror)
{
//Code that handles error and have solution to recover from it.

throw; //Rethrow of exception to Add exception details in event log or sending email.
}


Explain using statement?
  • using statement is used similar to finally block i.e. to dispose the object.
  • using statement declares that you are using a disposable object for a short period of time. As soon as the using block ends, the CLR release the corresponding object immediately by calling its dispose() method.
Example of using statement in C#

//Write code to allocate some resource
//List the allocated resource in a comma-seperated list inside
//the parantheses of the using block

using(...)
{
//use the allocated resource.
}

//here dispose method is called for all the object referenced without writing any additional code.


Is it a best practice to handle every error?
No, it is not best practice to handle every error. It degrades the performance.
You should use Error Handling in any of following situation otherwise try to avoid it.
  • If you can able to recover error in the catch block
  • To write clean-up code that must execute even if an exception occur
  • To record the exception in event log or sending email.

Difference between catch(Exception ex) and catch
try
{
}
catch(Exception ex)
{
//Catches all cls-compliant exceptions
}
catch
{
//Catches all other exception including the non-cls compliant exceptions.
}


Managing Unhandled Exception You can manage unhandled exception with custom error pages in asp.net. You should configure the element in web.config file. It has two attributes:
  • Mode Attribute: It specifies how custom error page should be displayed. It contains 3 values.
    • On - Displays custom error pages at both the local and remote client.
    • Off - Disables custom error pages at both the local and remote client.
    • RemoteOnly - Displays custom error pages only at the remote client, for local machine it displays default asp.net error page. This is default setting in web.config file.
  • defaultRedirect: It is an optional attribute to specify the custom error page to be displayed when an error occurs.
  • You can display custom error page based on http error statusCode using error element inside the customeError element, in case the no specific statusCode match it will redirect to defaultRedirect page.

  • statusCode="403" redirect="NoAccess.htm" />
    statusCode="404" redirect="FileNotFound.htm" />
Example of Unhandled Exception
I have created a sample website which can generate unhandled exception, divide by zero.



This will result into default error page generated by asp.net



To suppress error with CustomError Page you need to define customError element in Web.Config file.

Example:



This setting web.config will display default error page whenever web application generates unhandled exception

Now, after adding the above code in web.config file and creating a sample DefaultErrorPage.htm in root directory it will redirect to DefaultErrorPage.htm whenever unhandled exception occurs.



Similarly you can display error message for different http status code






Here we are using HttpError.aspx page to display all http errors by passing the error code as querystring.

You need to place following code into HttpError.aspx page to make this work

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string sErrorCode = Request.QueryString["ErrorCode"].ToString();
switch (sErrorCode)
{
case "403": Label1.Text = "Error: Request Forbidden";
break;
case "404": Label1.Text = "Error: Page Not Found";
break;
}
}
}

So lets click on page which is not present in web application and can generate page not found error.








Events fired on Unhandled Exception
Two events fire in successive order on unhandled exception
  • Page.Error() Event - Performing error handling at page level.
  • Application.Error() Event - Performing error handling at application level.

Page.Error() Event
Let display error message in above divide by error instead of display custom error page.

Add the Page_Error() Event

protected void Page_Error(object sender, EventArgs e)
{
Response.Write("Error: " + Server.GetLastError().Message + "");
Server.ClearError();
}

Server.GetLastError() method is used to display last error, while Server.ClearError() will clear the last exception and does not fire the subsequent error events. For this reason, you will notice that custom error page is not displayed even though there is unhandled error, and a default error message is displayed.






Application.Error() Event
Application.Error Event is used to handle unhandled exception of entire application. This event lies in Global.asax file. You can use this event to send email for error or generate a text file or recording error information in database, etc.

Here we will generate a text file in MyError directory of application and send email of same error to web master.

So lets begin by adding namespace to global.asax

For adding namespace to global.asax make use of import statement.

<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Net.Mail" %>


Now, add following code to Application_Error Event in Global.asax for generating error text file and sending error reporting email to webmaster in asp.net

void Application_Error(object sender, EventArgs e)
{
Exception err = (Exception)Server.GetLastError().InnerException;

//Create a text file containing error details
string strFileName = "Err_dt_" + DateTime.Now.Month + "_" + DateTime.Now.Day
+ "_" + DateTime.Now.Year + "_Time_" + DateTime.Now.Hour + "_" +
DateTime.Now.Minute + "_" + DateTime.Now.Second + "_"
+ DateTime.Now.Millisecond + ".txt";

strFileName = Server.MapPath("~") + "\\MyError\\" + strFileName;
FileStream fsOut = File.Create(strFileName);
StreamWriter sw = new StreamWriter(fsOut);

//Log the error details
string errorText = "Error Message: " + err.Message + sw.NewLine;
errorText = errorText + "Stack Trace: " + err.StackTrace + sw.NewLine;
sw.WriteLine(errorText);
sw.Flush();
sw.Close();
fsOut.Close();

//Send an Email to Web Master
//Create Mail Message Object with content that you want to send with mail.
MailMessage MyMailMessage = new MailMessage("[email protected]","[email protected]",
"Exception:" + err.Message, errorText);

MyMailMessage.IsBodyHtml = false;

//Proper Authentication Details need to be passed when sending email from gmail
NetworkCredential mailAuthentication = new
NetworkCredential("[email protected]", "password");

//Smtp Mail server of Gmail is "smpt.gmail.com" and it uses port no. 587
//For different server like yahoo this details changes and you can
//get it from respective server.
SmtpClient mailClient = new SmtpClient("smtp.gmail.com",587);

//Enable SSL
mailClient.EnableSsl = true;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = mailAuthentication;
mailClient.Send(MyMailMessage);
}

On running the program and generating exception will create error file in MyError directory and will send email stating error to web master, And it will display custom error page to user.


Error Text File generated on unhandled exception.



Email is sended to web master, with subject as Error Message.




Error description is stated as below.

Friday, September 28, 2007

Assemblies Concept in .Net

Understanding Assemblies Concept in .Net

What is Assemblies in .Net?

  • Assembly is a logical collection of smallest unit in .Net Framework.
  • Example: .DLL File contains the application code, the .aspx file, .ascx user controls, .gif, .bmp, .ico file and other files like Resource file (.resx), etc.
  • In summary, Assemblies is a basic fundamental unit of application development and deployment in the .Net Framework
  • An assembly contains the MSIL code, which the common language runtime executes, and the type metadata.
  • An assembly also contains an assembly manifest that contains the assembly metadata. This metadata contains information about the assembly version, its security identity, the resources required by the assembly, and the scope of the assembly.
  • Assemblies are the smallest units to which the .NET Framework grants permissions. They provide security boundaries within the .NET Framework. You specify the permission required by your application while building assemblies. When the assembly is loaded into the runtime, the assembly sends a request to the runtime to grant the permission.
So now, lets Get Started with Assemblies .Net and understand concept of Assemblies in .Net by easy step by step explanation.

What is Assembly Manifest?
  • Assembly Manifest contains the metadata for the assembly.
  • Example, Assembly Manifest contains
    • Name and Version Information of Assembly.
    • Files (or Resource) that are made up the assembly.
    • Set of permissions required for the assembly to run properly.
    • And few other details depends on assembly.

How Assembly Manifest is useful?

When the Common Language Runtime (CLR) loads an assembly, it first reads the manifest to get the information regarding assembly.


Benefits of Assemblies?

  1. It is used in Versioning
  2. For Type Identification
  3. For Security
  4. For Deployment
  5. For Referencing.
  6. Improving Application Performance
  7. Better Code Management and Maintenance

What is "DLL Hell" Problem?
"DLL Hell" problem occurs due to version incompatibility of dll's.

DLL HELL is the problem that occures when an installation of a newer application might break or hinder other application as newer DLLs are copied into the system and the older application do not support or not compatible with them. .net overcomes this problem by supporting multiple versions of an assembly at any given time.this is called side-by-side component versioning.

More on "DLL Hell" Problem.
"DLL Hell" is a problem occurs when multiple applications attempt to share a common component like a dynamic link library (DLL) or a Component Object Model (COM) class. In the most typical case, one application will install a new version of the shared component that is not backward compatible with the version already on the machine. Although the application that has just been installed works well, existing applications that depended on a previous version of the shared component might no longer work.

How Assembly used in Avoiding "DLL Hell" Problem?
"DLL Hell" Problem is solved in .Net using Assembly.

Each assembly has a version number. All the types and resources in an assembly share the same version number to make it easy for applications to refer to the correct version of files and avoid problem of "DLL Hell". Thus assemblies allows the execution of multiple versions of the same assembly on the same machine. The side-by-side execution of assemblies overcomes the problem known as "DLL hell," which is one of the major problems associated with COM applications.


How Assembly can Improve Application Performance?
CLR is place where .Net Application codes gets compiled. Whenever you made an request to ASP.NET page, the page gets compiled first and then is transferred to the user. The compilation process is also completed in two steps.
  • 1. An IL (Intermediate Language) is generated and then this is handed over for JIT
  • 2. JIT (Just In Time) compilation which produces the machine code and our pages get displayed with their dynamic content.

The performance of our web application can be improved by creating pre-compiled libraries of IL which can then be handed over to JIT directly without having the inclusion of an extra process to make the conversion. This method is called componentization. Components are pre-compiled set of classes that have been developed in the form of DLL files and can then be included within our projects. This is also known as an assembly.


How Assembly can be used for Better Code Management and Maintenance
As we use Componentization(refer above description), if a code change require you need to change the component code compile it, so you do not require to change all the reference of code for minor change. For better understanding understand the example of component given below.


Types of Assemblies in .Net
  • Static and Dynamic Assemblies
  • Single-File and Multifile Assemblies
  • Private and Shared Assemblies
  • Satellite and Resource-only Assemblies

What is Static Assembly?
A static assembly is created when you compile the program using any of the .NET language compilers. A static assembly contains the types, interfaces, and various resources required by the assembly. A static assembly is stored on the hard disk in the form of a portable executable (.exe or .dll) file. In a simple term, when you compile through VS.Net it generates files which are physically stored on the disk, this files are called static assembly.


What is Dynamic Assembly?
Assemblies which are created and execute on the fly are called dynamic assembly. You can create dynamic assembly through System.Reflection.Emit namespace.

What is Single-File Assembly?
A single-file assembly consists of a single .exe or .dll file.
Example of Single File Assembly
In the example the Shape.dll generated is a Single File Assembly.


What is Multifile Assembly?
  • A multifile assembly is an assembly that can include multiple file, but it should contain atleast one .dll or .exe file.
  • Assembly manifest in multifile assembly can be attached to any assembly file or can be created seperately just the manifest.

What is Satellite Assembly?
Resource-only assemblies are assembly's that stores only resource and no code. example, Image. Resource-only assemblies that store the culture-specific information are known as satellite assemblies.

What is Private Assembly?
  • When you deploy an assembly which can be use by single application, than this assembly is called a private assembly.
  • Private assemblies can be used by only one application they are deployed with.
  • Private assemblies are deployed in the directory where the main application is installed.

What is Shared Assembly?
  • When you deploy an assembly which can be used by several application, than this assembly is called shared assembly.
  • Shared assemblies are stored in a special folder called Global Assembly Cache (GAC), which is accessible by all applications.
  • Shared assemblies must have a strong name. A strong name consists of an assembly name, a version number, a culture, a public key and an optional digital signature.
  • GAC is capable of maintaining multiple copies of an assembly with the same name but different versions.

How to assign strong name to assembly?
You can use strong name tool sn.exe tool to assign strong name to assembly. It provides
  • Name
  • Version
  • Integrity Protection.

How to provide High Security to assembly?
You can provide high security to assembly with the help of File Signing Tool, signcode.exe. It attach a publisher's digital signature to assembly. You can sign an assembly with both Strong Name Tool and the File Signing Tool, but when you use both make sure that you use Strong Name Tool before you use the File Signing Tool.


How to view content of GAC?
To view content of GAC open explorer and go to c:\Windows\assembly.


Native Assembly Vs JIT-Compiled Assembly
Assemblies store code in the MSIL (Microsoft Intermediate Language) Format. When a method is invoked for the first time, the CLR just-in-time (JIT) compiles that method into native machine code. The native code is stored in memory and directly used for subsequent calls to this method. In the JIT compilation mode, a method is slow when it is called for the first time because an additional step of compilation is invoked, but any subsequent calls to that method will run as fast as native code itself.
When you view the GAC, note that some assemblies have their type marked as native images, meaning that these assemblies were precompiled in native code before they were installed in the native image cache. The advangate of using a native image is that even the first call of any method in an assembly will be as fast as its subsequent calls. You too can create a native image for your assembly by using the Native Image Generator Tool, ngen.exe, which is installed as part of .net framework.


Releated Links

Wednesday, September 26, 2007

Tips, Tricks, Articles and Information on .Net by Scott Guthrie

Tips, Tricks, Articles and Information on .Net by Scott Guthrie

A list of Popular Articles and Tips and Tricks for

  • Visual Studio.Net 2005
  • Asp.Net UI Development Articles
  • AJAX Development Articles
  • Database Related article
  • Security Tips and Tricks in Asp.net
  • Deployment Articles
  • Articles on Enhancing Performance of Web Application
  • .Net 3.5 Vs Visual Studio 2008
  • LINQ Articles and Explanation
  • Silverlight Articles
Click here

Tuesday, September 25, 2007

Creating Component in .Net

Creating Component in .Net

What is Component?
It is a set pre-compiled class, which is reusable. For now, just stick to it at the end of article you will practically understand how it is reusable piece of code.

Advantages of Component

  • Improving Application Performance
  • Better Code Management and Maintenance

How Component can Improve Application Performance?
CLR is place where .Net Application codes gets compiled. Whenever you made an request to ASP.NET page, the page gets compiled first and then is transferred to the user. The compilation process is also completed in two steps.
  • 1. An IL (Intermediate Language) is generated and then this is handed over for JIT
  • 2. JIT (Just In Time) compilation which produces the machine code and our pages get displayed with their dynamic content.

The performance of our web application can be improved by creating pre-compiled libraries of IL which can then be handed over to JIT directly without having the inclusion of an extra process to make the conversion. This method is called componentization. Components are pre-compiled set of classes that have been developed in the form of DLL files and can then be included within our projects. This is also known as an assembly.


How Component can be used for Better Code Management and Maintenance
As we use Componentization(refer above description), if a code change require you need to change the component code compile it, so you do not require to change all the reference of code for minor change. For better understanding understand the example of component given below.


Example of Creating Component in .Net

Creating a simple demo of famous Class Shape Example, wherein simple functionality is added.

Step1:
Create a Asp.net web application

Step2: Right click the solution explorer and add New Project "class library project"
For example, Delete the .CS File and Add Component using Project > Add New Component and Name it as csShape.cs

Note: By creating component you are actually creating assembly file and it has all the benefits that assembly has. You can edit all the assembly details by right clicking "Class Library Project" and Selecting Properties from popup window.

Step3: Created a Four Class as shown in Class Diagram



For better understanding download the Shape.CS File

Step4: Compile the Class Library Project

Step5: Add Reference to Project




Step6: Test the component.

Add namespace
using Shape;

protected void Page_Load(object sender, EventArgs e)
{
csShape objShape = new csShape();
Response.Write("
" + "I am " + objShape.ShapeName
+ " Object and my color is " + objShape.Color);

csCircle objCircle = new csCircle();
objCircle.Color = "Blue";
Response.Write("
" + "I am " + objCircle.ShapeName
+ " Object and my color is " + objCircle.Color);

csSquare objSquare = new csSquare();
objSquare.Color = "Green";
Response.Write("
" + "I am " + objSquare.ShapeName
+ " Object and my color is " + objSquare.Color);

csRectangle objRectangle = new csRectangle();
objRectangle.Color = "Orange";
Response.Write("
" + "I am " + objRectangle.ShapeName
+ " Object and my color is " + objRectangle.Color);
}


Output of Application



So now if you want to change the functionality of Shape class you can do it independently you just need to rebuild the class library application and all changes are reference without any extra effort.

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape