Wednesday, August 08, 2007

Get height and width of image / Generate image object from byte array

          We are storing image in database in our recent project. We do not store height and width for that image in database.  After few months of deployment the client wants to display the height and width of each image while we display image.  As we do not store height and width in database we need to find that runtime when we load the image from database. Below is the code that we used to solve our issue,

using (SqlConnection cnn = new SqlConnection(ConnectionString))
{
            try
            {
                cnn.Open();
                SqlCommand cmd = new SqlCommand("select
                             [Image] from   tableName where ID = 1"
);
                cmd.Connection = cnn;
                Byte[] bytImage = (Byte[])cmd.ExecuteScalar();

               // Generate Image from Byte array
                System.Drawing.Image img =
                            System.Drawing.Image.FromStream
                            (new System.IO.MemoryStream(bytImage));

                // If you are storing image in specific folder instead
                // of database then you can use following code to
                // generate image

                System.Drawing.Image img = 
                            System.Drawing.Image.FromFile
                            (@"D:\ExampleWeb Projects\Learn2K5
                            \ms.gif"
);

                //  Display Height and Width
                Response.Write("Height : " + img.Height.ToString()
                             + "   Width : " + img.Width.ToString());
            }
            finally
            {
                cnn.Close();
            }
}

Fig - (1) Generate image object from byte array and get height and width

Happy Programming !!!

Wednesday, August 01, 2007

Using the inserted and deleted Tables in SQL Sever

          DML trigger statements use two special tables: the deleted table and the inserted tables. SQL Server 2005 automatically creates and manages these tables. You can use these temporary, memory-resident tables to test the effects of certain data modifications and to set conditions for DML trigger actions. You cannot directly modify the data in the tables or perform data definition language (DDL) operations on the tables, such as CREATE INDEX.

         In DML triggers, the inserted and deleted tables are primarily used to perform the following:

            1. Extend referential integrity between tables.
            2. Insert or update data in base tables underlying a view.
            3. Test for errors and take action based on the error.
            4. Find the difference between the state of a table
                before and after a data modification and 
                take actions based on that difference.

          The deleted table stores copies of the affected rows during DELETE and UPDATE statements. During the execution of a DELETE or UPDATE statement, rows are deleted from the trigger table and transferred to the deleted table. The deleted table and the trigger table ordinarily have no rows in common.

          The inserted table stores copies of the affected rows during INSERT and UPDATE statements. During an insert or update transaction, new rows are added to both the inserted table and the trigger table. The rows in the inserted table are copies of the new rows in the trigger table.

          An update transaction is similar to a delete operation followed by an insert operation; the old rows are copied to the deleted table first, and then the new rows are copied to the trigger table and to the inserted table.

          When you set trigger conditions, use the inserted and deleted tables appropriately for the action that fired the trigger. Although referencing the deleted table when testing an INSERT or the inserted table when testing a DELETE does not cause any errors, these trigger test tables do not contain any rows in these cases.

           SQL Server 2005 does not allow for text, ntext, or image column references in the inserted and deleted tables for AFTER triggers. However, these data types are included for backward compatibility purposes only. The preferred storage for large data is to use the varchar(max), nvarchar(max), and varbinary(max) data types. Both AFTER and INSTEAD OF triggers support varchar(max), nvarchar(max), and varbinary(max) data in the inserted and deleted tables. For more information, see CREATE TRIGGER (Transact-SQL).

An Example of Using the inserted Table in a Trigger to Enforce Business Rules

           Because CHECK constraints can reference only the columns on which the column-level or table-level constraint is defined, any cross-table constraints (in this case, business rules) must be defined as triggers.

           The following example creates a DML trigger. This trigger checks to make sure the credit rating for the vendor is good when an attempt is made to insert a new purchase order into the PurchaseOrderHeader table. To obtain the credit rating of the vendor corresponding to the purchase order that was just inserted, the Vendor table must be referenced and joined with the inserted table. If the credit rating is too low, a message is displayed and the insertion does not execute.

IF OBJECT_ID ('Purchasing.LowCredit','TR') IS NOT NULL
   DROP TRIGGER Purchasing.LowCredit
GO
CREATE TRIGGER LowCredit ON Purchasing.PurchaseOrderHeader
AFTER INSERT
AS
DECLARE @creditrating tinyint,
   @vendorid int
SELECT @creditrating = v.CreditRating, @vendorid = p.VendorID
FROM Purchasing.PurchaseOrderHeader p INNER JOIN inserted i ON p.PurchaseOrderID =
   i.PurchaseOrderID JOIN Purchasing.Vendor v on v.VendorID = i.VendorID
IF @creditrating = 5
BEGIN
   RAISERROR ('This vendor''s credit rating is too low to accept new
      purchase orders.
', 16, 1)
ROLLBACK TRANSACTION
END

 

Using the inserted and deleted Tables in INSTEAD OF Triggers

         The inserted and deleted tables passed to INSTEAD OF triggers defined on tables follow the same rules as the inserted and deleted tables passed to AFTER triggers. The format of the inserted and deleted tables is the same as the format of the table on which the INSTEAD OF trigger is defined. Each column in the inserted and deleted tables maps directly to a column in the base table.

         The following rules regarding when an INSERT or UPDATE statement referencing a table with an INSTEAD OF trigger must supply values for columns are the same as if the table did not have an INSTEAD OF trigger:

      1. Values cannot be specified for computed columns or
          columns with a timestamp data type.
      2. Values cannot be specified for columns with an IDENTITY
          property, unless IDENTITY_INSERT is ON for that table.
          When IDENTITY_INSERT is ON, INSERT statements must
          supply a value.
      3. INSERT statements must supply values for all NOT NULL
          columns that do not have DEFAULT constraints.
      4. For any columns except computed, identity, or
            timestamp
columns, values are optional for any
          column that allows nulls, or any NOT NULL column that 
          has a DEFAULT definition.

         When an INSERT, UPDATE, or DELETE statement references a view that has an INSTEAD OF trigger, the SQL Server 2005 Database Engine calls the trigger instead of taking any direct action against any table. The trigger must use the information presented in the inserted and deleted tables to build any statements required to implement the requested action in the base tables, even when the format of the information in the inserted and deleted tables built

         The format of the inserted and deleted tables passed to an INSTEAD OF trigger defined on a view matches the select list of the SELECT statement defined for the view. For example:

 

CREATE VIEW EmployeeNames (EmployeeID, LName, FName)
AS
SELECT e.EmployeeID, c.LastName, c.FirstName
FROM AdventureWorks.HumanResources.Employee e
JOIN AdventureWorks.Person.Contact c
ON e.ContactID = c.ContactID

         The result set for this view has three columns: an int column and two nvarchar columns. The inserted and deleted tables passed to an INSTEAD OF trigger defined on the view also have an int column named EmployeeID, an nvarchar column named LName, and an nvarchar column named FName.

The select list of a view can also contain expressions that do not directly map to a single base-table column. Some view expressions, such as a constant or function invocation, may not reference any columns and can be ignored. Complex expressions can reference multiple columns, yet the inserted and deleted tables have only one value for each inserted row. The same issues apply to simple expressions in a view if they reference a computed column that has a complex expression. An INSTEAD OF trigger on the view must handle these types of expressions. For more information, see Expressions and Computed Columns in INSTEAD OF Triggers.

 

NOTE:
         This article is copied from MSDN for my personal learning.

Happy Learning !!!

Triggres in SQL Sever

           A trigger is single or multiple SQL statements that fires as an actionwhen event (like INSERT, DELETE,UPDATE, CREATE, ALTER, DROP) occures. You can devide tringgers in to two parts. DDL Triggers and DML Triggers.

DDL (Data Defenition Language)  Triggers

            DDL Triggers are a special kind of trigger that fire in response to Data Definition Language (DDL) statements. These events primarily correspond to Transact-SQL statements that start with the keywords CREATE, ALTER, and DROP. Certain system stored procedures that perform DDL-like operations can also fire DDL triggers. They can be used to perform administrative tasks in the database such as auditing and regulating database operations. Use DDL triggers when you want to do the following:

  • You want to prevent certain changes to your database schema.
  • You want something to occur in the database in response to a change in your database schema.
  • You want to record changes or events in the database schema.

            DDL triggers fire only after the DDL statements that trigger them are run. DDL triggers cannot be used as INSTEAD OF triggers.

            The following example shows how a DDL trigger can be used to prevent any table in a database from being modified or dropped.

CREATE TRIGGER safety 
ON DATABASE
FOR DROP_TABLE, ALTER_TABLE
AS
PRINT 'You must disable Trigger "safety" to drop or alter tables!'
ROLLBACK ;
Fig - (1) Example of DDL Trigger

DML (Data Manipulation Language) Triggers


           DML triggers are invoked when a data manipulation language (DML) event takes place in the database. DML events include INSERT, UPDATE, or DELETE statements that modify data in a specified table or view. A DML trigger can query other tables and can include complex Transact-SQL statements. The trigger and the statement that fires it are treated as a single transaction, which can be rolled back from within the trigger. If a severe error is detected (for example, insufficient disk space), the entire transaction automatically rolls back.


DML triggers are useful in these ways:


  • They can cascade changes through related tables in the database; however, these changes can be executed more efficiently using cascading referential integrity constraints.
  • They can guard against malicious or incorrect INSERT, UPDATE, and DELETE operations and enforce other restrictions that are more complex than those defined with CHECK constraints.
    Unlike CHECK constraints, DML triggers can reference columns in other tables. For example, a trigger can use a SELECT from another table to compare to the inserted or updated data and to perform additional actions, such as modify the data or display a user-defined error message.
  • They can evaluate the state of a table before and after a data modification and take actions based on that difference.
  • Multiple DML triggers of the same type (INSERT, UPDATE, or DELETE) on a table allow multiple, different actions to take place in response to the same modification statement.

Types of DML Triggers


           You can program the following types of DML Triggers:

        After Trigger

                   AFTER triggers are executed after the action of the INSERT, UPDATE,
            or   DELETE statement is performed. Specifying AFTER is the same as
            specifying FOR, which is the only option available in earlier versions of 
            Microsoft SQL Server. AFTER triggers can be specified only on tables. 


        Instead Of Trigger


                    INSTEAD OF triggers are executed in place of the usual triggering
            action. INSTEAD OF triggers can also be defined on views with one or more
            base tables, where they can extend the types of updates a view can support.


For more information about AFTER and INSTEAD OF triggers, see DML Trigger Planning Guidelines. 

CLR Triggers

          A CLR Trigger can be either an AFTER or INSTEAD OF trigger. A CLR trigger can also be a DDL trigger. Instead of executing a Transact-SQL stored procedure, a CLR trigger executes one or more methods written in managed code that are members of an assembly created in the .NET Framework and uploaded in SQL Server. For more information, see Programming CLR Triggers.  

DML Trigger Execution

            AFTER triggers are never executed if a constraint violation occurs; therefore, these triggers cannot be used for any processing that might prevent constraint violations.

             INSTEAD OF triggers are executed instead of the triggering action. These triggers are executed after the inserted and deleted tables reflecting the changes to the base table are created, but before any other actions are taken. They are executed before any constraints, so can perform preprocessing that supplements the constraint actions.

             If an INSTEAD OF trigger defined on a table executes a statement against the table that would usually fire the INSTEAD OF trigger again, the trigger is not called recursively. Instead, the statement is processed as if the table had no INSTEAD OF trigger and starts the chain of constraint operations and AFTER trigger executions. For example, if a DML trigger is defined as an INSTEAD OF INSERT trigger for a table, and the trigger executes an INSERT statement on the same table, the INSERT statement executed by the INSTEAD OF trigger does not call the trigger again. The INSERT executed by the trigger starts the process of performing constraint actions and firing any AFTER INSERT triggers defined for the table.

             If an INSTEAD OF trigger defined on a view executes a statement against the view that would usually fire the INSTEAD OF trigger again, it is not called recursively. Instead, the statement is resolved as modifications against the base tables underlying the view. In this case, the view definition must meet all of the restrictions for an updatable view. For a definition of updatable views, see Modifying Data Through a View. For example, if a DML trigger is defined as an INSTEAD OF UPDATE trigger for a view, and the trigger executes an UPDATE statement referencing the same view, the UPDATE statement executed by the INSTEAD OF trigger does not call the trigger again. The UPDATE executed by the trigger is processed against the view as if the view did not have an INSTEAD OF trigger. The columns changed by the UPDATE must be resolved to a single base table. Each modification to an underlying base table starts the chain of applying constraints and firing AFTER triggers defined for the table.

             DML trigger performance overhead is usually low. The time involved in running a DML trigger is spent mostly in referencing other tables, which can be either in memory or on the database device. The deleted and inserted tables are always in memory. The location of other tables referenced by the trigger determines the amount of time the operation requires.

DML Trigger Execution and Partitioned Views

             In SQL Server 2005, the way UPDATE and DELETE triggers fire on tables that underlie a partitioned view has changed from the way they fire in SQL Server 2000. In SQL Server 2000, when an UPDATE or DELETE statement is issued against a partitioned view, either local or distributed, any UPDATE or DELETE triggers that are defined on the base tables of the view fire. These include triggers on tables that are not affected by the update or delete operation. In SQL Server 2005, an UPDATE or DELETE trigger fires only if the base table on which the trigger is defined is affected by the update or delete operation. This behavior is the same for both AFTER and INSTEAD OF triggers.


            For example, consider a partitioned view PV that consists of fields from tables T1 and T2. Additionally, both T1 and T2 have UPDATE triggers defined on them. In SQL Server 2000, an UPDATE statement issued against PV that only affects rows in T1 causes the UPDATE triggers on both T1 and T2 to fire. In SQL Server 2005, only the UPDATE trigger that is defined on T1 fires.


CREATE TRIGGER TriggerName ON TableName
(FOR / AFTER)     INSERT / DELETE / UPDATE
AS
BEGIN
END


Fig - (2) Syntax for DML Trigger


NOTE:
            There is no BEFORE trigger in SQL Server.


 


Understanding DDL Triggers vs. DML Triggers


DDL triggers and DML triggers are used for different purposes.

DML triggers operate on INSERT, UPDATE, and DELETE statements, and help to enforce business rules and extend data integrity when data is modified in tables or views.

              DDL triggers operate on CREATE, ALTER, DROP, and other DDL statements. They are used to perform administrative tasks and enforce business rules that affect databases. They apply to all commands of a single type across a database, or across a server.

               DML triggers and DDL triggers are created, modified, and dropped by using similar Transact-SQL syntax, and share other similar behavior.

               Like DML triggers, DDL triggers can run managed code packaged in an assembly that was created in the Microsoft .NET Framework and uploaded in SQL Server. For more information, see Programming CLR Triggers.

               Like DML triggers, more than one DDL trigger can be created on the same Transact-SQL statement. Also, a DDL trigger and the statement that fires it are run within the same transaction. This transaction can be rolled back from within the trigger. Serious errors can cause a whole transaction to be automatically rolled back. DDL triggers that are run from a batch and explicitly include the ROLLBACK TRANSACTION statement will cancel the whole batch. For more information, see Using DML Triggers That Include COMMIT or ROLLBACK TRANSACTION.

               Like DML triggers, DDL triggers can be nested. For more information, see Using Nested Triggers.

               When you are designing DDL triggers, consider how they differ from DML triggers in the following ways:


  • DDL triggers run only after a Transact-SQL statement is completed. DDL triggers cannot be used as INSTEAD OF triggers.
  • DDL triggers do not create the inserted and deleted tables. The information about an event that fires a DDL trigger, and the subsequent changes caused by the trigger, is captured by using the EVENTDATA function. For more information, see Using the EVENTDATA Function.

 


Important:
                     This article is copied from different MSDN links. I have just gethered all the information at single place.


Happy Learning !!!

Monday, July 30, 2007

Debugging JavaScript in MAC Safari / Tool to debug JavaScript in Safari

      Safari has inbuilt debug menu for java script. By default it is hidden. Safari's "Debug" menu allows you to turn on the logging of JavaScript errors. To display the debug menu in Mac OS X, open a Terminal window and type:

            defaults write com.apple.Safari IncludeDebugMenu 1

      To display the debug menu in Safari 3.0 for Windows, use a text editor to add the following to the Preferences.plist file located at C:\Documents and Settings\USERNAME\Application Data\Apple Computer\Safari\Preferences.plist :

            <key>IncludeDebugMenu</key> <true/>

        Safari 1.3 and above supports explicit logging of arbitrary information - similar to Objective-C NSLog() - function by using window.console.log() in your JavaScript. All messages are routed to the JavaScript Console window and show up nicely in a dark green, to easily differentiate themselves from JavaScript exceptions.

            if(window.console)
           {
                window.console.log("I think therefore I code!"); 
           } 
           else
           { 
                alert("I think therefore I code!");
           }

        WebKit crew has released a JavaScript debugger tool Drosera to debug javascript in safari.

Happy Programming !!

Saturday, July 28, 2007

Session.SessionID is not unique

    I have seen many forums in which users are asking that Session.SessionID is not unique. You also have seen forums saying that "I am getting different value for SessionID on every page or in each post back." Yes they are correct !!!! "This is not possible. How can it be?", I know this is your reaction. We have read in all the books and seen practically that SessionID is unique, until user logs off or close the browser. This is also correct. Now you will say then why am I writing the story?

   Here is the actual fundamentals that I have observe practically. The session changes in each request (either post back or redirecting from one page to another page) until user has not insert any value in Session collection. This means server treats each request from new session if user has not entered any value in session. You can check this practically!!!

  Create a web application with two pages Default.aspx and Default2.aspx. Add one button and two lables on Default.aspx page. On page load of Default.aspx in if(!Page.IsPostBack) set any one lable's text to Session.SessionID. Now in click event of button set second lable's text to Session.SessionID. You can see that every time when post back occurs you have new value of SessionID. Amazing !!!!!!! You can check by redirecting to Default2.aspx page and print SessionID.

    Now, on Default.aspx page in if(!Page.IsPostBack) set Session["test"] = "1" or set any name value collection. Once you do this run the page. Click on button any number of time and you see that now SessionID is unique.

   Really Amazing!!!!

 

Happy Programming !!

Tuesday, July 24, 2007

Dispose and Finalize in Dot Net OR Maemory Management using Dispose and Finalize

       You can find article here

Happy Programming !!

Monday, July 23, 2007

Delete single row from duplicate rows in SQL Server 2005 and 2000

        Lets assume that you are using SQL Server 2005 for your current project. You found that you have few rows which have duplicate data in all the columns. Lets consider that you have table name "Example" which has two columns ID and Name.

CREATE TABLE [dbo].[Example]
(
[ID] [int] NOT NULL,
[Name] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
)
ON [PRIMARY]

Fig - (1) Create Statement for Table     

INSERT INTO [Example] ([ID],[Name]) VALUES (1,Chirag)
INSERT INTO [Example] ([ID],[Name]) VALUES (1,Chirag)
INSERT INTO [Example] ([ID],[Name]) VALUES (2,'Shailesh')
INSERT INTO [Example] ([ID],[Name]) VALUES (3,'Dipak')
INSERT INTO [Example] ([ID],[Name]) VALUES (4,'Mihir')
INSERT INTO [Example] ([ID],[Name]) VALUES (4,'Mihir')
INSERT INTO [Example] ([ID],[Name]) VALUES (4,'Piyush')

Fig - (2) Insert Script.

          You can see that first two and last three rows are duplicate rows. All the values in these rows are same.  Here is the insert script, if you want to do this practically in your local database.

       Now you want to delete duplicate rows in such a way that only one row will be exist after delete statement. First let me write the query which will give return all the duplicate rows from table.

SELECT
        [ID],[NAME],COUNT([ID])
FROM
        [Example]
GROUP BY
        [ID],[NAME]
HAVING
        COUNT([ID]) > 1

Fig - (3) Query to identify duplicate rows in table.

       Here I have used COUNT([ID]) in select statement as ID is not null filed. You can use any column which is not NULL. If all the columns in your table allows NULL value than you can use COUNT(*). The Difference between COUNT(Column Name) and COUNT(*) is, if your column allows null value and in table you have 5 records with 2 null values in ColumnA. If you use COUNT(ColumnA) it will returns 3 and if you use COUNT(*) it will returns 5. So COUNT(Column Name) ignores NULL value. Lets get back to our query. I have used all the column in SELECT and GROUP BY clause. You also have to write all the columns of your table in SELECT and GROUP BY clause. This way you can identify all the duplicates row from table.

        Lets assume that you have to delete the row which has value (1, 'Chirag') so that only one row remains. Here is the query, (Note: This will work only in SQL Sever 2005)

      DELETE TOP(1) FROM [Example] WHERE [ID] = 1

Fig - (3) Delete single row from duplicate rows.

          Here I have used TOP(1) , If you have n rows which has all the values same than you have to use TOP(n-1) so that only 1 row will be remain after delete statement. To delete all the duplicate rows you need to write a cursor as shown below,

DECLARE @ID int
DECLARE @NAME NVARCHAR(50)
DECLARE @COUNT int

DECLARE CUR_DELETE CURSOR FOR
SELECT [ID],[NAME],COUNT([ID]) FROM [Example] GROUP BY [ID],[NAME] HAVING COUNT([ID]) > 1

OPEN CUR_DELETE

FETCH NEXT FROM CUR_DELETE INTO @ID,@NAME,@COUNT
/* Loop through cursor for remaining ID */
WHILE @@FETCH_STATUS = 0
BEGIN

DELETE TOP(@COUNT -1) FROM [Example] WHERE ID = @ID

FETCH NEXT FROM CUR_DELETE INTO @ID,@NAME,@COUNT
END

CLOSE CUR_DELETE
DEALLOCATE CUR_DELETE

Fig - (4) Cursor to delete all duplicate  records

         This is all about deleting duplicate rows in SQL Server 2005.

       Now to do the same in SQL server 2000.  There is function called ROWCOUNT in SQL.  I have used same [Example] table. You can do this by,

SET ROWCOUNT 1
DELETE FROM [Example] WHERE [ID] = 1

Fig - (5) Delete duplicate row in SQL Server 2000

      ROWCOUNT function specify that how many rows will be affected by the statement which is immediately written below.  Here also you have to write  ROWCOUNT (n -1) to delete n duplicate rows such that only  1 row will remain in database.

Happy Programming !!

Tuesday, July 03, 2007

Anonymous Type in C#

          Anonymous types are a convenient language feature of C# and VB that enable developers to concisely define inline CLR types within code, without having to explicitly define a formal class declaration of the type.
           Anonymous types are particularly useful when querying and transforming/projecting/shaping data with LINQ.

            C# "Orcas" introduces a new var keyword that may be used in place of the type name when performing local variable declarations. 

             A common misperception that people often have when first seeing the new var keyword is to think that it is a late-bound or un-typed variable reference (for example: a reference of type Object or a late-bound object like in JavaScript).  This is incorrect -- the var keyword always generates a strongly typed variable reference.  Rather than require the developer to explicitly define the variable type, though, the var keyword instead tells the compiler to infer the type of the variable from the expression used to initialize the variable when it is first declared.

            The var keyword can be used to reference any type in C# (meaning it can be used with both anonymous types and explicitly declared types).  In fact, the easiest way to understand the var keyword is to look at a few examples of it using common explicit types.  For example, I could use the var keyword like below to declare three variables:

var a = 5;
var b = "5"
var c = 5.555;
var d = new Class();
var e = a;

int f = 6;
string g = "6"
double h = 6.666;

Fig - (1) Use of anonymous variable in code.

              You can look in to the IL code and found that IL is treating anonymous variables same as normal variable depending on their initialization. You can see the IL code below,

.method private hidebysig instance void UseOfAnonymousTypes() cil managed
{
// Code size 50 (0x32)
.maxstack 1
.locals init ([0] int32 a,
[1] string b,
[2] float64 c,
[3] class LearnLINQ.SimpleExamples d,
[4] int32 e,
[5] int32 f,
[6] string g,
[7] float64 h)
IL_0000: nop
IL_0001: ldc.i4.5
IL_0002: stloc.0
IL_0003: ldstr "5"
IL_0008: stloc.1
IL_0009: ldc.r8 5.5549999999999997
IL_0012: stloc.2
IL_0013: newobj instance void LearnLINQ.SimpleExamples::.ctor()
IL_0018: stloc.3
IL_0019: ldloc.0
IL_001a: stloc.s e
IL_001c: ldc.i4.6
IL_001d: stloc.s f
IL_001f: ldstr "6"
IL_0024: stloc.s g
IL_0026: ldc.r8 6.6660000000000004
IL_002f: stloc.s h
IL_0031: ret
} // end of method Class1::UseOfAnonymousTypes

 Fig - (2) IL generated for Anonymous Type

          As you can see that we have assigned 5 to "a". IL treats "a" as int32. Same is the case for remaining all. From this you can say that IL detects type of anonymous variable from their initialization. So you can declare anonymous variable without initializing it. Second rule for anonymous type is that you can not use Anonymous variable as a member of class, sturct or interface. So below line will not complile.

class LearnAnonymousType
{
       // Below line will give error
       var a = 5;
}

Fig - (3) Defining Anonymous variable as member field in class

    Third rule is that you can not pass or used for Anonymous type as a method argument. See below,

class LearnAnonymousType
{
       // Below line will give error
       function void sum(var Argument)
      {
      }
}

Fig - (4) Passing anonymous type as argument to function

     Fourth rule is, anonymous type can not be static.

      I hope this article has helped you in understanding the concept. Now lets have a simple quiz.

Quiz

Which of the following code fragments compile and which don't (and why)? Have fun!

Fragment 1

using System;
class Lti
{
   public static void Main()
   {
      var a;
      a = 123;
   }
}

Fragment 2

using System;
class Lti
{
   public static void Main()
   {
          int a = 123;
          var b = a;
   }
}

Fragment 3

using System;
using System.Collections.Generic;
class Lti
{
   public static void Main()
   {
              IEnumerable<string> l = new List<string>();
              var m = l;
              int i = m.Count;
   }
}

Fragment 4

using System;
using System.Collections.Generic;
class Lti
{
   private var a = 123;
   private const var b = 123;
   private static var c = 123;
   public static void Main()
   {
   }
}

Monday, June 25, 2007

Color Picker control in ASP.NET

      Recently I have to use color picker control in my project so that each user has its own UI. The best color picker example I found on blogger.com. This inspired me to create my own color picker control. 

      You can find the user control here.

Happy Programming !!

Wednesday, June 20, 2007

Create/Delete/View Virtual Directory or Website in IIS using C#

     Hi, in my previous atrlicle I show how to create virtual directory. Here I have attched the code for creating , deleteing or listing virtual directories or website in IIS using ASP.NET and C#. 

    Code uses DirectoryService name space which allows access to Internet Information Services (IIS). The System.DirectoryServices namespace also provides access to the Active Directory. The classes in this namespace can be used with any of the Active Directory service providers including Internet Information Services (IIS), the Lightweight Directory Access Protocol (LDAP), the Novell Directory Services in NetWare (NDS), and WinNT.

   Following softeares are required for this project to run successfully.

   * IIS 5.1 or later version
   * Dotnet SDK 2.0
   * Admin access to server on which IIS in installed

     You can download the Source Code  here. Once you download the file pls change the extension from “doc” to “zip”.    

        Sorry for uploading the code this way. I do not found any option to upload zip file. :)

Happy Programming !!

Tuesday, June 19, 2007

PNG issue in IE 6 or previous version

      In my recent project, I found a starnge behaviour of PNG file. We have created PNG files with transparent back ground for logo. Everything is working fine in IE 7 , Opera, Firefox and even in Safari. However when we saw the image in IE 6 we found a problem that it does not display as transparent back ground.

    Here is the PNG file with transparent back ground. Just save it to your PC and than open it in IE. If you have IE 6 than you can see light blue back ground and if you have IE 7 it will be transparent.

    Below is the html page that display png image.

<html>
<head>
<title>PNG in IE: JS Inc File </title>

<!-- Add below 3 lines in Head section as shown here. -->

<!--[if lt IE 7]>
<script defer type="text/javascript" src="pngfix.js"></script>
<![endif]-->

</head>
<body>
<div class="content">
<h1>PNG in Windows IE: Inc File Demo </h1>
<p>IE now renders this PNG image properly. View the source to see how
to use the JS Include file method.</p>
<img src="AboutUSIcon.png" alt="a PNG logo" />
</div>
</body>
</html>

Fig (1) HTML page that shows PNG file.

  

   Below is the javascript for "pngfix.js" file.Copy the above JS in new file and name it "pngfix.js". 


var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])

if ((version >= 5.5) && (document.body.filters))
{
     for(var i=0; i<document.images.length; i++)
     {
             var img = document.images[i]
             var imgName = img.src.toUpperCase()
             if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
            {
                    var imgID = (img.id) ? "id='" + img.id + "' " : ""
                    var imgClass = (img.className) ? "class='" + img.className + "' " : ""
                    var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='"
                                                  + img.alt + "' "
                    var imgStyle = "display:inline-block;" + img.style.cssText
                    if (img.align == "left") imgStyle = "float:left;" + imgStyle
                    if (img.align == "right") imgStyle = "float:right;" + imgStyle
                    if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
                    var strNewHTML = "<span " + imgID + imgClass + imgTitle
                                   + " style=\"" + "width:" + img.width + "px; height:" + 
                                    img.height + "px;" + imgStyle + "" + 
                                   "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                                   + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
                  
                    img.outerHTML = strNewHTML
                   i = i-1
            }
     }
}  

Fig (2) Content of "pngfix.js"" file

Happy Programming !! 

Wednesday, June 13, 2007

Moving Options/values up and down in list box using javascript

         Recently I found a really good article on moving options up and down in list box using javascript. Here is the link.

Happy Programming !!

Moving value from one list box to other list box using javascript

           Recent ly I found a really good article on moving value from one list box to another list box using javascript. Here is the link.

Happy Programming !!

Wednesday, June 06, 2007

Shadow Copying

A fantastic feature of ASP.NET is that the code for a Web site can be changed on the fly without shutting down the Web server. When a Web site's file is changed on the hard disk, ASP.NET detects this, unloads the AppDomain that contains the old version of the files (when the last currently running request finishes), and then creates a new AppDomain, loading into it the new versions of the files. To make this happen, ASP.NET uses an AppDomain feature called
shadow copying.

Shadow Copying Assemblies

Shadow copying allows assemblies that are used in an application domain to be updated without unloading the application domain. This is particularly useful for applications that must be available continuously, such as ASP.NET sites.

The common language runtime locks an assembly file when the assembly is loaded, so the file cannot be updated until the assembly is unloaded. The only way to unload an assembly from an application domain is by unloading the application domain, so under normal circumstances, an assembly cannot be updated on disk until all the application domains that are using it have been unloaded.

When an application domain is configured to shadow copy files, assemblies from the application path are copied to another location and loaded from that location. The copy is locked, but the original assembly file is unlocked and can be updated.

The following list describes how to use the properties of the AppDomainSetup class to configure an application domain for shadow copying.

  • Enable shadow copying by setting the ShadowCopyFiles property to the string value "true".

    By default, this causes all assemblies in the application path to be copied to a download cache before they are loaded. This is the same cache maintained by the common language runtime to store files downloaded from other computers, and the common language runtime automatically deletes the files when they are no longer needed.

A little example

Let's come to the point. How to enable this kind of stuff in your own application? A really simple and short example:

First, write a method to create a new app domain to host the new version of the assembly. As you might know, it's impossible to unload an assembly once loaded in an appdomain, you can only unload the associated appdomain entirely. What the following method does is pretty straightforward: it tells the CLR (assembly loader) where to look for files and then tells it to enable shadow copying by setting the (wrong-typed; a boolean property would have been much better) ShadowCopyFiles property to the string "true". Next, an appdomain is created with a unique name using some counter, and the assembly with the functionality is loaded (notice the _ indicates private members of the current class). This method is called when the app starts.

private void LoadAppDomain()
{
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = "c:\\temp";
setup.ShadowCopyFiles = "true";
AppDomain domain = AppDomain.CreateDomain("ShadowCopy
domain " + _domainNumber, null, setup);
_currentAssembly = domain.Load("Server", null);
_domainNumber++;
}

Add items in Drop Down List or List Box using Javascript

        I have seen lots of questions in diffrent forums for adding items in drop down list or list box using javascript. Below is the script for the same.

 

<script type="text/javascript">
function AddItem(Text,Value)
{
// Create Option object
var opt = document.createElement("option");



// Add Option to Dropdown/Listbox
document.getElementById
("DropDownList").options.add(opt);

// Assign text and value to option
opt.text = Text;
opt.value = Value;


}
<script />
        You can use this function in for loop and add more than one Items.
Happy Programming !!

Monday, June 04, 2007

Create Virtual Directory in IIS using C#

            In my recent project I need to create virtual directory in IIS programmatically.  I was searching on net and found a really good article posted by Dipali Choksi. You can find the artilce here. I have copied that article below for my reference.

 

Using System.DirectoryServices;
private
void btnCreateDirectory_Click(object sender, EventArgs e)
{
          string strSchema = "IIsWebVirtualDir";
          string strRootSubPath = "/W3SVC/1/Root" ;

           // you can specify any server name , "localhost" is for example
           DirectoryEntry deRoot =
                        new DirectoryEntry("IIS://" + "localhost" + strRootSubPath);
         try
        {
                 deRoot.RefreshCache();
                 DirectoryEntry deNewVDir =
                                    deRoot.Children.Add("Name of Virtual Directory", strSchema);

                 deNewVDir.Properties["Path"].Insert(0, "Path for Virtual Directory");
                 deNewVDir.CommitChanges();
                 deRoot.CommitChanges();

                // Create a Application
                if (strSchema == "IIsWebVirtualDir")
                           deNewVDir.Invoke("AppCreate", true);
                // Save Changes
                           deNewVDir.CommitChanges();
                
                deRoot.CommitChanges();
                deNewVDir.Close();
                deRoot.Close();
                lblResult.Text = "Virtual Directory "
                                   + ("Name of Virtual Directory"+ "(" + "Path for Virtual
                                             Directory
" + ") has  been created";
       }
      catch (Exception ex)
     {
                lblResult.Text = ex.Message;
      }
}

Fig (1) Code to create virtual directory using C#

Monday, May 28, 2007

Thousand Separator function for Java Script

     In my project, I have to display the total of selected item in thousand separated format. I am using java script to find total of selected values. Now I have to display the result in Thousand deperated format (like 12,345.00). Here the function that I have used to do that.   

 

 <script language = "javascript">
function ThousandSeparator(decimalDigits,Value)
{

// Separator Length. Here this is thousand separator
var separatorLength = 3;

var OriginalValue=Value;

var TempValue = "" + OriginalValue;

var NewValue = "";

// Store digits after decimal
var pStr;

// store digits before decimal
var dStr;

// Add decimal point if it is not there
if (TempValue.indexOf(".")==-1){TempValue+="."}

dStr=TempValue.substr(0,TempValue.indexOf("."));

pStr=TempValue.substr(TempValue.indexOf("."))

// Add "0" for remaining digits after decimal point
while (pStr.length-1< decimalDigits){pStr+="0"}

if(pStr =='.') pStr ='';

if(dStr.length > separatorLength)
{
// Logic of separation
while( dStr.length > separatorLength)
{
NewValue = "," + dStr.substr(dStr.length - separatorLength) + NewValue;
dStr = dStr.substr(0,dStr.length - separatorLength);
}

NewValue = dStr + NewValue;

}
else
{
NewValue = dStr;
}


// Add decimal part
NewValue = NewValue + pStr;

// Show Final value
alert(NewValue);



}

</script>
 Fig (1) Thousand Separator Function in Java Script

   You just need to  pass 2 parameters. Number of digits require after decimal point and value you want to conver in thousand seperated format.


Happy Programming !!

Saturday, May 26, 2007

An error occured while establishing a connection to server. When connectiing to SQL Server 2005,...SQL Network Interfaces, error:26 - Error Locating Server/Instance Specified.

      I have seen this error so many time so I thought that let me post the solution that work for me. First thing check your connection string that it points correct server. This is the most common mistake. Sometime connection string points to SQL Express, while machine does not have SQL Expressed installed.

      If the connection string is correct, second step is to check congiguration of SQL. Click on Start - All Programms - Sql Server 2005 - Configuration Tool - SQL Server Configuration Manager. 

      Click on SQL Server 2005 Network configuration - Protocols for MS SQL Server. Make sure that TCP/IP and Named Piped are Enable. If not that enable it. Now click on SQL Server 2005 Services. Restart Sql Server Browser Service and then restart SQL Server (MSSQLSERVER) service. Yupiiii !!! its all. Check your application now your error should be resolved.

Happy Programming !!

Thursday, May 24, 2007

Disable right click on page.

       Here is the code to disable right click on page.

<html>
<body oncontextmenu="return false;">
     Try right click.
</body>
</html>

   Happy Programming !!

Prototype.js

       Today while surfing, I found a good javascript framework Prototype.js. It is a JavaScript library written by Sam Stephenson. This amazingly well thought and well written piece of standards-compliant code takes a lot of the burden associated with creating rich, highly interactive web pages that characterize the Web 2.0 off your back.

       This framework helps the developers to write a good javascript witout knowing much about syntax of javascript and reduce the overhead of remembering lots of complex function.

      You can download this library from here.

       Here is a really good artilce which explains few methods of prototype.js with examples.