Praveen’s Blog

Just another WordPress.com weblog

Reading data from excel using OleDb

Posted by pnamburi on April 12, 2011

Providing the right connection string is the key. The connection strings are different for .xls (office 2003) and .xlsx (office 2007 and later) documents.

OleDbConnection oleConnection = null;
string filePath = @"E:\docs\doc1.xls";
string tableName = string.Empty;

string connString2003 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=’Excel 8.0;HDR=Yes;IMEX=1;’";

filePath = @"E:\docs\doc2.xlsx";

string connString2007 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=’Excel 12.0;HDR=No;IMEX=1;’";

oleConnection = new OleDbConnection(connString);
oleConnection.Open();

"HDR=Yes;" in the indicates that the first row contains columnnames, not data. "HDR=No;" indicates otherwise.

Once the connection is opened successfully, we can retrieve various other information like the sheets present etc. Now we will query the document’s schema to get the table(sheet) name and the data on the sheet.

using (DataTable oleSheets = oleConnection.GetOleDbSchemaTable(
           System.Data.OleDb.OleDbSchemaGuid.Tables,
           new object[] { null, null, null, "TABLE" }))
{
    tableName = string.Format("[{0}]", oleSheets.Rows[0]["TABLE_NAME"].ToString());
}

DataSet oleDataSet = new DataSet();
OleDbCommand oleCommand = new OleDbCommand();
oleCommand.Connection = oleConnection;
oleCommand.CommandText = string.Format("SELECT * FROM {0}", tableName);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter(oleCommand);
oleAdapter.Fill(oleDataSet);
oleConnection.Close();

For more information, please refer to this link here

Posted in ADO.NET Retrieving data | Leave a Comment »

Serializable & Read Committed

Posted by pnamburi on February 8, 2011

This article describes a few of the different kinds of locks that sql server holds on the database objects.

Shared Locks These are the locks that the sql server uses when querying a table. There can be multiple shared locks on the same table.

Exclusive Locks are acquired when an insert/update/delete operations are performed. These locks cannot co-exist with any other kind of locks.

Schema Locks are used to prevent modification or dropping a table or an index when it is in use.

Below I have described how a serializable transaction isolation level can lead to a deadlock. Let see briefly what the serializable and read commited isolation levels do:

Serializable: This is the highest level of isolation that sql server provides. In this mode all the transactions appear to execute in a sequential manner. It does not release the locks it has acquired (even shared locks) until the transaction is completed/rolledback.

Read Committed: Sql Server decides to place shared locks when querying. In this mode, sql server releases the shared locks once the query has returned and does not wait until the transaction is completed/rolledback.

Here is an example that describes the above statements. Consider a simple script that has a select and an update statement as below:

Set Transaction Isolation Level Serializable
BEGIN TRANSACTION    
    Select * from TableA order by 1 desc
    UPDATE TableA set columnA=1 where columnB=5   

COMMIT TRANSACTION

As you have seen above the isolation level is in serializable mode. So when this script executes in parallel there are chances of deadlock to occur. It is easy to manually have the deadlock occur by following these steps:

1. Execute the first script (Transaction A) up till the select statement.

2. Execute the second one (Transaction B) completely.

3. Now execute the remainder of first script (Transaction A).

You will see that a deadlock occurs and at this point sql server chooses one of the processes to be the deadlock victim. The error message is as shown below:

Transaction (Process ID xxx) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

The deadlock occurs because the shared lock has been acquired by both the transactions. In addition to this, in step 2, Transaction B wants to acquire an exclusive lock when it see the update statement but waits till the shared lock held by Transaction A is released.

Now in step 3 when the remainder of the Transaction A is executed, it in turn waits till the shared lock held by Transaction B is released. As a result both the transactions are waiting for one another resulting in deadlock.

Posted in Database Programming/Administration | Leave a Comment »

SQL Server Transactions & @@TRANCOUNT variable

Posted by pnamburi on October 6, 2010

The global variable @@TRANCOUNT is initially zero when the stored procedure begins execution. When each transaction is begun the variable increments by one. If any error occurs the transaction is rolled back. At this point the value of the global variable comes down to zero irrespective of the number of transactions begun. For each transaction that is started within the scope of the code, there has to be a commit transaction statement, otherwise SQL Server will throw an error saying the global variable value is different at the execution times of the proc enter and proc exit. The sql error is given below. This is the same case with nested transactions.

Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing. Previous count = 0, current count = 1.

For e.g. here is a stored procedure [TRANSTEST_Proc1] which makes use of the @@trancount variable and initiates some transactions. It calls another procedure [TRANSTEST_Proc2]. You can play around with a code to get a hang on the topic.

ALTER PROCEDURE [dbo].[TRANSTEST_Proc1]

AS
BEGIN

——————————————————————————–
— DECLARE
——————————————————————————–
DECLARE @RC int
DECLARE @BeginTranCount    INT

——————————————————————————–
— PROCESSING
——————————————————————————–
SET NOCOUNT ON

    BEGIN TRY
        SET @BeginTranCount = @@TRANCOUNT
        BEGIN TRANSACTION
        IF @BeginTranCount = 0
        BEGIN
            PRINT ‘Proc 1 – Begin Transaction’
            BEGIN TRANSACTION
        END
        PRINT ‘Proc 1 – @@TRANCOUNT = ‘ + CONVERT(varchar, @@TRANCOUNT)

        INSERT INTO [Form]
                   ([Name]
                   ,[Description]
                   ,[IsDeleted]
                   ,[CreateUserID]
                   ,[CreateDate]
                   ,[LastUpdateUserID]
                   ,[LastUpdateDate])
             VALUES
           (‘Insert2′
           ,’Insert2′
           ,’False’
           ,1
           ,getdate()
           ,1
           ,getdate())

        EXEC [TRANSTEST_Proc2]

        — TODO: Set parameter values here.

        PRINT ‘Proc 1 – @RC=’+IsNull(Convert(VarChar, @RC), ‘Null’)
        –EXECUTE @RC = [Nams].[dbo].[TRANSTEST_Proc3]
        IF @@TRANCOUNT > @BeginTranCount
        BEGIN
            COMMIT TRANSACTION
            PRINT ‘Proc 1 – Transaction Commited’
            PRINT ‘Proc 1 – @@TRANCOUNT = ‘ + CONVERT(varchar, @@TRANCOUNT)
            COMMIT TRANSACTION — Will throw error commot transaction has no corresponding begin transaction
            PRINT ‘Proc 1 – @@TRANCOUNT = ‘ + CONVERT(varchar, @@TRANCOUNT)
        END
    END TRY
    BEGIN CATCH
        PRINT ‘Proc 1: Error I am here’
        IF @@TranCount > 0
        BEGIN
            ROLLBACK TRANSACTION
            PRINT ‘Proc 1 – @RC=’+IsNull(Convert(VarChar, @RC), ‘Null’)
            PRINT ‘Proc 1 – Transaction Rolledback’
            PRINT ‘Proc 1 – @@TRANCOUNT = ‘ + CONVERT(varchar, @@TRANCOUNT)
        END
    END CATCH
END

SET QUOTED_IDENTIFIER ON
GO

ALTER       PROCEDURE [dbo].[TRANSTEST_Proc2]

AS

SET NOCOUNT ON
——————————————————————————–
— DECLARE
——————————————————————————–
DECLARE @ErrNo        INT,
        @ProjStatusCode int
DECLARE @BeginTranCount                    INT

——————————————————————————–
— PROCESSING
——————————————————————————–
BEGIN TRY
    SET @BeginTranCount = @@TRANCOUNT       
    BEGIN TRANSACTION
    IF @BeginTranCount = 0
    BEGIN
        PRINT ‘Proc 2 – Begin Transaction’
        BEGIN TRANSACTION
    END
    PRINT ‘Proc 2 – @@TRANCOUNT = ‘ + CONVERT(varchar, @@TRANCOUNT)

    –INSERT INTO dbo.Form([Name]) Values(Null)
    INSERT INTO [Nams].[dbo].[User]
               ([Username]
               ,[FirstName]
               ,[LastName]
               ,[MiddleInitial]
               ,[IsActive]
               ,[CreateUserID]
               ,[LastUpdateUserID])
         VALUES
               (‘pnamburi’
               ,’Praveen’
               ,’Namburi’
               ,’L’
               ,’True’
               ,1
               ,1)

    IF @@TRANCOUNT > @BeginTranCount
    BEGIN
        COMMIT TRANSACTION
        PRINT ‘Proc 2 – Transaction Commited’
        PRINT ‘Proc 2 – @@TRANCOUNT = ‘ + CONVERT(varchar, @@TRANCOUNT)
        –COMMIT TRANSACTION — Will throw error commot transaction has no corresponding begin transaction
        PRINT ‘Proc 2 – @@TRANCOUNT = ‘ + CONVERT(varchar, @@TRANCOUNT)
    END

END TRY
BEGIN CATCH
        PRINT ‘Proc 2: Error I am here’
        IF @@TranCount > 0
        BEGIN
            ROLLBACK TRANSACTION
            PRINT ‘Proc 2 – Transaction Rolledback’
            PRINT ‘Proc 2 – @@TRANCOUNT = ‘ + CONVERT(varchar, @@TRANCOUNT)
        END

END CATCH

Posted in Database Programming/Administration | Leave a Comment »

Using DataContractSerializer

Posted by pnamburi on June 6, 2010

The DataContractSerializer class belongs to the System.Runtime.Serialization namespace within the System.Runtime.Serialization assembly. It is used to serialize an instance of a type to XML and save it into any IO stream, XmlWriter or an XmlDictionaryWriter and deserialize back the data in XML format from the IO stream, XmlReader or XmlDictionaryReader.

You will need are three things:

1. An instance of a type that you want to serialize/deserialize.

2. An instance of DataContractSerializer class.

3. An instance of class that can read/write data into/from the IO stream or xml reader/writer.

Below is a sample code that shows you how serialize a collection of users. Lets say we have an User object whose type is declared as given below. As you can see, we need to add DataContractAttribute to the class and DataMemberAttribute to the class properties that we want to serialize. These attributes are defined in System.Runtime.Serialization namespace within System.Runtime.Serialization assembly.

[DataContract]
public class User
{
    [DataMember]
    public string UserName { get; set; }

    [DataMember]
    public int UserId { get; set; }

    public User() { }
}

The UserCollection class attributed with DataContract and DataMembers is shown below.

[DataContract]
public class UserCollection : IEnumerable<User>
{
    private List<User> _Users;
    [DataMember]
    public List<User> Users
    {
        get
        {
            return _Users;
        }
        set
        {
            _Users = value;
        }
    }

    public UserCollection()
    {
        _Users = new List<User>();
    }

    public void Add(User user)
    {
        _Users.Add(user);
    }

    public IEnumerator<User> GetEnumerator()
    {
        return _Users.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return _Users.GetEnumerator();
    }

}

Here is the code to serialize the UserCollection using DataContractSerializer.

public static string ToXmlString(object obj, bool omitXmlDeclaration)
{
    DataContractSerializer dcSer = new DataContractSerializer(obj.GetType());
    StringBuilder xmlString = new StringBuilder();
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.OmitXmlDeclaration = omitXmlDeclaration;

    XmlWriter writer = XmlWriter.Create(xmlString, settings);
    dcSer.WriteObject(writer, obj);
    writer.Close();

    return xmlString.ToString();
}

The code below creates a collection of users and calls the above method which returns the XmlString.

User user = new User() { UserId = 101, UserName = "user101" };
_UserCollection.Add(user);
user = new User() { UserId = 102, UserName = "user102" };
_UserCollection.Add(user);

string userXml = DataContractSerializationHelper.ToXmlString(_UserCollection, false);

The Xml string would look like this:

UserCollection

This xml string can be sent as a sql parameter to a sql stored procedure to save multiple users at a single database call. In SQL SERVER 2000, we use the prepare document system stored procedure to get a document handle from the xml string. We then feed the document handle to the open xml function from which we can feed the xml data into a table. The code is shown below.

–Source: http://www.extremeexperts.com/SQL/Articles/OpenXML.aspx
— We get this by calling a stored procedure called sp_xml_preparedocument. We’ll talk more about this stored procedure in a moment.
–The RowPattern parameter specified which nodes we want OPENXML to process using XPath.
–The Flags parameter specifies the format of our results. The following values can be used: 
–0 – Default value. Attribute centric mapping.
–1 – Use Attribute centric mapping. 
–2 – Use element centric mapping. 
–8 – Only unconsumed data should be copied to the overflow property @mp;xmltext.

DECLARE @DocHandle int, @AnswerSet VarChar(MAX)

CREATE TABLE #TempUsers
(
    [UserId] Int,
    [UserName] VarChar(300)
)

SET @AnswerSet = N’

<UserCollection xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns=http://schemas.datacontract.org/2004/07/Namsoft.Users.Model>

<Users>

<User><UserId>101</UserId><UserName>user101</UserName></User>

<User><UserId>102</UserId><UserName>user102</UserName></User>

</Users>

</UserCollection>’

— prepare the xml document
EXEC sp_xml_preparedocument @DocHandle OUTPUT, @AnswerSet, ‘<root xmlns:n="http://schemas.datacontract.org/2004/07/Namsoft.Users.Model"/>’

            INSERT INTO #TempUsers ([UserId], [UserName])
            SELECT *             
            FROM OPENXML (@DocHandle, ‘/n:UserCollection/n:Users/n:User’,2)
                     WITH (
                            [UserId] int ‘n:UserId’,                       
                            [UserName]  varchar(300) ‘n:UserName’
                         )

            — remove the xml document
            EXEC sp_xml_removedocument @DocHandle

select * from #TempUsers

drop table #TempUsers

SQL Server 2005 has advanced support for Xml where it introduces the Xml DataType. More information about Xml DataTypes can be found on MSDN here. Here is a sample code to retrieve data from xml datatype.

DECLARE @AnswerSet Xml

CREATE TABLE #TempUsers
(
    [UserId] Int,
    [UserName] VarChar(300)
)

–SET @AnswerSet = N'<UserCollection xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Namsoft.Users.Model"><Users><User><UserId>101</UserId><UserName>user101</UserName></User>

<User><UserId>102</UserId><UserName>user102</UserName></User></Users></UserCollection>’
SET @AnswerSet = N'<UserCollection><Users><User><UserId>101</UserId><UserName>user101</UserName></User><User><UserId>102</UserId><UserName>user102</UserName></User></Users>

</UserCollection>’

INSERT INTO #TempUsers([UserId], [UserName])
SELECT
    T.c.value(‘./UserId[1]’,’int’),
    T.c.value(‘./UserName[1]’,’varchar(300)’)
FROM @AnswerSet.nodes(‘/UserCollection/Users/User’) T(c)

select * from #TempUsers
drop table #TempUsers

Posted in Object Serialization and Deserialization | Tagged: , | Leave a Comment »

Open RadWindow from within a RadWindow

Posted by pnamburi on March 31, 2010

To use RadWindows on a page you need to add a RadScriptManager and a RadWindowManager as shown below. Every radwindow has only one radwindow manager. The key point to take away is open both the radwindows using the same rad window manager.

<telerik:RadScriptManager ID="RadSriptManager1" runat="server" />
<telerik:RadWindowManager ID="RadWindowManager1" runat="server">

Adding a RadWindowManager enables you to call radopen method on the DOM window object. It takes two parameters url and the name of the window. Once you get the reference to the radwindow on the client, you can call various methods to set its location, behaviours, skin, width, height, title etc…

var oWindow = window.radopen(url, ‘WindowDemo1’);
        oWindow.setSize(width, height);
        oWindow.center();
        oWindow.set_behaviors(Telerik.Web.UI.WindowBehaviors.Move + Telerik.Web.UI.WindowBehaviors.Close);
        oWindow.set_title("<b>" + title + "</b>"); 
 
        //Start
        oWindow.Skin = "Outlook";
        oWindow.DestroyOnClose = true;
        oWindow.add_close(OnClientclose);
        oWindow.ReloadOnShow = true;
        oWindow.set_modal(true);
         //End
        /* Lock Parent Scrollbar  */
        var oTop = document.body.scrollTop;    
        document.body.scroll = "no";    
        document.body.style.overflow = "hidden";    
        document.body.scrollTop = oTop;

Now the WindowDemo1 opens up. It can get a reference to itself with the following function:

            function GetRadWindow() {
                var oWindow = null;
                if (window.radWindow) oWindow = window.radWindow;
                else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
                return oWindow;
            }

There are two ways now to open a new radwindow from the popup.

1. Obtain a reference to the parent window, and call radopen from there.

var oBrowserWnd = GetRadWindow().BrowserWindow;
oBrowserWnd.radopen("http://www.google.com", "WindowDemo2");

2. Obtain a reference to the radwindow manager present on the parent page. Call its open method to open a new window.

var parentRadWindowManager = oBrowserWnd.GetRadWindowManager();
var oWindow = parentRadWindowManager.open(url, "WindowDemo2");

(Or)

var oManager = GetRadWindow().get_windowManager();
oManager.open("http://www.google.com", "WindowDemo2");

If you have a scenario where there can be multiple radwindow managers on the parent page, you would be better off using the first method because GetRadWindowManager() returns the first manager found on the page.

You cannot directly transfer date from windowdemo2 to windowdemo1. You can accomplish this in a different manner. Essentially every rad window is internally an iFrame. So you need get the correct frame of windowdemo1 as shown below:

var oWindow = GetRadWindow();
//get a reference to the editor RadWindow
var copyEditor = oWindow.get_windowManager().getWindowByName("WindowDemo1");

// Get a reference to the CopyEditor’s content
var contentWin = copyEditor.get_contentFrame().contentWindow

Now you can essentially make any javascript function calls present on WindowDemo1 by using the contentWin reference.

Posted in RadWindow | 1 Comment »

Automatic Properties

Posted by pnamburi on February 24, 2010

Generally a class defines properties with an access type. Each of these properties is associated with a private backing field. With automatic properties an implicit backing field is created which we do not have access to. Automatic properties can have empty get and sets. It is not possible to assign a default value to an automatic property. These properties can be used on interfaces and abstract classess.

Here is a simple class with automatic properties declared of various types:

 

public class AutoProperty
{
    public int memberInt;
    public int AutoInt { get; set; }
    public string AutoString { get; set; }
    public bool AutoBool { get; set; }
    [DefaultValue(true)] // This default value is read by the code generators and visual studio designer to assign the specified value. The actual
        // default value is still false.
    public bool AutoBoolDefaultedTrue { get; set; }
    public double AutoDouble { get; set; }
    public float AutoFloat { get; set; }
    public decimal AutoDecimal { get; set; }
    public DateTime AutoDateTime { get; set; }
    public int? AutoNullableInt { get; set; }
    public bool? AutoNullableBool { get; set; }
    public long? AutoNullableLong { get; set; }
    public Weekday WeekDayP { get; set; }

    public AutoProperty()
    {
        AutoInt = 10;
    }
}

 

This part of the code displays the default values on the console:

AutoProperty autoProperty = new AutoProperty() { AutoInt = 20 }; // This will overwrite the value assigned in the contructor
Console.WriteLine(string.Format("Is Null: AutoNullableInt: {0}", autoProperty.AutoNullableInt == null));
Console.WriteLine(string.Format("Is Null: AutoNullableBool: {0}", autoProperty.AutoNullableBool == null));
Console.WriteLine(string.Format("Is Null: AutoNullableLong: {0}", autoProperty.AutoNullableLong == null));
Console.WriteLine(string.Format("Default: AutoInt: {0}", autoProperty.AutoInt));
Console.WriteLine(string.Format("Default: AutoDateTime: {0}", autoProperty.AutoDateTime));
Console.WriteLine(string.Format("Default: DateTime.MinValue: {0}", DateTime.MinValue));
Console.WriteLine(string.Format("Is AutoDateTime equal to DateTime.MinValue?: {0}", autoProperty.AutoDateTime.Equals(DateTime.MinValue)));
Console.WriteLine(string.Format("Default: AutoBool: {0}", autoProperty.AutoBool));           
Console.WriteLine(string.Format("Default: AutoBoolDefaultedTrue: {0}", autoProperty.AutoBoolDefaultedTrue));
Console.WriteLine(string.Format("Default: string.IsNullOrEmpty(autoProperty.AutoString): {0}", string.IsNullOrEmpty(autoProperty.AutoString)));
Console.WriteLine(string.Format("Default: AutoDouble: {0}", autoProperty.AutoDouble));
Console.WriteLine(string.Format("Default: WeekDayP: {0}", autoProperty.WeekDayP));

The output looks like shown below:

Is Null: AutoNullableInt: True
Is Null: AutoNullableBool: True
Is Null: AutoNullableLong: True
Default: AutoInt: 20
Default: AutoDateTime: 1/1/0001 12:00:00 AM
Default: DateTime.MinValue: 1/1/0001 12:00:00 AM
Is AutoDateTime equal to DateTime.MinValue?: True
Default: AutoBool: False
Default: AutoBoolDefaultedTrue: False
Default: string.IsNullOrEmpty(autoProperty.AutoString): True
Default: AutoDouble: 0
Default: WeekDayP: 0

Observation: A property or an indexer cannot be used as an out parameter. Here is the code which explains this:

string i = "5";
int.TryParse(i, out autoProperty.memberInt);
Console.WriteLine(string.Format("memberInt: {0}", autoProperty.memberInt));           

int.TryParse(i, out autoProperty.AutoInt); !Error A property or indexer may not be passed as an out or ref parameter.

Posted in C# .NET | Leave a Comment »

Open, Close and RefreshParent with RadWindow

Posted by pnamburi on January 11, 2010

Add this code to the popup page. It has javascript hooks to get the current rad window and close it. Keep in mind that the javascript is added to the head section of the page.

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="Default" %>
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>                           
        <script type="text/javascript" language="javascript">

            function GetRadWindow() {
                var oWindow = null;
                if (window.radWindow) oWindow = window.radWindow;
                else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
                return oWindow;
            }

            function Close() {               
                var oWindow = GetRadWindow();
                oWindow.argument = null;
                oWindow.close();
            }
</script>
</head>

In the body of the form, add a ScriptManager, a RadWindowManager and any other controls that form the content of the page. At the end lets say you have buttons to ‘Save’ or ‘Cancel’ out of the window.

You can also pass values to the parent window if necessary. Just assign the properties that you would want to pass to an object as shown below:

function Close(value1, value2) {
            var arg;
            if (value1&& value2) {
                arg = new Object();
                arg.value1= value1;
                arg.value2= value2;
            }
            GetRadWindow().Close(arg);
            return false;
        }

On the server side event handler of the ‘Save’ button, register a start up script as shown below. The script is rendered just before the <form id=”form1” runat=”server”> is closed.

If Not Page.ClientScript.IsStartupScriptRegistered("CloseWindow") Then
         Page.ClientScript.RegisterStartupScript(Me.GetType(), "CloseWindow", "Close();", True)
End If

Hook up the javascript to the Cancel button as below:

btnCancel.Attributes.Add("OnClick", "javascript:Close(); return false;")

The following things have to be done on the page where the popup is loaded from:

Here is the javascript to show the popup. Also notice that when the window is closed a callback method ‘OnClientClose’ is registered. To refresh the current page, the Page.ClientScript.GetPostBackEventReference(Me) is used. It returns a string that when spit out on the client causes a postback to occur. It takes in (in this case the Page) the control (IPostBackEventHandler) that handles the event on the server.

<script language="javascript" type="text/javascript">
    function ShowEditor(id, height, width, title) {
        var url = ‘Default.aspx?id=’ + id;
        var oWindow = window.radopen(url, null);
        oWindow.setSize(height, width);
        oWindow.center();
        oWindow.set_behaviors(Telerik.Web.UI.WindowBehaviors.Move + Telerik.Web.UI.WindowBehaviors.Close);
        oWindow.set_title("<b>" + title + "</b>");

        //Start
        oWindow.Skin = "Outlook";
        oWindow.DestroyOnClose = true;
        oWindow.add_close(OnClientclose);
        oWindow.ReloadOnShow = true;
        oWindow.set_modal(true);
         //End
        /* Lock Parent Scrollbar  */
        var oTop = document.body.scrollTop;    
        document.body.scroll = "no";    
        document.body.style.overflow = "hidden";    
        document.body.scrollTop = oTop;  
        return false;
    }

    function OnClientclose(sender, eventArgs) {
       

var arg = eventArgs.get_argument();
        if (arg)
        {
            var hfValue1= document.getElementById(‘<%= hfValue1.ClientID %>’);
            var hfValue2= document.getElementById(‘<%= hfValue2.ClientID %>’);
            hfValue1.value = arg.hfValue1;
            hfValue2.value = arg.hfValue2;
            <%= Page.GetPostBackEventReference(Me) %>;
        }  
    }
</script>

Say there is a LinkButton that opens a rad window and is declared as below:

<asp:LinkButton ID="lnkAddItem" runat="server" Text="Add New Item" />

Hook it up to open the rad window from code behind:

lnkAddItem.Attributes.Add("OnClick", "return ShowEditor(" & id.ToString() & "," & 550.ToString() & "," & 450.ToString() & ", ‘Add Item’);")

Posted in RadWindow | Leave a Comment »

Use of ROW_NUMBER and PARTITION to find duplicates

Posted by pnamburi on October 9, 2009

ROW_NUMBER function can be used to generate a row number for the result set that is returned by a query.

SELECT ROW_NUMBER() OVER(ORDER BY ContactName) As RowId, * FROM Customers

The row number function when combined with Common Table Expressions (CTE) can be used for paging the result set and return only certain number of rows.

WITH CustomersCTE As
(
    SELECT ROW_NUMBER() OVER(ORDER BY ContactName) As RowId, * FROM Customers
)
SELECT * FROM CustomersCTE WHERE RowId BETWEEN 1 AND 20

Finding duplicate rows

Generally we use a GROUP BY clause to find the duplicate rows. More t-sql code has to be written to delete these rows i.e we have to join the duplicates result set with itself, find the min record to keep and delete the other duplicate rows.

For ex:

    DELETE c FROM Customers c
    INNER JOIN
    (
        SELECT Col1, Col2, COUNT(‘X’) Cnt FROM 
        Customers c
        WHERE c.IsActive = 1
        GROUP BY Col1, Col2
        HAVING COUNT(‘X’) > 1
    ) dup ON c.Col1=dup.Col1 AND c.Col2=dup.Col2
    AND c.CustomerId NOT IN
        (

                SELECT MIN(c.CutomerId) FROM
                Customers c
                WHERE c.IsActive = 1
                GROUP BY Col1, Col2
                HAVING COUNT(‘X’) > 1 
        )

By using CTE and ROW_NUMBER funtions it is easy to delete duplicates as shown below:

;WITH DuplicateMappings As
(
        SELECT ROW_NUMBER() OVER(PARTITION BY Col1, Col2 ORDER BY CustomerId) As         ‘RowId’, *
        from Customers

)
SELECT * FROM DuplicateMappings WHERE RowId>1 ORDER BY CustomerId desc

I order by customerId just to find the last inserted records that will get deleted.

Posted in Database Programming/Administration, T-SQL | Leave a Comment »

Find an item in a collection using List.Find method

Posted by pnamburi on October 7, 2009

We use the Predicate<T> Delegate to find an item in a collection based on a criteria. The delegate represents the method that defines a set of criteria and determines whether the specified object meets those criteria.

 

The Predicate<T> delegate is as given below:

public delegate bool Predicate<T>( T obj )

1. Create any generic collection class that either inherits from List<T> or internally maintains its collection in an List<T>.

public class GenericCollection<T> : List<T>

{

        /// <summary>
        /// Finds the specified predicate.
        /// </summary>
        /// <param name="predicate">The predicate.</param>
        /// <returns></returns>
        public T Find(Predicate<T> predicate)
        {
                return genericList.Find(predicate);
        }

}

2. Create a method that represents the predicate in your item object that constitutes the collection

public class MyObject

{

        public DateTime StartDate
        {
            get { return _dateStarted; }
            set
            {
                _dateStarted = value;                 
            }
        }

        public DateTime EndDate
        {
            get { return _dateEnded; }
            set
            {
                _dateEnded = value;                 
            }
        }

        public bool FindMinimum(MyObject obj)
        {
            if (obj.StartDate < startDate && obj.StartDate != DateTime.MinValue && startDate != DateTime.MinValue)
                return true;
            else return false;           
        }

        public bool FindMaximum(MyObject obj)
        {
            if (obj.EndDate > endDate && endDate != DateTime.MinValue && obj.EndDate != DateTime.MaxValue)
                return true;
            else return false;
        }

}

3. Once you have an instance of the collection and an object to match against, you can find your object like this:

GenericCollection<MyObject> objColl = new GenericCollection<MyObject>();

MyObject searchTarget = new MyObject() { StartDate = “10/07/2009”, EndDate = “11/07/2009” };

MyObject objectFound = objColl.Find(searchTarget.FindMinimum);

In our example the predicate involves two fields the StartDate and the EndDate which essentially form our search parameters. You can also use anonymous predicates as shown below.

MyObject objectFound = objColl.Find(delegate(MyObject obj)

                return (obj.EndDate > endDate && endDate != DateTime.MinValue && obj.EndDate != DateTime.MaxValue);

        );

Posted in C# .NET, Container Classes | Leave a Comment »

Viewing Available MIME Types

Posted by pnamburi on September 30, 2009

If a particular MIME type is not registered with the IIS, the GET operation on that type will fail. I ran into this problem with some resource files (having .properties extension). I used Fiddler to find that the request to these file types was failing with 404 ‘Page not found’ error. This works on IIS 5.1 but not on IIS 6.

I found the information below useful for retrieving a list of all the MIME types currently registered with IIS.

Source: Microsoft TechNet

To help prevent attackers from sending files that could compromise the security of your Web server, the IIS static file handler serves only the files that are explicitly listed in the list of Multipurpose Internet Mail Extensions (MIME) types. IIS is preconfigured to recognize a default set of global MIME types that are recognized by all of the Web sites that you create with IIS.

Procedures

ImportantImportant

You must be a member of the Administrators group on the local computer to perform the following procedure or procedures. As a security best practice, log on to your computer by using an account that is not in the Administrators group, and then use the runas command to run IIS Manager as an administrator. At a command prompt, type runas /user:Administrative_AccountName "mmc %systemroot%\system32\inetsrv\iis.msc".

To see a list of all available MIME types by using IIS Manager

  1. In IIS Manager, right-click the local computer, and then click Properties.

  2. In MIME types, click MIME Types.

    The registered MIME types are displayed in Registered MIME types (file extensions). You can add, change, or remove MIME types from the list.

To see a list of all available MIME types by using Adsutil.vbs

  1. From the Start menu, click Run.

  2. In the Open box, type cmd, and then click OK.

  3. At the command prompt, switch to the drive\Inetpub\AdminScripts directory.

  4. Type the following at the command prompt and then press ENTER:

    cscript.exe adsutil.vbs enum /Mimemap

Related Sections

Posted in IIS Administration | Leave a Comment »