Friday 26 November 2010

Problem with System.Guid.NewGuid returning Empty after some time

http://www.thesoftwaredevotional.com/2008/12/guid-visualizer-broken-in-vbnet.html

GUID Visualizer Broken in VB.NET and How to Fix It


A colleague brought over a strange problem he was seeing while debugging a VB.NET project. During a debugging session he hovered his mouse over a variable of type System.Guid. You normally expect the standard visualizer for the type to appear, but it was displaying "Empty". Unfortunately, this led to some thrashing and gnashing of teeth because this 'bug' caused him to incorrectly suspect a problem with his code.

After a bit of searching and reflecting over the System.Guid class, I found that it is the visualizer for GUIDs in VB.NET that is 'broken'. The 'bug' exists in both Visual Studio 2005 and Visual Studio 2008. Dang.

Here is what the problem looks like out in the wild. In VB.NET, the visualizer tricks you into thinking that the value of the GUID is Empty.



When you call .ToString on the GUID, there is clearly a GUID populated.


I ran the *same* code in C#, and it works perfectly. +1 for C#!



Microsoft left a bug in the two most recent versions of Visual Studio? Not really.

When I found that the GUID shows up correctly when you call the .ToString method, I realized that the GUID is populated, it just doesn't appear correctly in the debugger. This led me to believe that there must be something else going on. I got out Reflector to take a look at the System.Guid class and found the problem.

As it turns out, the System.Guid class contains a single read-only property named Empty. Because the Empty property shows up in the debugger visualizer as the only member, it has the effect of making you think that the value is empty. To make matters worse, the Empty property returns an empty (all zeros) instance of a System.Guid class. The result, when you drill into the System.Guid variable: you get a never-ending tree of what appears to be Empty GUIDs.


We can't blame the visualizer specifically. The word Empty is misleading and leads developers to believe that a GUID variable is empty - the "not used" type of empty.

You can work around this problem by downloading a visualizer for GUIDs (from here and here). Both of these visualizers give you the option to open a window in the debugger displaying the GUID's value. A little cumbersome.

Here's how you can create an even better GUID debugger visualizer on your own.

Create a VB.NET class library. If you are using Visual Studio 2008, make sure to target the .NET 2.0 framework. Create a new class and put the code below into the class file. The class and project names do not matter.


Public Class Visualizer_GUID
'---- no implementation necessary
End Class

Compile the code and put the output in your "My Documents\Visual Studio 2008\Visualizers" and/or "My Documents\Visual Studio 2005\Visualizers" directories. Crank up another Visual Studio project, create a GUID, and hover over it in debug mode. Here's what you will see.


Now that's much better.

Friday 22 October 2010

SQL Server Security

Test for presence of master key, certificate and symmetric key?

select Count(*) from sys.symmetric_keys where name like '%DatabaseMasterKey%' - Returns 1 if there is a master key

select * from sys.certificates - List of all certificates generated

select count(*) from sys.symmetric_keys - List of symmetric keys generated



Creating symmetric keys and master keys:


CREATE master key Encryption by password = 'Key_Name'

CREATE CERTIFICATE Certificate_Name with subject = 'Subject_Name'

CREATE symmetric key Key_Name with algorithm=DES Encryption by certificate Certificate_Name

'Open Keys Before encrypting/Decrypting
OPEN SYMMETRIC KEY Key_Name
DECRYPTION BY CERTIFICATE Certificate_Name


'Encrypt
select EncryptByKey(Key_GUID('Key_Name'), ValuetoBeEncrypted)

'Decrypt
DecryptByKey(ValuetoBeDecrypted)


Ex :


OPEN SYMMETRIC KEY Key_Name
DECRYPTION BY CERTIFICATE Certificate_Name

DECLARE @encrypted_str varbinary(max)
SET @encrypted_str = EncryptByKey(Key_GUID('Key_Name'), 'Testing')
SELECT @encrypted_str AS Encrypted
DECLARE @decrypted_str varbinary(max)
SET @decrypted_str = DecryptByKey(@encrypted_str)
SELECT CONVERT(VARCHAR, @decrypted_str) AS Decrypted


Result :
Encrypted
0x000B64F4BA1C634C8BB67A7E5E52CD77010000007BD87E72AD10A7FF7B26ADDD2F58C4BB635A1ECCCFDF0E96

Decrypted
Testing


A strange problem is occurred while doing encryption.I did encryption on a string which works fine using a Master Key. But when I did database copy the problem comes.

Each time the copy is performed we get an error while opening the symmetric keys:

"Please create a master key in the database or open the master key in the session before performing this operation."

This is resolved with the following SQL:

OPEN MASTER KEY DECRYPTION BY PASSWORD = 'SQLAuthority'
ALTER MASTER KEY ADD ENCRYPTION BY SERVICE MASTER KEY

Reason:
There are several levels of encryption on SQL Server. First is the Service Master Key, which is a server key. All lower keys are encrypted with this key. Next is a Database Master Key. This key is stored encrypted in the sys.symmetric_keys table in each database that a Master Key has been created in. All Symmetric, and Asymmetric keys keys created in a database are further encrypted with this Master key.

Opening a key means the Database master key is opened, which in turn requires the Service Master Key to be opened to decrypt the Database Master Key, so the user's key can be used.

At a minimum, i would expect the two database servers do not share the same Service Master Key. This can be synchronized with the Backup Service Master Key command, but you should take great care before changing the keys on any server. If you have other data that is encrypted with an old Service Master Key, or any of its descendants, you could lose that data entirely.

Any key called a Master Key will by definition be singular. Just like a backup carries user and role permissions, a database backup/restore will carry its (encrypted) Master Key, rendering the encrypted data unreadable, unless the Service Master Key has not changed.

Wednesday 14 April 2010

SQL Server Date, Time and DateTime Functions

 

 

user defined functions

 

create  function DateOnly(@DateTime DateTime)
-- Returns @DateTime at midnight; i.e., it removes the time portion of a DateTime value.
returns datetime
as
    begin
    return dateadd(dd,0, datediff(dd,0,@DateTime))
    end
go


create function Date(@Year int, @Month int, @Day int)
-- returns a datetime value for the specified year, month and day
-- Thank you to Michael Valentine Jones for this formula (see comments).
returns datetime
as
    begin
    return dateadd(month,((@Year-1900)*12)+@Month-1,@Day-1)
    end
go

 
create function Time(@Hour int, @Minute int, @Second int)
-- Returns a datetime value for the specified time at the "base" date (1/1/1900)
-- Many thanks to MVJ for providing this formula (see comments).
returns datetime
as
    begin
    return dateadd(ss,(@Hour*3600)+(@Minute*60)+@Second,0)
    end
go


create function TimeOnly(@DateTime DateTime)
-- returns only the time portion of a DateTime, at the "base" date (1/1/1900)
-- Thanks, Peso!
returns datetime
as
    begin
    return dateadd(day, -datediff(day, 0, @datetime), @datetime)
    end
go


create function DateTime(@Year int, @Month int, @Day int, @Hour int, @Minute int, @Second int)
-- returns a dateTime value for the date and time specified.
returns datetime
as
    begin
    return dbo.Date(@Year,@Month,@Day) + dbo.Time(@Hour, @Minute,@Second)
    end
go


Remember that you must prefix UDFs with the owner (usually dbo) when calling them.

Examples:

  • where TransactionDate >= dbo.Date(2005,1,2)  -- no formatting or implicit string conversions needed for date literals
  • select dbo.Date(year(getdate()), 1,1) -- returns the first day of the year for the current year.
  • select dbo.DateOnly(getdate()) -- returns only the date portion of the current day.
  • if dbo.TimeOnly(SomeDate) = dbo.Time(5,30,0)  -- check to see if the time for a given date is at 5:30 AM
  • select dbo.Date(year(getdate()), month(getdate()),1) -- returns the first day of the current month.
  • select dbo.Date(year(getdate()), month(getdate())+1,0) -- returns the last day of the current month.
  • where SomeDate >= dbo.DateOnly(getdate()) and SomeDate < dbo.DateOnly(getDate())+1 -- a simple way to get all transactions that occurred on the current date
  • select dbo.DateOnly(getdate()) + 1 + dbo.Time(14,30,0) -- returns tomorrow at 2:30 PM.

 

Ref : http://weblogs.sqlteam.com/jeffs/archive/2007/01/02/56079.aspx

Resetting Identity Column SQL Server

 

If you are using an identity column on your SQL Server tables, you can set the next insert value to whatever the value you want. As an example is if you wanted to start numbering my ID column at 1000 instead of 100.

First check the current identify value using:

DBCC CHECKIDENT (’tablename’, NORESEED)

To set the value of the next ID to be 1000, use this command:

DBCC CHECKIDENT (’tablename’, RESEED, 999)

Note that the next value will be whatever you reseed with + 1, so in this case I set it to 999 so that the next value will be 1000.

Note: Enclose the table name in single quotes or square brackets if you are referring by a full path, or if your table name has spaces in it. (which it really shouldn’t)

DBCC CHECKIDENT ( ‘databasename.dbo.tablename’,RESEED, 999)

 

My Problem:

By Mistake I entered one record in production server with ID (Identity Column) 1051.

SO 1st I deleted the record with ID = 1051 and then executed the following command immediately:

DBCC CHECKIDENT ('TableName', RESEED, 1050)

So Now There wont be any gaps while inserting from now onwards.

Saturday 10 April 2010

Copy Website to remote server through FTP in Visual Studio

 

 

To start, you will connect to the FTP Web site from within Visual Web Developer. You must know the FTP address of the FTP Web site and, if it is required, you must have a user name and password.

To access the FTP Web site
  1. In Visual Web Developer, on the File menu, click New Web Site.

  2. In the New Web Site dialog box, in the left-most Location list, click FTP Site, and then click Browse.

  3. In the Choose Location dialog box, in the Server and Directory boxes, enter the appropriate information.

    The Server field refers to the name or IP address of the FTP server. The Directory field refers to a specific directory on the FTP server that you want to put the content in. By default, many FTP sites connect you to a home directory, although there might still be a directory below that or a separate virtual directory where the Web content should be put. If you do not know these values, contact the FTP site administrator.

    For Port, the most common value is 21, but you should confirm that value with the FTP site administrator also.

  4. Examine the following values:

    • Passive Mode

      Leave this check box clear at first. Passive mode is sometimes required, if there is a firewall between your server and the FTP server.

    • Anonymous Login

      If the FTP site administrator has provided you with a user name and password, clear the Anonymous Login check box, and then in the Username andPassword boxes, enter the appropriate information.

  5. Click Open.

    Visual Web Developer will try to connect to the FTP server by using the information that you have provided. If the connection is successful, Visual Web Developer displays the FTP Web site name in Solution Explorer and lists the files that are already in the FTP Web site.

clip_image002

Troubleshooting

If the connection fails, examine the following:

  • If you have administrative rights on the server, use IIS Manager to add the Write permission to the FTP virtual directory. Do not complete this before you have set restricted NTFS File System permissions on the virtual directory, either by using IIS Manager or Microsoft Windows Explorer. For more information, go to Microsoft Technet and search for information about how to help secure FTP sites.

  • Confirm that the server name and directory name are correct.

  • Use the URL of the Web site or the FTP site in the Server field and leave the Directory field blank.

  • Try connecting with Passive Mode enabled. This frequently lets you get through a firewall.

  • Make sure that the FTP Web site has the directory that you have indicated. If you are using IIS as the FTP server, remember that the directory is typically defined under the ftproot directory, not the wwwroot directory.

  • Contact the FTP site administrator to determine whether anonymous log on is allowed. If not, make sure that you have credentials for a user account that has permission to access and modify the FTP directory.

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");   

        }
    }
}

Thursday 18 February 2010

Test Driven Development

 

             When sitting down to create an application, many developers start by writing the code. Test Driven Development emphasizes the opposite, stressing the need to prepare test scenarios or test cases before writing the code itself. This seemingly backwards approach has some benefits. First of all, it requires that the programmer be very clear about what tests the program should pass and what test it should fail, bringing such concerns to the forefront of the software design process. Furthermore, by meticulously detailing what tests a system should pass and fail we can use tools to automate most of our tests. An automated job is one that's always very, very easy to do. These automated tests are meant to be run every time there's a code change and are referred to as unit tests.

NUnit is a free, open-source tool for .NET that is developed as a framework which can help automate unit testing. (The same unit test framework was already available for Java and was named jUnit.) NUnit can be downloaded from NUnit site or the SourceForge NUnit page.

http://www.4guysfromrolla.com/articles/011905-1.aspx

http://www.codeproject.com/KB/dotnet/tdd_in_dotnet.aspx#h2

Wednesday 17 February 2010

ASP.NET MVC

 

Model-View-Controller

The Model-View-Controller (MVC) pattern separates the modeling of the domain, the presentation, and the actions based on user input into three separate classes :

  • Model. The model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller).

  • View. The view manages the display of information.

  • Controller. The controller interprets the mouse and keyboard inputs from the user, informing the model and/or the view to change as appropriate.

Figure 1 depicts the structural relationship between the three objects.

ms978748.des_MVC_Fig01(en-us,MSDN.10).gif

 

ASP.NET MVC is Microsoft framework for building web applications that use a model-view-controller pattern. ASP.NET MVC is built on the ASP.NET framework.

ASP.NET MVC provides the following benefits:

  • Provides complete control over your HTML markup.
  • Enables rich AJAX integration
  • Intuitive website URLs
  • Clear separation of concerns which results in web applications that are easier to maintain and extend over time.
  • Testability – including support for test-driven development.

For Developing Applications using MVC and to use entity framework for adding ADO.NET entity Data Models you need to have .net 3.5 and service pack 1.

The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc namespace and is a fundamental, supported part of theSystem.Web namespace.

http://www.asp.net/learn/mvc/tutorial-01-cs.aspx

 

Problems:

 

While trying to do a sample application i got the following problems:

1. ADO.Net Entity Data Model not a selectable option when I go to add an item.

Linq to Entity Framework is shipped with Visual Studio 2008 SP1. So in order to use it, we need to apply the Visual Studio SP1

http://www.microsoft.com/downloads/details.aspx?FamilyId=FBEE1648-7106-44A7-9649-6D9F6D58056E&displaylang=en

2. While trying to install sp1 i got the following error saying :

Installation Requirements:

You must first use <A HREF="http://go.microsoft.com/fwlink/?LinkID=121685">Microsoft Visual Studio Patch removal tool</A> before installing Visual Studio 2008 SP1.  The tool will verify Visual Studio integrity and remove previous Visual Studio 2008 updates or pre-release software
Microsoft Visual Studio 2008 - KB945140 (Beta)

image

Visual Studio 2008 Service Pack Preparation Tool must be installed inorder to avoid this error.