Navi's

Necessity, the mother of invention

  • Twitts

    Error: Twitter did not respond. Please wait a few minutes and refresh this page.

  • RSS My Reader

    • An error has occurred; the feed is probably down. Try again later.
  • Top Clicks

    • None
  • Advertisements
  • Visitor Map

    Locations of Site Visitors
  • Flag Counter

    free counters

Archive for the ‘.Net’ Category

How to check CURSOR Status in SQL Server?

Posted by Navi's on June 8, 2012

We can check the cursor status using bellow scalar function. It will return smallint value


SELECT CURSOR_STATUS('global','cursor_name')

It will return single value and each value have different meaning. Below we can find the meaning of returned value

Return value Cursor name Cursor variable

1

The result set of the cursor has at least one row.For insensitive and keyset cursors, the result set has at least one row.

For dynamic cursors, the result set can have zero, one, or more rows.

The cursor allocated to this variable is open.

For insensitive and keyset cursors, the result set has at least one row.

For dynamic cursors, the result set can have zero, one, or more rows.

0 The result set of the cursor is empty.* The cursor allocated to this variable is open, but the result set is definitely empty.*
-1 The cursor is closed. The cursor allocated to this variable is closed.
-2 Not applicable. Can be:No cursor was assigned to this OUTPUT variable by the previously called procedure.

A cursor was assigned to this OUTPUT variable by the previously called procedure, but it was in a closed state upon completion of the procedure. Therefore, the cursor is deallocated and not returned to the calling procedure.

There is no cursor assigned to a declared cursor variable.

-3 A cursor with the specified name does not exist. A cursor variable with the specified name does not exist, or if one exists it has not yet had a cursor allocated to it.

Reference URL: http://bit.ly/KDcw3O

Advertisements

Posted in .Net | Leave a Comment »

Get Distinct from DataTable

Posted by Navi's on May 6, 2011

Most of the time we require to get Distinct data from DataTable. But there is no method in existing Framework. So, If you want to select distinct data for selected columns you can use bellow code snippets

private DataTable SelectDistinct(DataTable SourceTable, params string[] FieldNames)
{
     object[] lastValues;
     DataTable newTable;
     DataRow[] orderedRows;

     if (FieldNames == null || FieldNames.Length == 0)
          throw new ArgumentNullException("FieldNames");

     lastValues = new object[FieldNames.Length];
     newTable = new DataTable();

     foreach (string fieldName in FieldNames)
          newTable.Columns.Add(fieldName, SourceTable.Columns[fieldName].DataType);

     orderedRows = SourceTable.Select("", string.Join(", ", FieldNames));

     foreach (DataRow row in orderedRows)
     {
          if (!fieldValuesAreEqual(lastValues, row, FieldNames))
          {
               newTable.Rows.Add(createRowClone(row, newTable.NewRow(), FieldNames));

               setLastValues(lastValues, row, FieldNames);
          }
     }

     return newTable;
}

private bool fieldValuesAreEqual(object[] lastValues, DataRow currentRow, string[] fieldNames)
{
     bool areEqual = true;

     for (int i = 0; i < fieldNames.Length; i++)
     {
          if (lastValues[i] == null || !lastValues[i].Equals(currentRow[fieldNames[i]]))
          {
               areEqual = false;
               break;
          }
     }

     return areEqual;
}

private DataRow createRowClone(DataRow sourceRow, DataRow newRow, string[] fieldNames)
{
     foreach (string field in fieldNames)
          newRow[field] = sourceRow[field];

     return newRow;
}

private void setLastValues(object[] lastValues, DataRow sourceRow, string[] fieldNames)
{
     for (int i = 0; i < fieldNames.Length; i++)
          lastValues[i] = sourceRow[fieldNames[i]];
}

How to use? It’s very simple…

You have to just pass the DataTable in SelectDistinct function and array of selected columns that you want to get in new datatable.

string[] arr1 = { "Column1", "Column2", "Column3" }; 

DataTable dt=SelectDistinct(dtExisting,arr1);

Posted in .Net | Leave a Comment »

Show loader on page load in asp.net

Posted by Navi's on March 24, 2011

To show loader while page is loading we have to use bellow code snippet. put this code on your master page or page. And overrride the OnLoad and Render methods.

protected override void OnLoad(EventArgs e)
    {
        if (!IsPostBack)
        {
            Response.Buffer = false;
            Response.Write("<div id='divImage'><div style='float: right;'><img src='loader.gif' />Please wait...</div></div>");
            Response.Flush();
        }
        base.OnLoad(e);
    }
    protected override void Render(HtmlTextWriter writer)
    {
        if (!IsPostBack)
        {
            Response.Clear();
            Response.ClearContent();
        }
        base.Render(writer);
    }
   

and to hide loader we uses bellow javascript code snippet. Put this code at the end of page

 
<script language="javascript" type="text/javascript">
        try
          {
                var divLImage =  document.getElementById("divImage")
                if (divLImage != null && typeof(divLImage ) != 'undefined')
                   {
                        divLImage .style.display="none";
                        divLImage .parentNode.removeChild(divLoadingMessage);
                   }
         }
        catch(e)
         {
         }
    
    </script>

css for loader div

#divImage {
     position: absolute;
    padding: 4px;
    top: 0px;
    right: 0px;
    color: gray;
    font-size: 13px;
    font-family: Verdana, Helvetica, Arial, sans-serif;
    width: 150px;
    font-weight: bold;
    height:20px;
}

Whenever you request any page it’ll show loader on that page during load.
That’s it 🙂

Posted in .Net, Javascript | 2 Comments »

Show loader during postback with ajax in asp.net

Posted by Navi's on March 24, 2011

To show loader during post back using ajax. We can do this very easy manner.
Please wait loader

First, we have to create css for loader.


#divImage {
    position: absolute;
    padding: 4px;
    top: 0px;
    right: 0px;
    color: gray;
    font-size: 13px;
    font-family: Verdana, Helvetica, Arial, sans-serif;
    width: 150px;
    height:20px;
 }

After this we have to include the scriptmanager on page or masterpage.

<asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>

Then we use bellow javascript function for async postback. We added two events InitializeRequest and EndREquest these events handles the loader to show/hide.

<script type="text/javascript">
             // Get the instance of PageRequestManager.
             var prm = Sys.WebForms.PageRequestManager.getInstance();
             // Add initializeRequest and endRequest
             prm.add_initializeRequest(prm_InitializeRequest);
             prm.add_endRequest(prm_EndRequest);
            
             // Called when async postback begins
             function prm_InitializeRequest(sender, args) {
                 // get the divImage and set it to visible
                 var panelProg = $get('divImage');                
                 panelProg.style.display = '';
             }
 
             // Called when async postback ends
             function prm_EndRequest(sender, args) {
                 // get the divImage and hide it again
                 var panelProg = $get('divImage');                
                 panelProg.style.display = 'none';
             }
    </script>

Now, we define the loader div in UpdatePanel.

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <div id="divImage" style="display: none">
                <div style="float: right;">
                    <img src="loader.gif" height="20px" />Please wait...</div>
            </div>
        </ContentTemplate>
    </asp:UpdatePanel>

Whenever the async post back occurs the loader div will show and hide when request ends.

That’s it… 🙂

To generate loader image we can use bellow links
ajaxload.info
preloaders.net

Posted in .Net, Javascript | Leave a Comment »

Disable Right Click using jQuery

Posted by Navi's on January 20, 2011

To disable right click on web page you can do this using jQuery.

You can download jQuery Library and include it and use bellow code of snippet.


<script src="jquery.min.js" type="text/javascript"></script>

$(function() {
            $(this).bind("contextmenu", function(e) {
                e.preventDefault();
            });
        }); 

That it 🙂

Posted in .Net, Javascript, jQuery | Tagged: | Leave a Comment »

Datatable to Generic collection and vice versa

Posted by Navi's on January 13, 2011

Most of the time we need to convert Generic Collection(GC) to DataTable(DT) and Data Table(DT) to Generic Collection(GC). For that bellow two functions are very helpfull to Convert Generic Function(GC) to DataTable(DT) and vice versa.

To convert DataTable(DT) to Generic Collection(GC) you can use bellow code snippet

Pass the DataTable(DT) object to bellow function and it will return you the Generic Collection(GC) of given type.

 public static List<T> ConvertTo<T>(DataTable table)
        {
            List<T> list = new List<T>();
            if (table == null)
            {
                return null;
            }

            List<DataRow> rows = new List<DataRow>();

            foreach (DataRow row in table.Rows)
            {
                T item = CreateItem<T>(row);
                list.Add(item);
            }

            return list;
        }
 public static T CreateItem<T>(DataRow row)
        {
            Type objType = typeof(T);
            T obj = Activator.CreateInstance<T>();
            if (row != null)
            {
                foreach (DataColumn column in row.Table.Columns)
                {
                    PropertyInfo prop = objType.GetProperty(column.ColumnName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                    object value = row[column.ColumnName];
                    if (value.Equals(DBNull.Value))
                        value = null;

                      prop.SetValue(obj, Convert.ChangeType(value, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType), null);
                   
                }
            }

            return obj;
        }

To convert Generic Collection(GC) to DataTable(DT) you can use bellow code snippet.

Pass the List object in bellow function and it will return DataTable(DT).

        public static DataTable ListToDataTable<T>(List<T> list)
        {
            DataTable dt = new DataTable();

            foreach (PropertyInfo info in typeof(T).GetProperties())
            {
                dt.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
            }
            foreach (T t in list)
            {
                DataRow row = dt.NewRow();
                foreach (PropertyInfo info in typeof(T).GetProperties())
                {
                    row[info.Name] = info.GetValue(t, null) != null ? info.GetValue(t, null) : DBNull.Value;
                }
                dt.Rows.Add(row);
            }
            return dt;
        }

References:
http://bit.ly/gck7q4
http://bit.ly/ebDP0Q

Posted in .Net, Technical | Leave a Comment »

Dropdownlist with checkbox

Posted by Navi's on July 15, 2010

Some times we need a DropDownList with checkbox. Either we use some ready made controls like Infragistics WebDropDown or create your own with TextBox, CheckBoxList and AjaxControlToolkit.

So, If we want to create our own DropDownList with checkbox we need first AjaxControlToolkit. You can download it from here.

We will use PopupControlExtender control. So lets start.

First add the one TextBox control and set some properties of its.

<asp:TextBox ID="txtDropDown" runat="server" Text="Select" ReadOnly="true" Style="background: url(DropDownarrow.png) no-repeat right; border: solid 1px #7F9DB9; padding-right: 30px;"></asp:TextBox>

Now Put Panel control with some default settings. Add CheckBoxList control within the Panel and PopupControlExtender control after the panel .

<asp:Panel ID="pnlDDL" runat="server" BackColor="White" Style="border: solid 1px #7F9DB9; overflow: auto; overflow-x: hidden; display: none; height: 250px; width: 250px;">

<asp:CheckBoxList id="chkList" runat="server"/>
</asp:Panel>

<ajaxtoolkit:PopupControlExtender runat="server" ID="popExtDDL" TargetControlID="txtDropDown" PopupControlID="pnlDDL" Position="Bottom" />

That’s it. Now you can Bind the CheckBoxList control with DataSource and it will show you the dropdown with CheckBox.
If you want to add the select all checkbox you can add the checkbox above the CheckBoxList. You can use simple HTML control checkbox control.

<input type="checkbox" id="chkAll" style="margin-left: 3px; display: none; font-size: 8pt" /><span style="font-size: 8pt;">Select All</span>

And use the jQuery for select all. To use jQuery you need to include the jQuery library in your page. You can download it from here.

 $(document).ready(function() {
            $('#chkAll').click(function() {
                $("#<%= chkList.ClientID %> input:checkbox").attr('checked', this.checked);
            });
});

This is the benefit of jQuery.

Now we need to selected items of CheckBoxList. For this we can use LINQ in place of looping.

IEnumerable<int> allChecked = (from item in chkList.Items.Cast<ListItem>()
                               where item.Selected
                               select int.Parse(item.Value));

This will return you the collection of selected items.

References:
http://bit.ly/99luaN

Posted in .Net, Javascript | 1 Comment »

Drag n Drop in asp.net

Posted by Navi's on June 9, 2010

To Implement the drag n drop functionality in Web application we can use different api’s.
But we can achieve this without using any api.

DND requires three basic events i.e. onmousedown, onmousemove and onmouseup.

You can achieve the DND using these three events. So, on onmousedown you can get the dragged control-id and change its x and y position on onmousemove event. and on onmouseup event drop that control.

To find out the drag able control we apply additional class on it and give any name to that class. you can define that class on style-sheet of on page in style like this

.drag{ 
       cursor:default;
       height:50;
       width:50;
       background-color:red; 
 }

Apply this drag class to identify the div using class name.

<div class='drag' id=d1/>

first create the OnDrag function which identify the event and control to be move

var draged = false
var dragElement
var x, y

function OnDrag(event) {
              if (event == null)
                    event = window.event;

 var target = event.target != null ? event.target : event.srcElement;

 if (target.className == "drag") {
		y = event.clientY;
                          x = event.clientX;
}
 
 document.onmousemove = OnMouseMove;

return false;
}

On OnMouseMove Event


function OnMouseMove(event) {
  if (event == null)
                  event = window.event;

if ((event.button == 1 && draged && window.event != null || event.button == 0 && draged) && dragElement.className == "drag") {
                  dragElement.style.left = event.clientX - x - document.body.scrollLeft + 'px';
                  dragElement.style.top = event.clientY - y - document.body.scrollTop + 'px';
                  return false;

}

On OnMouseUp event


 function OnMouseUpEvent() {
draged = false;
}

This is the basics of DND. You can modify as per your requirement.

Posted in .Net | 2 Comments »

Modify Style css class value by Javascript

Posted by Navi's on March 26, 2010

Very critical problem like we have a table and it contains lots of rows  and we need to change the CSS (background color) for each row.

What are the possible solution for this:
Either traverse each rows of table and set CSS class or use jQuery for add CSS class

but above solutions takes too much performance issues.

For this problem I got an idea i.e. Modify applied Style CSS at run time.

So, we need to create same copy of CSS style which already applied on rows of table.
Suppose we applied .xyz class on each rows.

<tr class='xyz'> 

And in .xyz class is look like this .xyz{ background:red}
We will change this .xyz class at run time and set background: green

This terminology is called set Rules (IE) or CssRules(Netscape familly) for style sheet.

To detect browser use navigator.appName and compare this value with “Netscape” or “Microsoft Internet Explorer”

First put the style sheet block in head section.

Setting rules for IE:

var inStyleSheet = document.styleSheets["inStyleSheetBlock"];

//Add rule
 if (inStyleSheet.rules.length == 0) {
inStyleSheet.addRule("tr .xyz", "background-color: green");
inStyleSheet.addRule("tr .xyz", "background-color: green");
}

//Remove rule
for (i = 0; i < inStyleSheet.rules.length; i++) {
                        inStyleSheet.removeRule()
                    }

To remove all rules from page we need to make a recursive call, because its not removing all applied rule at once. So we have to call removeRule till it will remove all created rules.

To get the how many rules at present in a page we can use rules.length property. It will return the count of rules in named style block.

 if (inlineStyleSheet.rules.length != 0)
            for (i = 0; i < inStyleSheet.rules.length; i++) {
                        inStyleSheet.removeRule()
                    }

Set rules for Netscape family [ Firefox ] :

var inStyleSheet = document.getElementById('inStyleSheetBlock').sheet;

//Add rule
inStyleSheet.insertRule("tr .xyz {background-color: green}", 0);
inStyleSheet.insertRule("tr .xyz {background-color: green}", 1);

//Remove rule

for (i = 0; i < inStyleSheet.cssRules.length; i++) {
                        inStyleSheet.deleteRule(i)
                    }

Same recursive steps applied here to remove rule.

if (inlineStyleSheet.cssRules.length != 0)
     for (i = 0; i < inStyleSheet.cssRules.length; i++) {
                        inStyleSheet.deleteRule(i)
                    }

Perform add and delete rules based on your condition.

References :
http://bit.ly/cCtKQY
http://bit.ly/cTBDIO
http://bit.ly/9IGBRk
http://bit.ly/40NVsg

-n’s

Posted in .Net, Javascript | 11 Comments »

Delete Items from Listview using Deleting event

Posted by Navi's on January 7, 2010

You can delete items on Listview by Deleting Event

using this event

protected void ListView1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
  Int32 Id = Int32.Parse(ListView1.DataKeys[e.ItemIndex].Value.ToString());
}

or you can get another key using

ListView1.DataKeys[e.ItemIndex]["Name"].ToString();

-n’s

Posted in .Net | 1 Comment »