Monday 22 March 2010

Fantasy Cricket

 

Custom Profile Provider:

http://www.bestechvideos.com/2009/04/07/asp-net-how-do-i-create-a-custom-profile-provider

 

 

Password Recovery : 

The passwordFormat property specifies how the provider will store passwords, and will impact a number of other membership features. The SqlMembershipProvider supports three formats: Hashed (the default and most secure format), Encrypted, and Clear. The hashed format passes a user’s plaintext password and a random salt value through a one-way hash algorithm before storing the password. You cannot retrieve a hashed password. To validate a password, the provider has to salt and hash the entered password and compare the two hash values (for more information on hashing passwords, seePass The Salt). The provider can also store encrypted passwords (which can be decrypted and retrieved), or store passwords in the clear (which is not recommended).

 http://odetocode.com/articles/427.aspx

 

 

Mail Settings:

  <system.net>
    <mailSettings>
      <smtp>
        <network
             host="relayServerHostname"
             port="portNumber"
             userName="username"
             password="password" />
      </smtp>
    </mailSettings>
  </system.net>

 

Session Management:

Problem : Session objects is not working properly.Some times it will work some times not(getting empty).

If your problem is that your page is getting timed out before the timeout value set.
Then I will suggest you to change your web.config code like this.

ASP.NET Syntax

  <sessionState mode="StateServer"   cookieless="false"   timeout="30"/>

Here I have changed the session state to a seperate worker process (ASP state management server).
It is recommended to move your session into the stateserver or SQL server state management in the production environment.


Note: You need to start the 'ASP.NET State Service' windows service on the web server in order to make this code work.

image

Diff between diff session states:

http://forums.asp.net/p/7504/7504.aspx

If You want to use StateServer on Remote Servers (Hosting Machines) use the following code:

<sessionState mode="StateServer"  stateConnectionString="tcpip=127.0.0.1:42424"
                    stateNetworkTimeout="20"/>

“stateConnectionString” Specifies the server name or address and port where session state is remotely stored. The port value must be 42424. This attribute is required when mode is the StateServer value.

To improve the security of your application when using StateServer mode, use Protected Configuration to help protect the stateConnectionString value by encrypting the sessionState section of the configuration.

The default is "tcpip=127.0.0.1:42424".

stateNetworkTimeout” Specifies the number of seconds that the TCP/IP network connection between the Web server and the state server can be idle before the request is canceled. This attribute is used when the mode attribute is set to the StateServer value.

The default is 10 seconds.

 

Model PopUp

The ModalPopup extender is used to pop open a standard ASP.NET Panel control as a modal dialog box.

http://www.asp.net/learn/ajax-videos/video-85.aspx

Download  ajax tool kit from http://ajaxcontroltoolkit.codeplex.com/releases/view/11121.

Friday 19 March 2010

Enterprise Library 4.1 – Exception Application Block

 

I am using logging block in order to log all the exceptions.Different Logging blocks can be found at .

Rolling flat file trace listener

Email Trace Listener

Database Trace Listener

 

In this scenario default logging block contains event log trace listener.i.e All the exceptions will be sent to event log which we can find by entering ‘eventvwr’ in start—> Run.

start—> Run –> enter ‘eventvwr’ –> Application:

You can view the errors generated by our application as follows.

image

To do this follow the following steps:

Step 1 :

Add the following references to the web site.i.e Add the following files to the bin folder in your web site.

Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.EnterpriseLibrary.Data.dll
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.dll
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.dll
Microsoft.Practices.EnterpriseLibrary.Logging.dll
Microsoft.Practices.EnterpriseLibrary.Logging.dll.exclude
Microsoft.Practices.ObjectBuilder2.dll

Step 2 :

Add the code below to the cs file of any aspx page. (Exception generated code.)

       try
       {
           int i = 1;
           int j = 0;
           i = i / j;
       }
       catch (Exception ex)
       {

           //Logger.Write("Our Message : "+ex.Message, "General");
           ExceptionPolicy.HandleException(ex, "MyPolicy");
       }

 

ExceptionPolicy.HandleException will handle the exception and will go to the exception block in web.config to find the place to write the exception.

Logger will write the error message based on logging application block configuration i.e here to the event log.

We can use either of them.

Here we are configuring it to be event logger.

Step 3:

Open web.config file in Enterprise Library Configuration tool and add the exception block and logging application block as..

a) Right click on root of the application –> New –> Exception Handling Application Block

image

b) Now Right Click on the created Exception Application Block –> New –> Exception Policyimage

Rename the Exception Policy to ‘MyPolicy’ – Which we specifiled in our code.

c) Now Right Click on MyPolicy –> New –> Exception Type.

image

Select Exception Type as Exception and click on OK.

image

d) Add the logging application block by right clicking on Exception

image

e) add the Formatter Type and Log Category as follows in logging handler section of the exception application block.

image we are done.

f) Run the application and Check the event log file as above.

    Note :

Logger.Write("Our Message : "+ex.Message, "General");

Here “General” is the Category name in Logging application block. We can add more categories and point each category to a different trace listener like email trace listener , db trace listener etc.


ExceptionPolicy.HandleException(ex, "MyPolicy");

Here “MyPolicy” is the exception policy name in exception application block.We can add more policies and point each policy to a different exception types.

Microsoft Enterprise Library 4.1 – Email Trace Listener

This summary is not available. Please click here to view the post.

MS Enterprise Library – Rolling Flat File Trace Listener

 

This article describes the RollingFileTraceListener extension of the Logging block of the Microsoft Enterprise Library. This is a custom trace listener that can be plugged into the Enterprise Library Logging block like the standard trace listeners that are included. The FlatFileTraceListener shipped with EntLib 2.0 may not be adequate for enterprise systems since log files by default will continue to grow unchecked. This new trace listener provides support for rolling over log files based on age of the log file or file size.

Step 1 : 

In order to use the new trace listener from the Enterprise Library Configuration tool, you must refererence the following 2 assemblies.

Microsoft.Practices.EnterpriseLibraryExtensions.Logging.dll

Microsoft.Practices..EnterpriseLibraryExtensions.Logging.Configuration.Design.dll.

Step 2:

Open web.confgi file in Enterprise Library Configuration tool.

Add new Logging Application Block By Clicking on the root node.

image

Add the new Text Formater by Right Clicking on Formater section.

 

image

Now Add New Trace Lister in Logging Application Block By right Clicking on ‘Trace Listener’.

 

image

Specify the info as follows:

 

image

 

Now Add the Rolling flat file listener to category Sources –> General and Special Sources –> All Events by right clicking on them and adding the listener name.

 

image

 

STEP 4: Code to write errors to this db log:

Add a default aspx page to the website and write the following code in .cs file.

 

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            int i = 1;
            int j = 0;
            i = i / j;
        }
        catch (System.DivideByZeroException ex)
        { 
         }
    }
}

Thursday 18 March 2010

MS Enterprise Library – Database Trace Listener

 

The Microsoft Enterprise Library is a collection of reusable software components (application blocks) designed to assist software developers with common enterprise development cross-cutting concerns (such as logging, validation, data access, exception handling, and many others).

Data Access Application Block provides access to the most frequently used features of ADO.NET, exposing them through easily used classes.

Create logs in database with EntLib:

It sets up a logging to database framework. The steps needed for this job :

STEP 1: configure entries in web.config:

<configuration>

<configSections>

<!—For Logging Handler-->

<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

<!—For Database Handler-->
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

……

…..

</configSections>

<!—Logging Handler Block-->

<loggingConfiguration name="Logging Application Block" tracingEnabled="true"
    defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
    <listeners>

       <!—Data Base Litener-->
      <add databaseInstanceName="FCConnectionString" writeLogStoredProcName="fantasyCricket.WriteLog"
        addCategoryStoredProcName="fantasyCricket.AddCategory" formatter=""
        listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        name="Database Trace Listener" />

          </listeners>
    <formatters>
      <add template="Timestamp: {timestamp}&#xD;&#xA;Message: {message}&#xD;&#xA;Category: {category}&#xD;&#xA;Priority: {priority}&#xD;&#xA;EventId: {eventid}&#xD;&#xA;Severity: {severity}&#xD;&#xA;Title:{title}&#xD;&#xA;Machine: {machine}&#xD;&#xA;Application Domain: {appDomain}&#xD;&#xA;Process Id: {processId}&#xD;&#xA;Process Name: {processName}&#xD;&#xA;Win32 Thread Id: {win32ThreadId}&#xD;&#xA;Thread Name: {threadName}&#xD;&#xA;Extended Properties: {dictionary({key} - {value}&#xD;&#xA;)}"
        type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        name="Text Formatter" />
    </formatters>
    <categorySources>
      <add switchValue="All" name="General">
        <listeners>
          <add name="Database Trace Listener" />
        </listeners>
      </add>
    </categorySources>
    <specialSources>
      <allEvents switchValue="All" name="All Events"></allEvents>
      <notProcessed switchValue="All" name="Unprocessed Category">
      </notProcessed>
      <errors switchValue="All" name="Logging Errors &amp; Warnings">
        <listeners>
          <add name="Database Trace Listener" />
        </listeners>
      </errors>
    </specialSources>
  </loggingConfiguration>

<connectionStrings>
    <add name="FCConnectionString" connectionString="server=localhost; Database=HowLuckyMe;User=sa; Password=hari999"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

Alternatively we can add the same setting ny suing configuration toll in All program Files –> Microsoft Patterns & Practises –> Enterprise Library 4.1 – October 2008 –> Enterprise Library Configuration.

 

image 

 

 image

STEP 2: Add the following References to the web site.

Microsoft.Practices.EnterpriseLibrary.Common.xml
Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.EnterpriseLibrary.Data.xml
Microsoft.Practices.EnterpriseLibrary.Data.dll
Microsoft.Practices.EnterpriseLibrary.Logging.Database.xml
Microsoft.Practices.EnterpriseLibrary.Logging.Database.dll
Microsoft.Practices.EnterpriseLibrary.Logging.xml
Microsoft.Practices.EnterpriseLibrary.Logging.dll
Microsoft.Practices.ObjectBuilder.dll

Which will be in folder :

Installation Directory\Microsoft Enterprise Library 4.1 - October 2008\Bin

STEP 2: Create the Data base tables.

Run the following DB script to create log related tables and stored procedures.

or you can find the same script file in EntLib(Go to : Installation Directory\Microsoft Enterprise Library 4.1 - October 2008\src –> Click on “Enterprise Library 4.1 - October 2008 - Source Code” windows installer package).

EntLib provides a script(CreateLoggingDb.cmd) for creating a database for logging.  It's located in the @\EntLib41Src\Blocks\Logging\Src\DatabaseTraceListener\Scripts folder. 
1. Run this script.
2. Add a Database Trace Listener to your configuration file.  This will automatically add the Data Access Application block if you haven't done so.
3. Create a connection string for your Logging database.
4. Set the DatabaseInstance property of your Database Trace Listener to the name of your connection string.
5. Add a category under the Category Source node and reference the Database Trace Listener.

 

CREATE TABLE [fantasyCricket].[Category](
    [CategoryID] [int] IDENTITY(1,1) NOT NULL,
    [CategoryName] [nvarchar](64) NOT NULL,
CONSTRAINT [PK_Categories] PRIMARY KEY CLUSTERED
(
    [CategoryID] ASC
) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [fantasyCricket].[CategoryLog](
    [CategoryLogID] [int] IDENTITY(1,1) NOT NULL,
    [CategoryID] [int] NOT NULL,
    [LogID] [int] NOT NULL,
CONSTRAINT [PK_CategoryLog] PRIMARY KEY CLUSTERED
(
    [CategoryLogID] ASC
) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [fantasyCricket].[Log](
    [LogID] [int] IDENTITY(1,1) NOT NULL,
    [EventID] [int] NULL,
    [Priority] [int] NOT NULL,
    [Severity] [nvarchar](32) NOT NULL,
    [Title] [nvarchar](256) NOT NULL,
    [Timestamp] [datetime] NOT NULL,
    [MachineName] [nvarchar](32) NOT NULL,
    [AppDomainName] [nvarchar](512) NOT NULL,
    [ProcessID] [nvarchar](256) NOT NULL,
    [ProcessName] [nvarchar](512) NOT NULL,
    [ThreadName] [nvarchar](512) NULL,
    [Win32ThreadId] [nvarchar](128) NULL,
    [Message] [nvarchar](1500) NULL,
    [FormattedMessage] [ntext] NULL,
CONSTRAINT [PK_Log] PRIMARY KEY CLUSTERED
(
    [LogID] ASC
) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

CREATE PROCEDURE fantasyCricket.InsertCategoryLog
    @CategoryID INT,
    @LogID INT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @CatLogID INT
    SELECT @CatLogID FROM fantasyCricket.CategoryLog WHERE CategoryID=@CategoryID and LogID = @LogID
    IF @CatLogID IS NULL
    BEGIN
        INSERT INTO fantasyCricket.CategoryLog (CategoryID, LogID) VALUES(@CategoryID, @LogID)
        RETURN @@IDENTITY
    END
    ELSE RETURN @CatLogID
END

CREATE PROCEDURE [fantasyCricket].[AddCategory]
    -- Add the parameters for the function here
    @CategoryName nvarchar(64),
    @LogID int
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @CatID INT
    SELECT @CatID = CategoryID FROM fantasyCricket.Category WHERE CategoryName = @CategoryName
    IF @CatID IS NULL
    BEGIN
        INSERT INTO fantasyCricket.Category (CategoryName) VALUES(@CategoryName)
        SELECT @CatID = @@IDENTITY
    END

    EXEC fantasyCricket.InsertCategoryLog @CatID, @LogID

    RETURN @CatID
END

CREATE PROCEDURE fantasyCricket.ClearLogs
AS
BEGIN
    SET NOCOUNT ON;

    DELETE FROM fantasyCricket.CategoryLog
    DELETE FROM fantasyCricket.[Log]
    DELETE FROM fantasyCricket.Category
END

CREATE PROCEDURE [fantasyCricket].[WriteLog]
(
    @EventID int,
    @Priority int,
    @Severity nvarchar(32),
    @Title nvarchar(256),
    @Timestamp datetime,
    @MachineName nvarchar(32),
    @AppDomainName nvarchar(512),
    @ProcessID nvarchar(256),
    @ProcessName nvarchar(512),
    @ThreadName nvarchar(512),
    @Win32ThreadId nvarchar(128),
    @Message nvarchar(1500),
    @FormattedMessage ntext,
    @LogId int OUTPUT
)
AS

    INSERT INTO fantasyCricket.[Log] (
        EventID,
        Priority,
        Severity,
        Title,
        [Timestamp],
        MachineName,
        AppDomainName,
        ProcessID,
        ProcessName,
        ThreadName,
        Win32ThreadId,
        Message,
        FormattedMessage
    )
    VALUES (
        @EventID,
        @Priority,
        @Severity,
        @Title,
        @Timestamp,
        @MachineName,
        @AppDomainName,
        @ProcessID,
        @ProcessName,
        @ThreadName,
        @Win32ThreadId,
        @Message,
        @FormattedMessage)

    SET @LogID = @@IDENTITY
    RETURN @LogID

ALTER TABLE [fantasyCricket].[CategoryLog]  WITH CHECK ADD  CONSTRAINT [FK_CategoryLog_Category] FOREIGN KEY(    [CategoryID])
REFERENCES [fantasyCricket].[Category] (    [CategoryID])
ALTER TABLE [fantasyCricket].[CategoryLog]  WITH CHECK ADD  CONSTRAINT [FK_CategoryLog_Log] FOREIGN KEY(    [LogID])
REFERENCES [fantasyCricket].[Log] (    [LogID])

 

STEP 4: Code to write errors to this db log:

Add a default aspx page to the website and write the following code in .cs file.

 

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            int i = 1;
            int j = 0;
            i = i / j;
        }
        catch (System.DivideByZeroException ex)
        {
            LogEntry logEntry = new LogEntry();
            logEntry.Message = "Informational message

                                        generated using Logging Application Block.";
            logEntry.Categories.Add("General");
            logEntry.Title = "SomeTitle";
            Logger.Write(logEntry, "General");   

        }
    }
}