Health Check of your ASP.NET 2.0 Web Application

March 8th, 2010 amitmathur31 No comments

One of the best, yet often overlooked, features of ASP.NET 2.0 is health monitoring. I believe it is absolutely essential to be notified of any problems with your web application, and this is where health monitoring comes in handy. Health Monitoring is a natural progression of that approach.

There are three pieces to this puzzle:

Events

You need to decide what you want to be notified about. ASP.NET 2.0 comes with a number of events pre-configured for you. I found just about the best diagram of what events are available out of the box in this how-to (follow the link or click the diagram below).

 

For example, if you want to know about all events, you’ll get bombarded. Every time your site starts up, shuts down, recompiles, etc, an event will be raised. If your method of delivery is email, your inbox will beg for mercy.

If you only want to know about errors (and you always should!), you will be notified about aborted requests, view state errors, unhandled exceptions, etc. In my opinion, you owe your users to monitor at least this much. On the diagram above, it’s everything next to WebErrorEvent and WebRequestErrorEvent.

You may want to zero in on a specific error. Scott Guthrie showed how to log shutdown events with some hacking. Health monitoring comes with a pre-defined event, ApplicationShutdown (#1002) which you can easily wire to achieve the same.

 

<eventMappings>
<add
  name="My site shutdown notifications"
  type="System.Web.Management.WebApplicationLifetimeEvent,
  System.Web, Version=2.0.0.0, Culture=neutral,
  PublicKeyToken=b03f5f7f11d50a3a"
  startEventCode="1002"
  endEventCode="1002" />
</eventMappings>

An event will list the shutdown reason along the following lines:

** Events **
---------------
Event code: 1002
Event message: Application is shutting down. Reason: Configuration
changed.
[...skipped...]

Last, but not least, you can write your own (custom) events. For example, Positive Lookahead raises a custom event every time a review is submitted and sends me an email with detailed information. Implementing and raising custom events is very easy.

Even though I’ve been talking about “defining events,” most likely you won’t need to define anything. Below are listed a handful of interesting events pre-configured for you in 2.0. Class names in parentheses are for your reference. You’ll be able to look them up on the above diagram.

  • “All events” (WebBaseEvent). Anything and everything that happens on your site.
  • “Application Lifetime Events” (WebApplicationLifetimeEvent). Application compilation, start-up and shutdown.
  • “All Errors” (WebBaseErrorEvent). Any and all errors on the site.
  • “Infrastructure Errors” (WebErrorEvent). Compilation, configuration, parse, etc, errors.
  • “Request Processing Errors” (WebRequestErrorEvent). View state and validation errors, as well as all unhandled exceptions.

 

    Providers

    Once you’ve decided what to monitor, you need to decide what to do with notifications. You can have them written to the system event log, sent to the trace (ASP.NET page tracing system), emailed, written to a database, or passed to the Windows Management Instrumentation (WMI). This is where providers come into picture.

    You may write your own provider, for example, to log events via a web service. Below is a diagram of pre-canned providers (click for a bigger image):

Health monitoring allows you to have the same event(s) handled by multiple providers. For example, all site errors can be emailed to you and handed over to a custom provider, should you write one.

If you host a site in a shared environment, you won’t have access to the system event log. This is where email providers, “simple” and “templated”, come to the rescue.

SimpleMailWebEventProvider sends insanely detailed logs. It’s fine as long as you need all that information. To tame the format and content, use TemplatedMailWebEventProvider which allows you to design a template and limit the amount of information that gets put in. Send E-mail for Health Monitoring Notifications shows how to use these two providers. Another extremely helpful how-to, Use Health Monitoring in ASP.NET 2.0, provides additional clues how to set email header, footer, separator, and so on.

 

Rules

Rules bring events and providers together. A rule spells out which events to monitor and how to deliver them.

For example, I’d like to have all errors from my site emailed to me. I’d add the following configuration section to web.config:

<system.web>
<healthMonitoring enabled="true">
<providers>
<add
  name="MailWebEventProvider"
  type="System.Web.Management.SimpleMailWebEventProvider"
  to="[an email here]"
  from="[an email here]"
  buffer="false"
  subjectPrefix="My site crapped its pants: "
  />
</providers>
<rules>
 <add
   name="All errors from my site"
   eventName="All Errors"
   provider="MailWebEventProvider"
   profile="Critical"
  />
</rules>
</healthMonitoring>
</system.web>

<system.net>
<mailSettings>
 <smtp deliveryMethod="Network">
  <network
     defaultCredentials="true"
     host="[your SMTP server]" />
 </smtp>
</mailSettings>
</system.net>

You’ll notice I don’t explicitly declare events here. As discussed before, “All errors” is pre-configured. You will find it here under <eventMappings>. The finer points of what each attribute means are well documented on MSDN. I only want to draw your attention to the profile attribute.

Out of the box, there are two profiles: default and critical.

<profiles>
 <add
  name="Default"
  minInstances="1"
  maxLimit="Infinite"
  minInterval="00:01:00"
  custom="" />
 <add
  name="Critical"
  minInstances="1"
  maxLimit="Infinite"
  minInterval="00:00:00"
  custom="" />
</profiles>

Under the default profile

  • The minimum number of times an event can occur before an event notification is sent is 1.
  • The maximum number of times an event can occur before notifications stop is 2147483647 (infinite).
  • The minimum time interval between two events is one minute.

The critical profile doesn’t throttle the flow of event notifications, so there’s no one-minute limitation, and notifications are dispatched right away. I’m deliberately not getting into a discussion about buffering to keep things simple.

Conclusion

I hope this post gives you enough information to get going with health monitoring. I wanted to keep it on a conceptual level, which is why there was no talk of implementation details.

VN:F [1.6.3_896]
Rating: 0.0/5 (0 votes cast)
Categories: ASP.Net Tags:

Dynamically write text on an image

March 8th, 2010 amitmathur31 No comments

This posts basically concentrates on dynamically writing some text content on image. This technique can be used in many of our development tasks like for developing captcha, printing of email addresses on websites which actually avoids spammers and many other purposes as per the development requirements.

Below given is the sample code to print sometext “Hey! this is me.” on an image.

Namespaces to be used:

using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;

Text and Image load content:

Bitmap bitMapImage = new System.Drawing.Bitmap(Server.MapPath(”Amit.jpg”));
Graphics graphicImage = Graphics.FromImage(bitMapImage);
graphicImage.SmoothingMode = SmoothingMode.AntiAlias;
graphicImage.DrawString(”Hey! This is me.”, new Font(”Arial”, 12, FontStyle.Bold),SystemBrushes.WindowText, new Point(100, 250));
graphicImage.DrawArc(new Pen(Color.Red, 3), 90, 235, 150, 50, 0, 360);

Response.ContentType = “image/jpeg”;
//Save the new image to the response output stream.

bitMapImage.Save(Response.OutputStream, ImageFormat.Jpeg);

graphicImage.Dispose();
bitMapImage.Dispose();

VN:F [1.6.3_896]
Rating: 0.0/5 (0 votes cast)
Categories: ASP.Net, C Sharp Tags:

C# Forms Authentication using ticket and managing user roles in asp.net

February 16th, 2010 amitmathur31 No comments

In this article i am going to describe how to implement Forms authentication using tickets and managing roles based access in ASP.NET using C#

Solution Explorer

For implementing forms authentication without using formsauthentication ticket, read my previous article – Forms Authentication with C# and managing folder lavel access with multiple web.config files

Configuring web.config file in application root

<authentication mode=”Forms”>
<forms defaultUrl=”Default.aspx” loginUrl=”~/Login.aspx”
slidingExpiration=”true” timeout=”20″></forms>
</authentication>

Defining roles and accessibility in root web.config

<location path=”Admin”>
<system.web>
<authorization>
<allow roles=”admin”/>
<deny users=”*”/>
</authorization>
</system.web>
</location>

Defining roles settings for folders and aspx within those folders in web.config file in those folders

<system.web>
<authorization>
<allow roles=”user”/>
<deny users=”*”/>
</authorization>
</system.web>

settings for any logged in member

<system.web>
<authorization>
<deny users=”?”/>
</authorization>

Now after creating Login page we need to authenticate user

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string userName = Login1.UserName;
string password = Login1.Password;
bool rememberUserName = Login1.RememberMeSet;

//Fetch User login information fromthe xml file into Dataset

string xmlFilePath = Server.MapPath(”~/App_Data/LoginInfo.xml”);
DataSet objDs = new DataSet();
objDs.ReadXml(xmlFilePath);
DataRow[] dRow = objDs.Tables[0].Select(”UserName = ‘” + userName + “‘ and Password = ‘” + password + “‘”);
if (dRow.Length > 0)
{
//Fetch the role
string roles = dRow[0]["Roles"].ToString();

//Create Form Authentication ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(20), rememberUserName, roles, FormsAuthentication.FormsCookiePath);

// In the above parameters 1 is ticket version, username is the username associated with this ticket
//time when ticket was issued , time when ticket will expire, remember username is user has chekced it
//roles associted with the user, and path of cookie if any

//For security reasons we may hash the cookies
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);

// add the cookie to user browser

Response.Cookies.Add(cookie);

// get the requested page

string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null)
returnUrl = “~/Default.aspx”;
Response.Redirect(returnUrl);
}

Now to retrieve the authentication and roles information on every request we need to write this code in Global.asax file

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
// look if any security information exists for this request

if (HttpContext.Current.User != null)
{

// see if this user is authenticated, any authenticated cookie (ticket) exists for this user

if (HttpContext.Current.User.Identity.IsAuthenticated)
{

// see if the authentication is done using FormsAuthentication

if (HttpContext.Current.User.Identity is FormsIdentity)
{

// Get the roles stored for this request from the ticket

// get the identity of the user

FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;

//Get the form authentication ticket of the user

FormsAuthenticationTicket ticket = identity.Ticket;

//Get the roles stored as UserData into ticket

string[] roles = ticket.UserData.Split(’,');

//Create general prrincipal and assign it to current request

HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles);
}
}
}
}

To check whether user in in the role or not we need to write this code in every page which provide access on role basis
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.User.IsInRole(”admin”))
{
lblMessage.Text = “Welcome Administrator”;
}
}

VN:F [1.6.3_896]
Rating: 0.0/5 (0 votes cast)
Categories: ASP.Net Tags:

ASP.NET 2.0 – Forms Authentication with C# and managing folder level access with multiple web.config files

February 16th, 2010 amitmathur31 No comments

Authentication in ASP.NET 2.0 is technique to decide how users can access your web application.
Using froms authentication we can decide certain users can access only certain pages or we can control the anonymous access, we can implement folder level access and access based on roles

we can manage the access through web.config file

Read my article on implementing  forms authentication using FormsAuthentication ticket and managing roles

1. First of all create a new website and add a new form , name it Login.aspx
Drag login control on it from the toolbox
Make sure you have a web.config file in root of your application

2. Right click on solution explorer and add new folder , name it membersArea
Add a new from and name it members.aspx
Add a web.config file in this folder.

Now to implement Forms Authentication we need to configure web.config file (in the application root)

For this we need to add Authentication and Authorization tags inside <system.web> tag of web.config

<system.web>
<authentication mode=”Forms”>
<forms defaultUrl=”Default.aspx” loginUrl=”~/Login.aspx”
slidingExpiration=”true” timeout=”20″>
</forms>
</authentication>
</system.web>

Now To restrict access to the membersonly page which is inside membersonly folder so that only members can access this page we need to create a another web.config file inside this folder to provide it’s access rules
In this web.config write this inside <system.web> tag

<system.web>
<authorization>
<deny users=”?”/>
</authorization>
</system.web>

Now for login process and checking the username and password we need to write this code, double click on the login control placed on the Login.aspx page, it will generate Login1_Authenticate event

protected void Login1_Authenticate
(object sender, AuthenticateEventArgs e)
{
bool isMember = AuthenticateUser(Login1.UserName, Login1.Password,
Login1.RememberMeSet);
if (isMember)
{
FormsAuthentication.RedirectFromLoginPage(Login1.UserName,
Login1.RememberMeSet);
}
}

And this for checking username and password, i m using hard coded values

private bool AuthenticateUser(string userName, string password, bool rememberUserName)
{
string userName = “amiT”;
string password = “password”;

if (userName.Equals(userName) && password.Equals(password))
{
return true;
}
else
{
return false;
}
}

VN:F [1.6.3_896]
Rating: 0.0/5 (0 votes cast)
Categories: ASP.Net Tags:

SQL University : An Introduction to BI – Part I

November 23rd, 2009 govindsyadav No comments

Welcome to Class Guys , Well , we will be starting our week of by taking a sneak peek into SQL BI gearing up to the more elaborative and deep understanding about BI and its applications .

Before , just diving in , I would like to mention here , the useful resources , which are being referred here up in this article.

  1. SQL Server Books Online (http://msdn.microsoft.com/en-us/library/ms130214.aspx)
  2. Jorge had written about the Sql server books online , and its availability in his article ,which can be found on http://sqlchicken.com/2009/09/sql-university-basic-tools/

  3. http://www.sqlauthority.com

First of all , a general question I would like to answer about BI .

Q . What is BI and what exactly it is there for ?

Answer : BI Stands for Business Intelligence .

We’ll make it little bit mathematical

BI=Business Intelligence

BI = Business + Intelligence

      Business= (Enterprise , Customary,etc)

      Intelligence= Decision

                  Decision = Data and Analysis

                           Analysis = Skills + Processes + Technologies + Tools(applications)

BI = (Enterprise,Customary,etc) + (Data and analysis)

So, now from above equation its clear that BI Means Analysis of Enterprise/customary Data .

Now , just summing up the above equation in words , BI basically refers to Processes,Skills,Applications,Technologies that are use to support the Decision making Process.

BI Technologies : When we do talk about BI Technologies , then its not just about reporting , but its lot more than reporting .

Just to explain about why BI is lot more than reporting , I would like to state here an live example ( going out of boundaries of BI and sql server) , of ICEBERG . when we see an iceberg , its 10% above the sea water while 90% beneath , so that’s the same thing with Reports , reports are only the visualization of that 90% of what is beneath it i.e a lot things including , Data , OLAP , Text mining ,Querying , Statistical analysis ,Benchmarking ,Predictive Analysis .

Summing up the above we got to know a new equation

BI = Reporting + Data mining + OLAP +Text mining + Benchmarking + Statistical analysis + Predictive Analysis + Querying .

Its Well Said by Danny Siegel about BI , that an effective BI system provides corporations with “one version of the truth”.

What BI is for ?

BI is there for Success of a business , because it helps you in making decisions and when you are able to make correct , accurate decisions on time then only the success is yours . Because if BI is there , then you are handy with your statistical analysis and predictive analysis (future , foreseen analysis) and can better make your decisions to remain competitive and stay ahead .

Hopes , the question we had started off with is answered and we are quite clear about the concept of BI.

Now , another Question Comes out to mind .

Q. What is the History of BI  ? Where all it came from ?

Answer : A basic question , what is the history of BI , how it came into existence and from where it get evolved , is it something new born ??

No , its not something which is recently evolved but today it is used more and more that’s why we are wondering and taking it as some new born , but its nothing like that ,

In a 1958 article, IBM researcher Hans Peter Luhn used the term business intelligence. He defined intelligence as “the ability to apprehend the interrelationships of presented facts in such a way as to guide action towards a desired goal.”

In 1989 Howard Dresner (later a Gartner Group analyst) proposed BI as an umbrella term to describe “concepts and methods to improve business decision making by using fact-based support systems.”. It was not until the late 1990s that this usage was widespread.

Wow , so above we came to know that BI do exists there since from a very long time , but today it is widespread and is present everywhere ,no matter whatever the business is , whatever the technology is , if some system is there , decision is there , BI is THERE .

Now comes another question :

Q. If BI is so vast , then from where to start with .?

Answer : Anywhere , that totally depends upon your choice , you can go for data mining , OLAP ,Text mining , Reporting , that all is your part , you need to decide what best you can do , because there are lots of tools available under BI , but you had to choose which tools you wish to learn , use and master .

Another tricky question :

Q. What language(terminology) does BI Speaks ?

Answer : Sure , that’s very important to learn the BI Language(Terminology) , because unless and until we are familiar with BI Terminology , we won’t be able to get hands on it , so just a quick view of BI Terms :

Aggregation : Information stored in summarized form

Agent : Application (client ) who searched the data and sends the alert.

Alert : Message sent by agents

Attribute : Fields or columns in table ,report ,charts .

Cube : Known as multidimensional format used for viewing and analyzing data .The fundamental structure for data in a multidimensional (OLAP ) System.

Data : Reality , facts stored in and processed.

Data Base : Collection of data

Data Cleansing / Scrubbing : Removing erroneous data

Data Mart : Local Data Warehouse , Small subset of Data warehouse for one or few divisions

Data Migration : Process of moving of data from one environment to other

Data Mining : Digging deep the hidden relationship of data and attributes among each other

Data Transformation : Process after data migration is done ,i.e the step of modifying the data as per the new data warehouse.

Data Warehouse : A storage of Enterprise/ customary data meant for to be analyzed .

Drill down and drill up : Process to move across hierarchy used in OLAP.

ETL : Extract , transform and load makes ETL . i.e get the data , transform it(modify) and migrate it .

DTS : its below ETL , because it’s a tool for ETL .

Star Schema : The simplified database as per the normalized forms of database management system

Fact Table : the table containing :

  1. The fields storing the foreign keys which connect each particular number to the appropriate value in each dimension.
  2. The fields storing the individual number, measure or any numeric value. Example(discount,price,etc)

Measure : A numeric value in fact table

Multidimensional Analysis / OLAP =Online Analytical processing, the technique to process and fetch out results in different –different dimensions of data i.e cubes .(widespread use of graphs and spreadsheets )

Slice : Tool for OLAP Viewing of data through multi dimensions example : Where clause in OLAP.

Dice : Tool for OLAP Viewing of data through multi dimensions

Replication : Replica of one data at another place.

Schema : Logical arrangement of data within database.

MDX : Multidimensional expressions, the query language for OLAP ,

Hopes , now ,as we have discussed couple of basic questions about BI ,we are ready with to get dive into the BI sea , but before getting in it , we’ll have a break and will continue on this interactive session in the same manner (if nobody complains of this is not a good idea to learn about what BI is .?) .

While writing this article , I was just wondering up from where to start this article on , because it is such a vast area to discuss on with that I cannot see the boundaries of , then thought of , why not to make it more interactive in an question / answer manner . I myself started asking questions to me as a layman and then tried to answer the questions .Hope you’ll enjoy this question answer class of BI , not to mention here , that if you do have any question up there in mind that is not covered up or required some more lights , then do revert back , I am waiting for your questions and would try my best to answer them .

You can reach me at govindsyadav[@]soliddotnet[dot]com

VN:F [1.6.3_896]
Rating: 4.3/5 (3 votes cast)