Wednesday, September 30, 2009

Month Name from Month Number

Getting Month Name from the Month Number is quite easy by extending DateTime properties in .net.

For Example, if you are having a month number, say 2, which you need to convert it into corresponding Month Name(February)




string strMonth = "2";

DateTime date = new DateTime(1, strMonth, 1);

string strMonthName = date.ToString("MMM");



This will return you the month name "Feb" ,but only first three characters.

If you need the month name in full, slightly modify the above syntax



string strMonth = "2";

DateTime date = new DateTime(1, strMonth, 1);

string strMonthName = date.ToString("MMMM"); // Four Characters will give you the full month name.



Happy Coding..

Labels: , , , , , , ,

Tuesday, September 29, 2009

Implemeting SSL in IIS 7.0

Recently read an article written by ScottGu, on enabling SSL on IIS 7.0 Using Self-Signed Certificates. Well explained and understandable implementation procedures. Follow the simple steps explained below to implement the same.

SSL enables browsers to communicate with a web-server over a secure channel that prevents eavesdropping, tampering and message forgery. You should always use SSL for login pages where users are entering usernames/passwords, as well as for all other sensitive pages on sites (for example: account pages that show financial or personal information).

Configuring SSL on Windows with previous versions of IIS has been a pain. Figuring out how to install and manage a certificate, and then associate it with a web-site, is something I bet most web developers don't know how to enable.

The good news is that IIS 7.0 makes it radically easier to configure and enable SSL. IIS 7.0 also now has built-in support for creating "Self Signed Certificates" that enable you to easily create test/personal certificates that you can use to quickly SSL enable a site for development or test purposes.

Using IIS 7.0 you can SSL enable an existing web site in under 30 seconds. The below tutorial demonstrates how to-do this.

Step 1: Create a New Web Site

We'll start by creating a new web-site using the new IIS 7.0 admin tool. This admin tool is a complete re-write of the previous IIS admin tool (and was written entirely in managed code using Windows Forms), and provides a more logical organization of web features. It provides a GUI admin experience for all ASP.NET and IIS settings:



















To create a new site on the box, right click on the "Web Sites" node in the left hand tree-view pane and choose the "Add Web Site" context menu option. Enter the appropriate details to create a new web-site:
























One nice feature of IIS7 on Windows Vista is that you can now have an unlimited number of sites on a box (previous versions of IIS on Windows Client only allowed 1 site). The 10 simultaneous request limitation on Windows Client versions of IIS also no longer exists with IIS 7.0.

Once we've completed the above steps, we will now have a brand new site running on our IIS web-server.

Step 2: Create a new Self Signed Certificate

Before binding SSL rules to our new site, we need to first import and setup a security certificate to use with the SSL binding.

Certificates are managed in IIS 7.0 by clicking the root machine node in the left-hand tree-view explorer, and then selecting the "Server Certificates" icon in the feature pane on the right:




This will then list all certificates registered on the machine, and allow you to optionally import and/or create new ones.

I could optionally go to a certificate authority like Verisign and purchase a certificate to import using this admin UI. Alternatively, I can create a "self-signed certificate" which is a test certificate that I can use during the development and testing of my site. To-do this, click the "Create Self-Signed Certificate" link on the right-hand side of the admin tool:






Enter a name to use for the certificate (for example: "test") and hit ok. IIS7 will then automatically create a new self-signed crypto certificate for you and register it on the machine:





 
 
 
 
 
 
 
 
Step 3: Enable HTTPS Bindings for our New Site


To SSL enable the web-site we created earlier, select the web-site node in the left-hand tree-view, and the click the "Bindings" link in its "actions" pane on the right-hand side of the screen:




 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
This will then bring up a dialog that lists all of the binding rules that direct traffic to this site (meaning the host-header/IP address/port combinations for the site):


 
 
 
 
 
 
 
 
 
To enable SSL for the site, we'll want to click the "Add" button. This will bring up an "add binding" dialog that we can use to add HTTPS protocol support. We can select the self-signed certificate we created earlier from the SSL certificate dropdownlist in the dialog, and in doing so indicate that we want to use that certificate when encrypting content over SSL:
 

 
 
 
 
 
 
 
 
 
 
 
 
Click ok, and we now have SSL enabled for our site:
 

Step 4: Test out the Site


Add a "default.aspx" page to the site, and then try and hit it with the browser by typing https://localhost/default.aspx (note the usage of "https" instead of "http" to indicate that you want to connect over SSL).

If you are using IE7, you'll likely see this anti-phishing error message kick in





Don't panic if this happens - it is just IE being helpful by suggesting that a self-signed certificate on your local machine looks suspicious. Click the "Continue to this website" link to bypass this security warning and proceed to the site. You'll find that your default.aspx page is now running protected via SSL:



You are all done. :-)

Appendix: A Few Last SSL Notes

A few last SSL related notes:

•The IIS 7.0 admin tool has an "SSL Settings" node that you can select for each site, directory or file that allows you to control whether that particular resource (and by default its children) requires an SSL request in order to execute. This is useful for pages like a login.aspx page, where you want to guarantee that users can only enter their credentials when they are posting via an encrypted channel. If you configure the login.aspx page to require SSL, IIS 7.0 will block browsers from accessing it unless they are doing so over SSL.

•Within an ASP.NET page or handler, you can programmatically check whether the current request is using SSL by checking the Request.IsSecure property (it will return "true" if the incoming browser request is over SSL).

•You can set the "requireSSL" attribute on the <forms> configuration section within web.config files to have ASP.NET's forms-authentication system ensure that forms-authentication cookies are only set and used on SSL enabled pages and URLs. This avoids the risk of a hacker trying to intercept the authentication cookie on a non-SSL secured page, and then trying to use a "replay attack" from a different machine to impersonate a user.

Labels: , , , ,

Monday, September 28, 2009

Maintain Scroll Position on PostBack in ASP.NET

In order to maintain the page scroll position after the page gets postback, ASP.NET gives us three methods. They are:


1. In Web.config :
<pages maintainScrollPositionOnPostBack="true">

2. In single Page :
<%@ Page MaintainScrollPositionOnPostback="true" ...

3. Programatically :

Page.MaintainScrollPositionOnPostBack = true;

Labels: , , , , , ,

Thursday, September 24, 2009

Offline Mode of your WebSite

A simple .htm file will make your application offline in no time.

Just place App_Offline.htm file on root of your web application, all requests to your web site will be redirected automatically to this file.

Now your Website is completely Offline!

Labels: , , , , , ,

Handy Extension Methods for ASP.NET MVC's UrlHelper

Mickael Chambaud posted three extension methods he created for UrlHelper: Image(), Stylesheet() and Script(). They make it pretty easy to keep your images, stylesheets and scripts organized in a single location – without the need for you to remember where they are placed. And if you need to move things around for some reason, you only have to change the extension methods.

It takes only a few minutes and will probably save you a lot of massive Search & Replace in the future!


public static string Image(this UrlHelper helper, string fileName)
{
return helper.Content("~/Content/Images/" + fileName));
}

public static string Stylesheet(this UrlHelper helper, string fileName)
{
return helper.Content("~/Content/Stylesheets/" + fileName);
}

public static string Script(this UrlHelper helper, string fileName)
{
return helper.Content("~/Content/Scripts/" + fileName);
}


So instead of doing this:


<link href="../../../Content/StyleSheets/Main.css" rel="stylesheet" type="text/css" />


You can do this :


<link href="<%= UrlHelper.Stylesheet("Main.css")%>" rel="stylesheet" type="text/css" />


Happy Coding...

Labels: , , , , , ,

Credit Card Expiration Date DropDownList Sample Code

Below is the sample code for populating Credit Cart Expiration Date DropDownList.


//Populate the credit card expiration month drop down
for (int i = 1; i <= 12; i++) { DateTime month = new DateTime(2000, i, 1); ListItem li = new ListItem(month.ToString("MMM (M)"), month.ToString("MM")); ExpirationDateMonthDropDown.Items.Add(li); } //Populate the credit card expiration year drop down (go out 12 years) for (int i = 0; i <= 11; i++) { String year = (DateTime.Today.Year + i).ToString(); ListItem li = new ListItem(year, year); ExpirationDateYearDropDown.Items.Add(li); }



Happy Coding...

Labels: , , , , , ,

Visual Studio Automatically Changing the IDs in Source View

When pasting a snippet of HTML into the Visual Studio source window, Visual Studio will automatically change the IDs to the default naming convention (TextBox1, etc.).






Most of the time though I do not want this to happen since I purposely want to have that ID copy exactly as is since it makes things easier for me when changing the name. For example, it is easier to change FirstNameTextbox to LastNameTextbox than to change TextBox1 to LastNameTextbox.

There is an option to turn the Auto ID elements on paste off. It can be found in:

Tools > Options > Text Editor > HTML> Miscellaneous > Auto ID elements on paste in Source view. Uncheck the box to turn this feature off.














Now Visual Studio will leave IDs alone:


Better Perfomance of Web Applications

If you are :

•Running Windows server in 64 bit mode.
•Running a standard .Net web application
•Do not need a large memory address space (ie. over 4 gigabytes)
•Have no special 64 bit optimisations

Simple solution to improve the performance is by enabling 32 bit mode on your iis server.

Follow these simple steps to get the better performance improvements in your application.

1.To enable 32 bit mode on IIS in 64 bit windows, at a command prompt type:
cscript %SYSTEMDRIVE%\inetpub\adminscripts\adsutil.vbs SET W3SVC/AppPools/Enable32bitAppOnWin64 1

2.Once this is done, 32 bit mode is enabled but we need to ensure that the 32 bit DLL’s are used as IIS will still have the 64 bit DLL’s defined for the ISAPI handler. To do this, all we have to do is re-register ASP.NET. At a command prompt, simply type:
%SYSTEMROOT%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe –i

3.Finally, just make sure the status ASP.NET version 2.0.50727 (32-bit) in the web services extension, within IIS, is set to allowed.
(More information on this process can be found here http://support.microsoft.com/kb/894435)

Thats it, you can improve the performance by 30% - 50%.

Happy Coding...

Labels: , , , ,

Display Numerals in Arabic Format

When you are working in multilingual website, especially in arabic language, the following code may be useful to show numbers in arabic format. Because keep in mind, there is no automatic digit localization in ASP.NET. This code will help if you are in situation where you dont want change the regional settings of the PC.


public string ConvertToArabicNumerals(string input)
{
System.Text.UTF8Encoding utf8Encoder = new UTF8Encoding();

System.Text.Decoder utf8Decoder = utf8Encoder.GetDecoder();

System.Text.StringBuilder convertedChars = new System.Text.StringBuilder();

char[] convertedChar = new char[1];

byte[] bytes = new byte[]{217,160};

char[] inputCharArray = input.ToCharArray();

foreach (char c in inputCharArray)

{

if(char.IsDigit(c))

{

bytes[1] = Convert.ToByte(160 + char.GetNumericValue(c));

utf8Decoder.GetChars(bytes, 0, 2, convertedChar, 0);

convertedChars.Append(convertedChar[0]);

}

else

{

convertedChars.Append(c);

}

}

return convertedChars.ToString();
}



Happy Coding...

Labels: , , , , ,

Wednesday, September 23, 2009

The Controls collection cannot be modified because the control contains code blocks

Sometimes when you write inline code inside Javascript tag or inside style sheet tag within the header of the page just like code 1, the yellow error page will explode in your face telling you that The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

<%@ Page Language="VB" AutoEventWireup="false"
CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head >
<title>Inline Code inside JavaScript</title>
<script type="text/javascript" language="javascript">
function fnTest()
{
var txt = document.getElementById("<%= TextBox1.ClientID %>")
alert(txt.value);
}


</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</form>
</body>
</html>


There are two solutions to overcome this error.

Solution 1 :

Move the JavaScript tag to the bottom of the page, typically above the close form tag.

<%@ Page Language="VB" AutoEventWireup="false"
CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head >
<title>Inline Code inside JavaScript</title>
</head>
<body>
<form id="form1" runat="server">

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<script type="text/javascript" language="javascript">
function fnTest()
{
var txt = document.getElementById("<%= TextBox1.ClientID %>")
alert(txt.value);
}


</script>


</form>
</body>
</html>


Solution 2 :

By registering the JavaScript code from code behind.


Protected void Page_Load(object sender, EventArgs e)
{
StringBuilder strScript = New StringBuilder();
strScript.Append("function fnTest()")
strScript.Append("{")
strScript.Append("var txt = document.getElementById('")
strScript.Append(Me.TextBox1.ClientID)
strScript.Append("');")
strScript.Append("alert(txt.value);")
strScript.Append("}")

Page.ClientScript.RegisterClientScriptBlock (Me.GetType, "MyScript", strScript.ToString, True)

}

Happy Coding...

Labels: , , , , ,

Team Foundation PowerToys

The Team Foundation PowerToys (TFPT) application provides extra functionality for use with the Team Foundation version control system. The Team Foundation PowerToys application is not supported by Microsoft.

Five separate operations are supported by the TFPT application: unshelve, rollback, online, getcs, and uu. They are all invoked at the command line using the tfpt.exe application. Some of the TFPT commands have graphical interfaces.

Read More on PowerToys..

Labels: , , , , , ,

String is All Lower or All Upper Case

How do we find a string is All Lower or All Upper case characters?

There are so many ways to accomplish the same thing. We immediately go to the most simple solution; using the ToLower() method on the string object and comparing the original string input to the lower version of the same sentence. The code is shown below.

private bool IsAllLowerCase(string value)
{
return (value.Equals(value.ToLower()));
}

This is a simple method that should be fairly performant. We can make it great performant by using a regular expression. This is shown in the following code:

using System.Text.RegularExpressions;

private bool IsAllLowerCase(string value)
{
// Allow anything but upper case
return new Regex(@"^([^A-Z])+$").IsMatch(value);
}

We can flip around the above regular expression to check for Upper Case.

Happy Coding...

Labels: , , , , , ,

Tuesday, September 22, 2009

Detecting Chrome browser in ASP.NET

ASP.NET comes with a browser capabilities database (BCD), which describes the capabilities of known browsers. This database is usefull for control developers who want to take advantage on different browser capabilities. Of course, more recent browsers are not listed on that database, simply because they did not exist at the time ASP.NET 2.0 was released (versions 3.0, 3.5 and 3.5 SP1 don't add anything new), and, specifically, Chrome is not on that list.

If you want to add new browsers to the BCD, you have two options:

1.The global database, located in the %Windir%\Microsoft.NET\Framework\v2.0.50727\CONFIG\Browsers directory

2.A local database on your ASP.NET application, in the App_Browsers directory
In any case, you start by adding a new file, say, Chrome.browser, to the appropriate directory. Looking at all browsers registed in the BCD, we choose Safari as the most similar one, and have our definition inherit from it:


<browsers>
<browser id="Chrome" parentID="Safari1Plus">

<identification>
<useragent match="Chrome/(?'version'(?'major'\d+)\.(?'minor'\d+\.\d+).\d+)" />

</identification>

<capabilities>
<capability name="browser" value="Chrome" />

<capability name="majorversion" value="${major}" />
<capability name="minorversion" value="${minor}" />

<capability name="version" value="${version}" />
</capabilities>

</browser>
</browsers>


Of course, you can override the capabilities defined for Safari, if you want, but I think they should be OK. Also, you can add entries for all the Chrome versions.

If you try to access your web application running Chrome and look at the HttpContext.Request.Browser.BrowserName, you may be surprised to see that the name is... not Chrome! It so happens that you must increase the number of characters ASP.NET uses for the user agent header, and you do this in Web.config under <system.web> section.



<browsercaps userAgentCacheKeyLength="128" />



That's it! If you try now, you'll see that the BrowserName property is now "Chrome" and that the listed capabilities match the configured ones.

Labels: , , , ,

Chart Control for .net 3.5

Microsoft has launched a new ASP.NET server control - <asp:chart /> - that can be used for free with ASP.NET 3.5 to enable rich browser-based charting scenarios.

Once installed the <asp:chart/> control shows up under the "Data" tab on the Toolbox, and can be easily declared on any ASP.NET page as a standard server control.



<asp:Chart id="chart1" runat="server"/>


<asp:chart /> supports a rich assortment of chart options - including pie, area, range, point, circular, accumulation, data distribution, ajax interactive, doughnut, and more. You can statically declare chart data within the control declaration, or alternatively use data-binding to populate it dynamically. At runtime the server control generates an image (for example a .PNG file) that is referenced from the client HTML of the page using a <img/> element output by the <asp:chart/> control. The server control supports the ability to cache the chart image, as well as save it on disk for persistent scenarios. It does not require any other server software to be installed, and will work with any standard ASP.NET page.

You can download the chart controls from

Microsoft Chart Controls

Tool support from

Tool Support for the Chart Controls

Samples

Chart Control Samples

Documentation

Chart Control Documentation

Labels: , , , ,

Increase the VS screen for HTML pages

By default, when you are in HTML source-editing mode with VS 2008 and Visual Web Developer 2008 Express edition there is a set of drop-downs that are rendered immediately above the HTML text editor view.

This is of no use, when you are using separate code behind files for your page and not lot of inline javascript functions.

We can always hide this navigation dropdown boxes to increase the size of VS screen.

To achieve this, just select the Tools->Options menu item within VS, navigate to the "Text Editor->HTML" node and uncheck the "Navigation Bar" checkbox option.

The navigation toolbar above your html page or html source of your aspx page will be hidden.

You can always enable this by reversing the above process.

After hiding it, if it is not reflecting in your page, try closing and re-opening your aspx/html file.

Labels: , , , , , ,

Working with Dynamic Controls

Accessing dynamic controls created on the page is a bit tedious job. But with the help of generics we can actually access n number of dynamic controls created on the page.



public T FindControl(Control container, string id) where T : Control

{

return (container.FindControl(id) as T);

}


This function takes the id of the control we want to find and the control it's in, casts it to the type you specify and returns.

Example :


TextBox txtBox = FindControl(this.wrapper, "mytextbox");


This can be further expanded, by creating property for multiple methods.


private TextBox _MyTextBox;

public TextBox DynamicTextBox

{

get

{

if (_MyTextBox == null)

{

_MyTextBox = FindControl(this.wrapper, "mytextbox");

}

return _MyTextBox;

}

}


Now we can simply use the dynamic controls like anyother controls in the page.


Label1.Text = this.mytextbox.Text.ToString();


Happy Coding...

Labels: , , , , ,

Dynamics CRM 4.O SDK for IPHONE

Dynamics CRM 4.O for Iphone is on the way. The developers are working on a version of the Dynamics CRM 4 SDK that will work with the iPhone via MonoTouch. Here is a preview of it creating an account in Dynamics CRM using the MonoTouch C# library. They are creating this to speed up development of xRM solutions that can leverage the power of touch based mobile devices as well as the Dynamics CRM platform.



As MonoTouch doesn't support web services natively yet, therefore they had to use the HttpWebRequest class to make raw calls to the crm web service. they also had to duplicate Request, Response, CreateRequest, CreateResponse, TargetCreateDynamic as well as all Dynamics CRM specific data types (CrmDateTime, CrmDateTimeProperty...etc).

Sample Code

// IFD not supported yet
CrmAuthenticationToken token = new CrmAuthenticationToken
{
AuthenticationType = 0,
OrganizationName = "MagnetismLimited",
CallerId = Guid.Empty
};
CrmWebRequest sdk = new CrmWebRequest("http://virtualcrm03/mscrmservices/2007/crmservice.asmx",
"MAGNETISM", "Administrator", "h3rew3g0", token);
// only difference here is that entity.Properties is an array instead of type PropertyCollection

DynamicEntity entity = new DynamicEntity("account");
entity.Properties = new Property[]
{
new StringProperty("name", accountName),
};
TargetCreateDynamic target = new TargetCreateDynamic
{ Entity = entity };

CreateRequest cr = new CreateRequest { Target = target };
CreateResponse response = sdk.Execute(cr) as CreateResponse;
Console.WriteLine(response.id);

Dynamics CRM SDK for the iPhone is still in its early stages, public beta will be released by the end of October.

Sql Injection Tracking Tool

This is one of the nice tool, i came across, which tracks the mass SQL Injections into the website.

Check this tool: Sql Injection Tracking Tool

You need to signup to get a free tool.

Labels: , , , ,

Using LogParser to get Download Details from IIS

LogParser is the wonderful application which parses all the information in IIS.

I came across a situation, where i needed to get total number of downloads of video files from the website.

Logparser saved my time, by querying the IIS logs for the downloads.



logparser.exe "select top 50 count(*) as downloads, cs-uri-stem from ex*.log where cs-uri-stem like '%.wmv%' group by cs-uri-stem order by downloads DESC"


The above command gives top 50 downloads of movies of type ".wmv"

Happy Coding...

Labels: , , , , , ,

Monday, September 21, 2009

Getting IP Address and ISP name of our Web Page Visitors

We all know how to get the IP address of the user accessing our website.

In .net , we can achieve this by using the Dns.GetHostByName() method.

What if the case, that we need the ISP(Interner Service Provider) name of that IP too.

Code for finding the IP address goes below.


string strHostName = Dns.GetHostName();
IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
IPAddress[] addr = ipEntry.AddressList;
string strIp = addr[0].ToString();


Now we got the IP address of our web page visitor.

Lets find the ISP NAME of that visitor.

For this , first we need to know the Regional Internet Registry that allocates IP and AS numbers.

If the IP address is from the ASIA PACIFIC REGION,we need to query the APNIC.NET, who holds the IP addresses list for ASIA PACIFIC.

And if the IP address is from the American region, we need to query the ARIN.NET(American Registry for Internet Numbers).

For other regions pls. google and find out the respective registry.

Lets assume, the visitor is from the asia region, we got the IP address from the steps above and now lets find out the ISP name of that visitor.

using System.Net.Sockets;
using System.IO;

string ipaddress = ""; // ip address goes here
string strResponse = "";
NetworkStream stream;
StreamReader reader;
StreamWriter writer;
TcpClient tcpc;
tcpc = new TcpClient();
tcpc.Connect("whois.apnic.net", 43);
stream = tcpc.GetStream(); // Get refrence to opened Network stream
reader = new StreamReader(stream); // Lets assign reader to stream
writer = new StreamWriter(stream); // lets assign writer to stream
writer.WriteLine(ipaddress);
writer.Flush();
while (!reader.EndOfStream)
{
strResponse += reader.ReadLine() + Environment.NewLine;
}
stream.Close();


Now you got the response stream in strResponse, you can iterate through the response , to get the ISP NAME.

The same method is applicable to get the ISP in American Region.

Instead of "whois.apnic.net" , we need to use "whois.arin.net".

We can manipulate the code, in several ways to get the different infomation about an IP address.


Happy coding...

Labels: , , , , , ,

Error Handling in Web.Config

If you do not call Server.ClearError or trap the error in the Page_Error or Application_Error event handler, the error is handled based on the settings in the <customerrors> section of the Web.config file. In the <customerrors> section, you can specify a redirect page as a default error page (defaultRedirect) or specify to a particular page based on the HTTP error code that is raised. You can use this method to customize the error message that the user receives.

If an error occurs that is not trapped at any of the previous levels in your application, this custom page is displayed. This section demonstrates how to modify the Global.asax file so that Server.ClearError is never called. As a result, the error is handled in the Web.config file as the last point to trap the error.

1. Open the Global.asax file from the previous example.
2. Comment out the Server.ClearError line to ensure that the error surfaces in the Web.config file.
3. Save your changes to Global.asax. Your code should now appear similar to the following:


using System.Diagnostics;

protected void Application_Error(object sender, EventArgs e)
{
Exception objErr = Server.GetLastError().GetBaseException();
string err = "Error Caught in Application_Error event\n" +
"Error in: " + Request.Url.ToString() +
"\nError Message:" + objErr.Message.ToString() +
"\nStack Trace:" + objErr.StackTrace.ToString();
EventLog.WriteEntry("Sample_WebApp",err,EventLogEntryType.Error);
//Server.ClearError();
//additional actions...
}


4. Add the following code to the <customerrors> section to redirect the user to a custom page:

<customerrors defaultredirect="http://hostName/applicationName/errorStatus.htm" mode="On">
</customerrors>



Although you can reference a default error page in the value of the defaultRedirect attribute in the <customerrors> section, you can also specify a particular page to redirect to based on the HTTP error code that is raised. The child element allows for this option. For example:

<customerrors defaultredirect="http://hostName/applicationName/errorStatus.htm" mode="On">
<error redirect="filenotfound.htm" statuscode="404">
</error>

</customerrors>

Notice that the <customerrors> section includes a mode attribute that is set to On. The mode attribute is used to control how the error redirection occurs. For example, if you are developing the application, you most likely want to see the actual ASP.NET error messages and do not want to be redirected to the more user-friendly error page. The mode attribute includes the following settings:

* On: Unhandled exceptions redirect the user to the specified defaultRedirect page. This mode is used mainly in production.
* Off: Users receive the exception information and are not redirected to the defaultRedirect page. This mode is used mainly in development.
* RemoteOnly: Only users who access the site on the local computer (by using localhost) receive the exception information. All other users are redirected to the defaultRedirect page. This mode is used mainly for debugging.

Labels: , , , , ,

Handling Application_Error Method

Similar to the Page_Error event handler, you can use the Application_Error event handler to trap errors that occur in your application. Due to the event's application-wide scope, you can log of application error information or handle other application-level errors that may occur.

The sample to follow is based on the preceding Page_Error code sample and would be fired if the error in Page_Load was not trapped in the Page_Error event handler. The Application_Error event handler is specified in the Global.asax file of your application. For simplicity, the steps in this section create a new page in which to throw the exception, trap the error in the Application_Error event handler of the Global.asax file, and write the error to the event log. The following steps demonstrate how to use the Application_Error method:

1. Add a new file named AppEvent.aspx to your project.
2. Add the following code to AppEvent.aspx:

void Page_Load(object sender, System.EventArgs e)
{
throw(new ArgumentNullException());
}


Note The information discussed in the "Page_Error" section about the AutoEventWireup attribute also applies to the code sample in this step. See the information in the "Page_Error" section for more details.
3. From the File menu, click Save AppEvent.aspx.
4. Add the Application_Error event handler to the Global.asax file to trap the error that you throw in the Page_Load event handler of the AppEvent.aspx page. Notice that you must add another using statement for the System.Diagnostics namespace to Global.asax to use the event log.

Add the following code to the Global.asax file:
using System.Diagnostics;

protected void Application_Error(object sender, EventArgs e)
{
Exception objErr = Server.GetLastError().GetBaseException();
string err = "Error Caught in Application_Error event\n" +
"Error in: " + Request.Url.ToString() +
"\nError Message:" + objErr.Message.ToString()+
"\nStack Trace:" + objErr.StackTrace.ToString();
EventLog.WriteEntry("Sample_WebApp",err,EventLogEntryType.Error);
Server.ClearError();
//additional actions...
}


5. Save the Global.asax file.
6. In Visual Studio .NET, on the Build menu, click Build.
7. Right-click the page, and then click View in Browser. In this case the page will be blank, however, you should notice that a new entry has been added in the event log. This sample makes an entry in the Application log, which is accessible from the Event Viewer. After logging the error you might want to redirect the user to another more user-friendly error page, or perform some additional actions if needed.


Error Handling in Web.Config

Labels: , , , ,

Error Handling in .net 3.5

The Page_Error event handler provides a way to trap errors that occur at the page level. You can simply display error information (as the sample code to follow does), or you can log the event or perform some other action.

Note This example displays detailed error information in the browser only for demonstration purposes. You will want to be cautious when displaying detailed information to the end user of the application, especially when the application is running on the Internet. A more appropriate action would be to display a message to the user notifying them that an error has occurred, and then actually logging the specific error details in the event log.

This example throws a null exception, which forces an error to occur in the Page_Load event handler. Follow these steps to create the initial page that will demonstrate using the Page_Error event handler.
  1. Follow these steps to add a new file named PageEvent.aspx to your project:

    1. Open Microsoft Visual Studio .NET.
    2. In Solution Explorer, right-click the project node, point to Add, and then click Add Web Form.
    3. In the Name text box, type PageEvent.aspx, and then click Open.


  2. Add the following code to PageEvent.aspx:


void Page_Load(object sender, System.EventArgs e)
{
throw(new ArgumentNullException());
}

public void Page_Error(object sender,EventArgs e)
{
Exception objErr = Server.GetLastError().GetBaseException();
string err = "Error Caught in Page_Error event" +
"Error in: " + Request.Url.ToString() +"Error Message: " + objErr.Message.ToString()+"Stack Trace:" +
objErr.StackTrace.ToString();
Response.Write(err.ToString());
Server.ClearError();
}



Note In this code sample, the AutoEventWireup attribute is not explicitly set. If you do not explicitly assign a value to the AutoEventWireup attribute, the default value true is used. If you are using Visual Studio .NET to develop your applications, the Web Form template code explicitly sets the AutoEventWireup attribute value to false. There is an important difference between the default value that ASP.NET uses, and the default value that the Visual Studio .NET template code assigns to this attribute. If the AutoEventWireup attribute value is set to false, the event handlers that are declared in the .ASPX page do not fire. This may be confusing if you do not know about this functionality.
3. From the File menu, click Save PageEvent.aspx.
4. Right-click the page, and then click View in Browser to run the page. Notice that the error is thrown and reported according to the code specifications.

Note You may notice that the code issues a call to Server.ClearError. This prevents the error from continuing to the Application_Error event handler.

In addition, you should also take note of the Inherits attribute in the @ Page directive. If Inherits is set, you must build the project before you browse to the page. If you do not build the project first, you receive the following error message:

'Project.PageEvent' is not a valid type


Using Application_Error

Labels: , , , ,

Using LINQ in String Collections

By using LINQ we can query the String Collections.

How ? Find it below..

Assume that you have a collection of strings.

####Code Begin####

String [] Names = {"naren","mandhir","vishal","vinod","rajesh","mani","pandey"};

Lets find the Names whose length is greater than 5, using LINQ.

IEnumerable Name = from n in Names where n.lenght  > 5 select n;

Thats it, lets print the names.

foreach(string strName in Name)
{
Console.WriteLine("{0}", name);
}

####Code Ends####

And the output will be:

mandhir
vishal
rajesh
pandey

Note : System.Linq namespace is must for all linq queries used in your .net page.

Happy Coding...                 

Labels: , , , , , ,

Saturday, September 19, 2009

SQL in .net Using LINQ



Assume that you have a table with a datetime field. You need to get the result grouped by both month and

 year and also you need number of records that falls into the grouped category.

This can be done easily with the help of LINQ.

####Code Starts####

var grouped = from p in groups

group p by new { month = p.Create.Month,year= p.Create.Year } into d

select new { dt = string.Format("{0}/{1}",d.Key.month,d.Key.year), count = d.Count() };
 
####Code Ends####
 
Thats is , you got the result.
 
Happy Coding..

Querying the DataTable in .Net

The best method for holding data collection in .net programming is by using DataTable.

By holding the data in datatable enables the programmer to query it, whenever needed and therefore avoiding connecting to the database.

Lets assume we have a datatable with some user registration data having UserName and State columns.

Now we are Querying the DataTable for a username like 'narenmcpd'.

####Code Starts####
string searchQuery = "USER_NAME LIKE ('%narenmcpd")";

DataView objdv = new DataView(objdt, searchQuery, "", DataViewRowState.CurrentRows);

####Code Ends####

Thats it, now we got the result into the dataview objdv.

If nothing meets the query, the dataview objdv will be null.

This is the way of querying the datatable in .net programming.

we can query n number of columns by manipulating the searchquery.

For example, if we need to query the datatable for both the UserName and State columns in the above example.

####Code Starts####

string searchQuery = "USER_NAME LIKE ('%narenmcpd")";

searchQuery = searchQuery + " AND state LIKE ('%delhi%')";

DataView objdv = new DataView(objdt, searchQuery, "", DataViewRowState.CurrentRows);

####Code Ends####

Happy Coding..

Labels: , , , ,

Converting DataView into DataTable

In the middle of our programming there will be situations, where we have our dataview to be converted into datatable, may be for searching..

We can achieve this by using Enumerator.

Follow the below code to achieve this.

Assume objDataView is our DataView, which we are converting into DataTable named obNewDt.


DataTable obNewDt = objDataView.Table.Clone();
int idx = 0;
string[] strColNames = new string[obNewDt.Columns.Count];
foreach (DataColumn col in obNewDt.Columns)
{ strColNames[idx++] = col.ColumnName; }
IEnumerator viewEnumerator = objDataView.GetEnumerator();
while (viewEnumerator.MoveNext())
{
DataRowView drv = (DataRowView)viewEnumerator.Current;
DataRow dr = obNewDt.NewRow();
try
{
foreach (string strName in strColNames)
{
dr[strName] = drv[strName];
}
}
catch (Exception ex)
{
throw ex;
}
obNewDt.Rows.Add(dr);
}

Your DataTable obNewDt is ready for your further programming.

Happy Coding...

Labels: , , , , , , ,

Deleting TFS Project

Ever tried deleting a TFS project created accidentally??.

As Team foundation server is not having any UI functions to delete the project, we can do this through command line.

Use the below command on your server where TFS is installed and you can completely delete all the traces of the project.

syntax :

TFSDeleteproject [/q] [/force] [/server: servername] teamprojectname

example:

TFSDeleteProject /server:testserver testproject

while specifying the servername please use quotes if the server name has spaces.

Thats it. Now your accidentally/unused project will be removed forever.

Labels: , , , , , ,