Sukumar Raju's Blog

MCP

Sponsors

Tags

News

SharePoint SharePoint

More reading these days Patterns and practicces


Interesting to work with ASP.NET Membership provider

Suggested Reading C# Book


patterns & practices Application Architecture Guide 2.0


MVP Blog Badge.

Grab this badge here!


ASP.NET Web API Logging and Troubleshooting

Logging exceptions to persistent store or email alert with exception stack helps developer to troubleshoot issues without having to debug the application. This practice helps in exception trend monitoring and improve the application. In the applications where security is high priority it is feasible to trace and log security exceptions. Mostly all of the tracing and logging technologies provide configuration driven trace levels i.e., Information, Warning, Error etc.

This article discusses various tracing and logging technologies and walks through 'configuring ASP.NET Web API application to log unhandled exceptions to database and generate email alert with exception stack using ELMAH'.

AppFabric provides two services for monitoring and caching services.

  1. Monitoring services
  2. Caching services

AppFabric is IIS extension that provides a dashboard to monitor and troubleshoot issues with in WCF and WF applications and services. Installation & configuring AppFabric creates database to store service trace as well. AppFabric installation and configuration process is discussed in another blog post.

AppFabric does not support ASP.NET Web API services to monitor and troubleshoot issues.

In order to log unhandled exceptions from ASP.NET Web API there are number of alternatives as outlined below.

Configuring Logging application block to email exception block is discussed in my blog article at http://weblogs.asp.net/sukumarraju/archive/2010/08/21/email-exception-stack-using-logging-application-block-email-trace-listener.aspx 

 Log4Net provides another mechanism to log trace to text file or to database or custom location.

Being built on top of ASP.NET run time WebForms, Web API, MVC, Single page and SignalR can utilise above alternative technologies in addition to ASP.NET Health monitoring to log exceptions or trace to desired location for applications troubleshooting.

ASP.NET_Runtime

Logging unhandled exceptions using ELMAH

ELMAH is an open source tool for ASP.NET services, exceptions that are thrown in ASP.NET applications trigger event handlers in ELMAH tool. It provides pluggable out of box implementation.

Note that all the frameworks that run on ASP.NET can take advantage of ELMAH to log unhandled exceptions.

Step 1: Get the assembly from Nuget

PM> Install-Package Elmah.Contrib.WebApi

Installing the assembly updates application Web.config SectionGroup, connection Strings and Http modules.

Now in memory exception logging for the application, which can be accessed by navigating to /elmah.axd">/elmah.axd">/elmah.axd">http://<port>/elmah.axd as shown below.

Elmah_Dashboard

Note that when the application is stopped or app pool recycles the exception will be lost. Because these are in memory exceptions. Selecting the Details hyperlink in the above dashboard opens detailed exception stack with complete server variables and values.

Step 2: Log exceptions to SQL Server database

To store exceptions to SQL Server database get the assembly.

   1: PM> Install-Package elmah.sqlserver

Adding the package adds App_Readme folder with SQL script to generate database tables and stored procedures for logging exceptions. Also adds <errorLog> element to Web.config and connection String as below.

   1: <connectionStrings>
   2:     <add name="elmah-sqlserver" 
   3: connectionString="Data Source=****;
   4: User ID=****;Password=****;
   5: Initial Catalog=****;" 
   6: providerName="System.Data.SqlClient" />
   7:  
   8: <!-- of course it is required to update above SQL connection-->
   9:  
  10: <security allowRemoteAccess="false" />
  11: <errorLog type="Elmah.SqlErrorLog, Elmah" 
  12: connectionStringName="elmah-sqlserver"
  13: applicationName="Contact Manager" />
  14:  
  15: <!-- applicationName added to distinguish the applications in the 
  16: centralised exceptions database -->

That is it! Unhandled from the application logged into database as shown below.

elmah_db_log

 

Step 3: Email exception stack

Provide SMTP (mail server), port, From and To email addresses in <errorMail> section as shown below.

   1: <elmah>
   2:   <errorMail from="robot@elmah" to="dev@groupcom"  
   3:   async="true" smtpServer="xxxx.xxx.xxxx.xx" smtpPort="25"/>
   4: </elmah>

This generates email alerts with exception stack as shown below.

elmah_email_stack

Note that running applications can take advantage of ELMAH error logging, all it requires is copying required assemblies and configuration into Web.config.

Conclusion:-  Logging all web applications exceptions to database helps to troubleshoot, it is feasible to implement a dashboard with the exceptions from various applications that are utilising ELMAH. All it requires to configuring ELMAHR (Elmah + SignalR), real time web framework. This is for another blog article !!

Resources

ASP.NET Web API testing using NUnit framework

Hello

I am not intending to provide an introduction for this topic, you can download the solution that I uploaded at MSDN code samples at http://code.msdn.microsoft.com/ASPNET-Web-API-NUnit-ac687169

Please note that in above solution the Web API service returns DTO in Json format to client.

To concise the solution consists of ASP.NET Web API project and a test project for testing service controllers and service Http response using HttpClient.

complete source is available at above URL from MSDN code sample. Here is the actual implementation of the same, which is replicated.

Controllers testing

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Text;
   5:  
   6:  
   7: using ContactManager.Controllers;
   8: using ContactManager.Models.Repository;
   9: using NUnit.Framework;
  10: using System.Web.Http;
  11: using ContactManager.Models.Entities;
  12:  
  13: namespace ContactsNUnitTests
  14: {
  15:     /// <summary>
  16:     /// Contains NUnit test cases for ContactsController
  17:     /// </summary>
  18:     [TestFixture]
  19:     public class ContactsControllerTests
  20:     {
  21:         ContactsController contactsController;
  22:         ContactRepository repository;
  23:         
  24:         int count;
  25:         int contactId;
  26:         
  27:         [SetUp]
  28:         public void Setup()
  29:         {
  30:             //create an instance of contactRepository
  31:             repository = new ContactRepository();
  32:             
  33:             //Create an instance of controller by passing repository
  34:             contactsController = new ContactsController(repository);
  35:             
  36:             //Number of records
  37:             count = contactsController.Get().contacts.Count;
  38:             
  39:             //Pass contact ID and store the retrieved contact ID
  40:             contactId = contactsController.Get(1).contact.Id;
  41:         }
  42:  
  43:         [Test]
  44:         public void GetAllContacts()
  45:         {
  46:           Assert.IsTrue(count > 0);
  47:         }
  48:  
  49:         [Test]
  50:         public void GetContact()
  51:         {
  52:           Assert.IsTrue(contactId.Equals(1));
  53:         }
  54:     }
  55: }

Service response testing

Testing service Http response using HttpClient

   1: namespace ContactsNUnitTests.ServiceHttpResponse
   2: {
   3:     using System;
   4:     using System.Collections.Generic;
   5:     using System.Linq;
   6:     using System.Text;
   7:  
   8:     using NUnit.Framework;
   9:     using System.Net.Http;
  10:     using System.Configuration;
  11:     using System.Net;
  12:     using System.Net.Http.Headers;
  13:  
  14:     /// <summary>
  15:     /// Service Http Response tests
  16:     /// </summary>
  17:     public class HttpResponseTests
  18:     {
  19:         private HttpClient client;
  20:  
  21:         private HttpResponseMessage response;
  22:  
  23:         [SetUp]
  24:         public void SetUP()
  25:         {
  26:             client = new HttpClient();
  27:             
  28:             client.BaseAddress = new Uri(ConfigurationManager.AppSettings["serviceBaseUri"]);
  29:             response = client.GetAsync("contacts/get").Result;
  30:         }
  31:  
  32:         [Test]
  33:         public void GetResponseIsSuccess()
  34:         {
  35:             Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
  36:         }
  37:  
  38:  
  39:         [Test]
  40:         public void GetResponseIsJson()
  41:         {
  42:             client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  43:             
  44:             Assert.AreEqual("application/json", response.Content.Headers.ContentType.MediaType);
  45:         }
  46:  
  47:         [Test]
  48:         public void GetAuthenticationStatus()
  49:         {
  50:             Assert.AreNotEqual(HttpStatusCode.Unauthorized,
  51:  response.StatusCode);
  52:  
  53:         }
  54:     }
  55: }

References:

http://www.peterprovost.org/blog/2012/06/16/unit-testing-asp-dot-net-web-api

http://www.asp.net/web-api/overview/testing-and-debugging

http://blogs.msdn.com/b/youssefm/archive/2013/01/28/writing-tests-for-an-asp-net-webapi-service.aspx

Free eBook: 50 Ways to Avoid, Find and Fix ASP.NET Performance Issues
50 Ways to Avoid, Find and Fix ASP.NET Performance Issues
MVC for Web Forms Developer
Below video tutorial walks through the MVC pattern, similaries between MVC and Web Forms and then implements a MVC application from scratch.

Reference: MSDN Channel 9: TechEd 2010

Free eBook: Intro to asp.net mvc 4: https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&ved=0CD0QFjAA&url=http%3A%2F%2Fdownload.microsoft.com%2Fdownload%2F0%2FF%2FB%2F0FBFAA46-2BFD-478F-8E56-7BF3C672DF9D%2FIntro%2520to%2520ASP.NET%2520MVC%25204%2520with%2520Visual%2520Studio%2520-%2520Beta.pdf&ei=nmUnUYWDF-Wd0QWW_IGQCg&usg=AFQjCNHUve5OvbugUO-yLtrNX7EDJzEnnA&bvm=bv.42768644,d.d2k

Best source: Readable online at  http://ofps.oreilly.com/titles/9781449320317/ch_MvcForWebFormsDevs.html

Refer http://www.asp.net/mvc for tutorials, vieos, samples, books and more resources

InfoPath Forms Services : Activate or deactivate a form template for a site collection

After InfoPath form has been published and uploaded to the server from SharePoint admin site in order to add the content type with in SharePoint document library it is required to activate the form in SharePoint site as below.

1. Select Site Settings

2. Under Site Collection Administration tab select Site collection features hyper link

3. On the Site Collection Features page, choose the row for the form that needs to be activated or deactivated, then select Active or Deactivate button.

image

 

References:

http://office.microsoft.com/en-gb/sharepoint-server-help/activate-or-deactivate-a-form-template-for-a-site-collection-HA010167281.aspx

http://office.microsoft.com/en-gb/sharepoint-server-help/demo-deploy-an-administrator-approved-form-template-HA010205047.aspx?CTT=3

eBooks from Microsoft

Latest technical eBooks from Microsoft

http://blogs.msdn.com/b/mssmallbiz/archive/2012/07/27/10334262.aspx

Few more here

SharePoint 2010 Training resources

Few Microsoft provided articles and free video training resources.

 

SharePoint 2010 Developer Training Kit MSDN

Video center for SharePoint 2010 development

Learn SharePoint Server 2010

Technet.Microsoft SharePoint Server 2010 videos

SharePoint server virtual labs

Microsoft demo showcase suite

How I passed SharePoint 2010 exam 70-667

Microsoft SharePoint 2010 showcase

 

MCTS Certification

Exam 70-667: TS: Microsoft SharePoint 2010, Configuring
Exam 70-573: TS: Microsoft SharePoint 2010, Application Development

Extract Year and Text between brackets using Regular Expressions

Hi All,

It is straight forward to use Regular expressions to extract text from a string. Below code snippet demos extracting year from a string and Text in between brackets from a string.

Extract Text between brackets

   1: static void Main(string[] args)
   2:         {
   3:             
   4:             //Regular Expression pattern 
   5:             string Pattern = @"\((.*?)\)";
   6:             //Regular Expression with pattern
   7:             Regex re = new Regex(Pattern);
   8:             string strSearch = "Microsoft (www.msdn.com)";
   9:  
  10:             //Loop through the string and output the matching text
  11:             foreach(Match m in re.Matches(strSearch))
  12:             {
  13:              Console.Write(m.Value.Replace("(",string.Empty).Replace(")",string.Empty).Trim());
  14:                 
  15:             }
  16:             Console.ReadKey();
  17:         }

Extract Year from string

   1: //Regular expression for year
   2: string pattern = "([0-9]{4})";
   3: Regex re = new Regex(pattern);
   4: string txtYear = string.Empty;
   5:  
   6: string strSearch = "SharePoint 2010";
   7:  
   8: foreach (Match m in re.Matches(strSearch))
   9: {
  10:     txtYear = m.Value;
  11:     Console.Write(txtYear);
  12: }   
  13:  
  14: Console.ReadKey();
  15:         }

References

http://support.microsoft.com/kb/308252

http://msdn.microsoft.com/en-us/library/ms228595(v=VS.80).aspx

http://www.mikesdotnetting.com/Article/46/CSharp-Regular-Expressions-Cheat-Sheet

Configuring WCF service to utilise Enterprise Library: Logging application to log data to database

This article walks through the 'Enterprise Library: Logging application' configuration process to log data to database using WCF service.

Note that regardless of Web service type i.e., SOAP or RESTful the configuration process is same.

Technical environment:-

Visual Studio 2010 with .NET 4.0
Enterprise library 5.0
WCF

ASP.NET Web application on Client end.

Open Service Web.config using Enterprise library configuration tool

Open the Service Web configuration file using Enterprise library configuration tool, which can be found at C:\Program Files\Microsoft Enterprise Library 5.0\Bin [assuming that you chosen C: drive for Enterprise library installation process]

EntLib_Configuration_Tool

[Image: Enterprise library configuration tool location]

Note: Make sure that Service Web.config contains database connection string in connectionStrings section.

Step 1: Open Enterprise library configuration tool

Below screenshot shows the configuration tool after opening the service web.config file.

Service_Web_Configuration_Initail
[Service web.configuration with in Enterprise Library configuration tool]

Step 2: _Choosing the Default database instance with in Database settings section

Choose the Default Database Instance from drop down list, in this example Logging is chosen as default one as shown below.

Default_Database_Instance

[Default Database Instance]

Step 3: Add Logging block block

Choose 'Logging Settings' to add logging application block from Blocks menu as shown below screenshot.

Add_Logging_Block

[Add_Logging_Block]

Step 4: Expand Logging Settings section

In order to configure Logging block, expand logging settings by clicking the icon on the  left hand side as marked in red below image.

Expand_Logging_Settings

[Expand_Logging_Section_Image]

Step 5: Add Database Trace listener

From Logging Target Listeners selecting the + opens 'Add Logging Target  Listeners'.

Choose 'Add Database Trace Listener' from context menu that is opened from
'Add Logging Target Listeners' as shown below screenshot.

Add_Database_Trace_Listener

[Add-database-trace-listener]

Step 6: Choose Database Trace Listener as default listener

Make sure that 'Database Trace listener' is chosen as default listener in Logging settings --> General section as shown in below image.

Choose_Database_Trace_Listener_As_Default

[Choose-db-trace-listener]

Note:- By selecting right mouse button on particular configuration section it is feasible to Validate particular section as shown in below image.

Config_Sections_Validate

[Configuration-Sections-Validate]

Step 7: Enterprise library application block DLL references

Make sure that below mentioned references from Enterprise library API are added to
the service WCF service as shown in below image.

These DLLs are available from Enterprise Library installation at

C:\Program Files\Microsoft Enterprise Library 5.0\Bin

Required-DLL-References

[Required DLLs]

Step 8: Add required 'using' statements

 

   1: using Microsoft.Practices.EnterpriseLibrary.Logging;
   2: using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
   3: using Microsoft.Practices.EnterpriseLibrary.Logging.ExtraInformation;
   4: using Microsoft.Practices.EnterpriseLibrary.Logging.Filters;
   5: using Microsoft.Practices.EnterpriseLibrary.Data;
   6: using System.Data;

Step 9: Create a method that utilises Logging application block to log data to database.

Create a private LogWriter variable as below;

   1: private LogWriter writer = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>(); 

Logger method can be similar to the one below or it can have more parameters.

   1: ///Create a logEntry object and write to database
   2: public void  DbLogger(string _Title, string _Message, string _MachineName)
   3: {
   4:     LogEntry logEntry = new LogEntry();
   5:  
   6:     logEntry.Title = _Title;
   7:     logEntry.Message = _Message;
   8:     logEntry.MachineName = _MachineName;
   9:     logEntry.TimeStamp = DateTime.Now;
  10:  
  11:     writer.Write(logEntry);
  12: }

Step 10: Test the functionality with a client instance

   1: protected void Page_Load(object sender, EventArgs e)
   2:         {
   3:             //Create an instance of client proxy 
   4:             Service1Client client = new Service1Client();
   5:             client.Open();
   6:  
   7:             try
   8:             {
   9:                 client.DbLogger("Logger service consumer", "Testing the Logger db functionality", "My machine");
  10:             }
  11:  
  12:             catch (Exception ex)
  13:             {
  14:                 Response.Write(ex.InnerException.Message.ToString());
  15:             }
  16:         }

Running the client app with above should log data to Logging database, which can be installed from scripts provided with Hands-on-Labs referenced below.

image

Creating Logging database

Note that Logging database can be created by running the SQL script provided with Enterprise Library 5.0 Hands on labs, which can be downloaded at
http://www.microsoft.com/download/en/details.aspx?id=6932

Reference

http://msdn.microsoft.com/en-us/library/ff632023.aspx

http://www.microsoft.com/download/en/details.aspx?id=6932

http://msdn.microsoft.com/en-us/library/ff650510.aspx

Visual Studio 2011 LightSwitch released

VS LightSwitch 2011 is released today to get the development/deployment process up and running in few minutes..

Read more at http://www.microsoft.com/visualstudio/en-us/lightswitch

More Posts Next page »