Dec 31, 2011

Easily build powerful client-side AJAX paging, using jQuery

When I suggest that developers consider using web services and a more client-centric approach to solve their UpdatePanel performance problems, the lack of paging is often their first objection.
Conventional ASP.NET wisdom seems to hold that the GridView/UpdatePanel combo is king when asynchronously paging through a data source. If you’ll give me a few minutes of your time, I’d like to challenge that notion!

To read more click on the below link
http://encosia.com/easily-build-powerful-client-side-ajax-paging-using-jquery/

Inline text editing with ASP.NET AJAX

This is a technique that I really like. It’s excellently suited to intranet sites and administrative interfaces, where your users are typically familiar enough with the application to know which text they can click to edit. It’s actually very easy to implement, with a small amount of JavaScript.


to view code click on below link

http://encosia.com/seamless-inline-text-editing-with-aspnet-ajax/

how to pass a JavaScript object to a .NET webservice that expects a parameter of type object.

Introduction

This article shows how to pass a JavaScript object to a .NET webservice that expects a parameter of type object. JSON is an enormously powerful and lightweight way to send data to and from a webservice, however if there are a number of parameters that are needed to be sent to webservice, building a JSON string can be a pain, and having to set your webmethod to expect a matching number of parameters can be equally as painful. This article shows how to build and pass a JavaScript object "Customer" and pass it to a .NET webservice webmethod that is expecting an object of type "Customer".

for more click on below link
http://smartprogrammingspot.blogspot.com/2010/06/javascript-objects-to-net-webmethods.html

Why ASP.NET AJAX UpdatePanels are dangerous

If you’re like me, it’s hard to resist the lure of tossing a half dozen UpdatePanels on every page and reveling in AJAX goodness. The UpdatePanel makes AJAX trivially easy for anyone to implement, even without knowledge of what’s actually going on behind the scenes.
Unfortunately, that very lack of transparency regarding the mechanics of the client/server exchange makes it all too easy to shoot yourself (or your application) in the foot. Let me give you an example that you’re probably familiar with by now, and thoroughly sick of seeing:


for more view below links
http://encosia.com/why-aspnet-ajax-updatepanels-are-dangerous/

Dec 29, 2011

Formula for Create Amount In String in Crystal Report .net





numbervar RmVal:=0;
numbervar Amt:=0;
numbervar pAmt:=0;
stringvar InWords :=" ";

Amt := {sp_OfferHeaderReport;1.nMTotalOfferValue};

if Amt > 10000000 then RmVal := truncate(Amt/10000000);
if Amt = 10000000 then RmVal := 1;
if RmVal = 1 then
InWords := InWords + " " + towords(RmVal,0) + " crore"
else
if RmVal > 1 then InWords := InWords + " " + towords(RmVal,0) + " crores";
Amt := Amt - Rmval * 10000000;
if Amt > 100000 then RmVal := truncate(Amt/100000);
if Amt = 100000 then RmVal := 1;

if Amt> 100000 then

InWords := InWords + " " + towords(RmVal,0) + " lakhs";
Amt := Amt - Rmval * 100000;
if Amt > 0 then InWords := InWords + " " + towords(truncate(Amt),0);
pAmt := (Amt - truncate(Amt)) * 100;
if pAmt > 0 then
InWords := InWords + " and " + towords(pAmt,0) + " paisa only"
else
InWords := InWords + " only";
UPPERCASE(InWords)

Dec 21, 2011

Sample Web Method

=============================== Aspx Page Source ============================


<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>


<!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 id="Head1" runat="server">
    <title>:: Using PageMethods :: </title>
    <style type="text/css">
        #MessagePlaceholder
        {
            background-color: #C0C0C0;
        }
    </style>
</head>
<body>
    <script language="javascript" type="text/javascript">
       // Step 4: Use the PageMethod from code
       function getServerGreeting() {
           $get("MessagePlaceholder").innerHTML =
               "<img alt=\"Please Wait\" src=\"image\\ajaxwait01.gif\" />";
           // NOTE: Instead of using getElementById in the last
           // statement, ASP.AJAX has a shortcut to this method
           // that does the same thing, $get.
           // Call the server method
           PageMethods.GetGreeting(getServerGreeting_Success);
           return false;
       }
       // Step 5: Process the callback
       function getServerGreeting_Success(result) {
           /// <summary>
           /// This is the callback method to handle the
           /// result from the server.
           /// </summary>
           /// <param name="result">The result from the server</param>
           $get("MessagePlaceholder").innerHTML = result;
           $get("<%= Label1.ClientID %>").innerText = 'on Label1 '+ result;
           $get("<%= TextBox1.ClientID %>").value = 'on TextBox1 '+ result;
       }
    </script>
    <form id="form1" runat="server">
        <div style="text-align:center; width:200px;">
            <!-- Step 1: Add a ScriptManager to the page -->
            <!-- Step 2: Set the EnablePageMethods property to true -->
            <asp:scriptmanager id="sm" runat="server" enablepagemethods="true" />
            
            <input type="button" value="Get Message Html Btn" onclick=" return getServerGreeting();" 
                style="width:145px;" /><br />
            <asp:Button ID="Button1" runat="server" Text="Asp Button with Page Method" 
                Width="192px" onclientclick=" return getServerGreeting();" />
            <br />
            <asp:Button ID="Button2" runat="server" 
                Text="Asp Button with without Page Method" onclick="Button2_Click" /><br />
            <asp:Label ID="Label1" runat="server" Text="Label" BackColor="#B6C8ED"></asp:Label>
            <br />
&nbsp;<asp:TextBox ID="TextBox1" runat="server" Width="340px"></asp:TextBox>
            <br />
            <div id="MessagePlaceholder"></div>
        </div>
    </form>
</body>
</html>


=============================== C# Page Code =================================



using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;


using System.Web.Services; /// new add for webMethod 
using System.Threading;/// for threading purpose (optional) if 




public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("On PageLoad: " + DateTime.Now.ToLongTimeString());
    }




    [WebMethod]
    public static string GetGreeting()
    {
        // Step 3: Create a static method and decorate it with
        //         the WebMethod attribute
        // In order to slow the method down a bit to illustrate
        // the async call, have the method wait 2 seconds.
        Thread.Sleep(2000); //optional
        // Return the result
        return "Hello PageMethods: "+DateTime.Now.ToLongTimeString();
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Write(" On Button Click : " + DateTime.Now.ToLongTimeString());
        TextBox1.Text = " On Button Click : " + DateTime.Now.ToLongTimeString();
        Label1.Text = " On Button Click : " + DateTime.Now.ToLongTimeString();
    }
}




Use Image





useful link
http://blogs.visoftinc.com/2008/09/07/asp-net-ajax-page-methods/


Dec 16, 2011

How to Get Last Day of the week and Month

DECLARE @Date datetime
SET @Date = '2000/02/1'
SELECT DATEADD(dd,-(DATEPART(dw, @Date) - 1),@Date) AS 'First day of the week'
SELECT DATEADD(dd,-(DATEPART(dw, @Date) - 7),@Date) AS 'Last day of the week'
SELECT DAY(DATEADD(d, -DAY(DATEADD(m,1,@Date)),DATEADD(m,1,@Date))) AS 'Last day of the month'

SELECT convert(varchar, DATEADD(d, -DAY(DATEADD(m,1,@Date)),DATEADD(m,1,@Date)), 101) AS 'Last Date of the month'

Insert into oracle table By XML In StoreProcedure

Well, after a bit of looking on Oracle's Metalink, I found some information on
passing XML to stored procedures via varchars or CLOBs. Here are examples of an
insert and of an update:

Create procedure to take in xml as a varchar or a clob:

create or replace procedure InsertXML(xmlDoc IN VARCHAR2, tableName IN
VARCHAR2) is

insCtx DBMS_XMLSave.ctxType;

rows number;

begin

insCtx := DBMS_XMLSave.newContext(tableName); -- get the context handle

rows := DBMS_XMLSave.insertXML(insCtx,xmlDoc); -- this inserts the document

dbms_output.put_line(to_char(rows) || ' rows inserted');

DBMS_XMLSave.closeContext(insCtx); -- this closes the handle

end;

The xml text that is passed must be in the form of:

<?xml version="1.0"?>

<ROWSET>

<ROW num="1">

<EMPID>10</EMPID>

<EMPNAME>Perry Smith</EMPNAME>

<EMPJOB>Manager</EMPJOB>

<EMPSAL>800</EMPSAL>

</ROW>

<ROW num="1">

<EMPID>20</EMPID>

<EMPNAME>John Calvach</EMPNAME>

<EMPJOB>Principal Support Consultant</EMPJOB>

<EMPSAL>900</EMPSAL>

</ROW>
</ROWSET>

Notice that the tags nested in the <ROW> tag are the same as the columns in
any table you would use. I don't know if it is case sensitive or not, but I
build all the xml as uppercase just in case.

This is using the internal Oracle XML parser for PL/SQL.

The update procedure is a bit different, because you have to tell it which
item is the primary key This procedure would update the empleados table which
has a primary key of empid:

create or replace procedure UpdateEmpleados ( xmlDoc IN VARCHAR2) is

updCtx DBMS_XMLSave.ctxType;

rows number;

begin

updCtx := DBMS_XMLSave.newContext('empleados'); -- get the context

DBMS_XMLSave.clearUpdateColumnList(updCtx); -- clear the update settings..

DBMS_XMLSave.setKeyColumn(updCtx,'EMPID'); -- set EMPNO as key column

rows := DBMS_XMLSave.updateXML(updCtx,xmlDoc); -- update the table.

dbms_output.put_line(to_char(rows) || ' rows updated');

DBMS_XMLSave.closeContext(updCtx); -- close the context..!

end;

And that's it! It seems to work quite well, and now I don't have to use the
<cftransaction> tag and let the database handle all rollbacks, etc.

Thanks for all the help on this!

Nov 28, 2011

Linking Sql Server 2005 to Oracle

Here is a quick guide to setting up linked servers so you can query Oracle through Sql Server.  For my testing of this I used Sql Server Express 2005, and Oracle 9.2.   This all uses simple commands that can be run via Query Analyzer or Query Tool.


First, if you've been doing this and having issues, you need to clear out any of your linked server's logins:

sp_droplinkedsrvlogin @rmtsrvname = 'LINKED_ORA', @locallogin = null

Next, drop the server

EXEC sp_dropserver LINKED_ORA

Ok, now let's add the linked server to Sql Server.  The linked server will be called LINKED_ORA.  Once this is done you should see this listed in SS Management Studio under  Server Objects->Linked Servers

-- add server
EXEC sp_addlinkedserver
  @server= 'LINKED_ORA'
, @provider='MSDASQL'
, @srvproduct='Oracle'
, @datasrc= 'myOracle'

@server - this is the name to use.  It can be anything
@provider - can be either MSDASQL and MSDAORA.  Both seem to both work fine.  There is talk of another provider from Oracle, but I have not gotten this one to work.
@srvproduct - must be "Oracle".  I do not know why this matters
@datasrc - this is a DSN that you have set up using Oracle's .NET manager

Now, the Oracle system does not implicitly let Sql Server connect.  You need to add a login for this linked server to use.

-- add login - the DSN is protected by a password
EXEC sp_addlinkedsrvlogin
  @rmtsrvname='LINKED_ORA'
, @useself='false'
, @rmtuser='oracleUserId'
, @rmtpassword='oraclePassword'

Once this is set, then you can test using this command:

--verify tables OK
exec sp_tables_ex @table_server = 'LINKED_ORA', @table_schema='MySchema'

@table_schema is optional.  If not provided, you will get a list of all  tables in all schemas.

This will return information about the tables in the linked server.  I use it as a basic diagnostic to verify that the linked server is working.  if it's not, then I use the scripts above to delete the login and linked server, then re-create using other inputs.

Now, the big pain with Oracle is that you cannot just query into the database. I know, it is ridiculous, but I found that only OPENQUERY works.  Here is how it looks:

SELECT * FROM OPENQUERY( LINKED_ORA, 'SELECT * FROM Exp.Proj')

But from there you can now do handy things in Sql Server.  One of my favorites is to re-create the Oracle schema in a Sql Server database, then use INSERT to pull in all of the Oracle data.  Then you can just work with Sql Server!

Nov 24, 2011

Upload file on fileUpload onchange event in asp.net



==================== ASPX code======================
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        <asp:FileUpload ID="FileUpload1" onchange="if (confirm('Upload ' + this.value + '?')) this.form.submit();" runat="server" />      
            <br />

<asp:RegularExpressionValidator ID="rexp" runat="server" ControlToValidate="FileUpload1"
     ErrorMessage="Only .DAT,.PNG,.BMP,.JPEG,.XLSX,.DOCX,.PPTX,
.DXF,.DRW,.SLD,.TXT,.PPT,.XLS,.PPS,.DOC,
.PDF,.GIF,.JPG,.RTF"
     ValidationExpression="(.*\.([Gg][Ii][Ff])|.*\.([Jj][Pp][Gg])|.*\.([Bb][Mm][Pp])|.*\.([pP][nN][gG])|.*\.([xX][lL][sS][xX])|.*\.([dD][oO][cC][xX])|.*\.([pP][pP][tT][xX])|.*\.([dD][xX][fF])|.*\.([dD][rR][wW])|.*\.([sS][lL][dD])|.*\.([tT][xX][tT])|.*\.([pP][pP][tT])|.*\.([xX][lL][sS])|.*\.([pP][pP][sS])|.*\.([dD][oO][cC])|.*\.([pP][dD][fF])|.*\.([dD][aA][tT])|.*\.([rR][tT][fF])$)"></asp:RegularExpressionValidator>


            <asp:Label ID="lblFileSize" runat="server" Text="Label"></asp:Label></div>
    </form>
</body>
</html>
==================================================

====================On page Load======================
protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {
            if (FileUpload1.HasFile)
            {
                string strFileName, strFileExtension;
                strFileName = FileUpload1.FileName;
                strFileExtension = strFileName.Substring(strFileName.LastIndexOf('.') + 1);
                lblFileSize.Text = FileUpload1.PostedFile.ContentLength.ToString();
                string strSavedFilePath = Server.MapPath("~//CTD_Files");
                strFileName = strFileName.Substring(0, strFileName.LastIndexOf('.')) + DateTime.Now.ToString("ddMMyyyyhhmmss") + "." + strFileExtension.Trim();
                strSavedFilePath += "\\" + strFileName;
                FileUpload1.PostedFile.SaveAs(strSavedFilePath);
            }
        }
    }

====================================================

Nov 22, 2011

How to give Link for Download or code for uploding and downloading file.

=========================== Upload Code ============================

 String strFileName = "", strFileExtension, strSavedFilePath;

            if (FileUploadCtd.HasFile)
            {
                strFileName = FileUploadCtd.FileName;
                strFileExtension = strFileName.Substring(strFileName.LastIndexOf('.') + 1);
                //if (strFileExtension.ToUpper() != "XLS")
                //{
                //    ClientScript.RegisterStartupScript(Page.GetType(), "", "<script>alert('Select Excel File Only.')</script>");
                //    return;
                //}
                strSavedFilePath = Server.MapPath("../CTD_Files");
                if (!Directory.Exists(strSavedFilePath))
                {
                    Directory.CreateDirectory(strSavedFilePath);
                }
                strFileName = strFileName.Substring(0, strFileName.LastIndexOf('.')) + DateTime.Now.ToString("ddMMyyyyhhmmss") + "." + strFileExtension.Trim();
                //strSavedFilePath += "\\" + strFileName.Substring(0, strFileName.LastIndexOf('.')) + DateTime.Now.ToString("ddMMyyyyhhmmss") + "." + strFileExtension.Trim();
                strSavedFilePath += "\\" + strFileName;
                FileUploadCtd.PostedFile.SaveAs(strSavedFilePath);

                objDesign._strvCTDPath = strFileName; // save in DB table.
                lblCTDLink.Text = strFileName;
            }
            else
            {
                objDesign._strvCTDPath = "";
                lblCTDLink.Text = "";
            }
            // CTD file uploading end Here

===============================================================

=========================On Page Load (Data Load) ====================

 // get file name from Db
lblCTDLink.Text = dtItemData.Rows[0]["vCTDPath"].ToString();

================================================================

======================= On download  link button click ====================

 protected void linkCTD_Click(object sender, EventArgs e)
    {
        // code for show donload link
        if (lblCTDLink.Text.Trim() != "")
        {
            string strSavedFilePath;
            strSavedFilePath = Server.MapPath("../CTD_Files" + "\\" + lblCTDLink.Text);
            FileInfo fileInfo = new FileInfo(strSavedFilePath);

            if (fileInfo.Exists)
            {
                Response.Clear();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
                Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                Response.ContentType = "application/octet-stream";
                Response.Flush();
                Response.WriteFile(fileInfo.FullName);
            }
        }
        else
        {
            objFnLib.WebMessageBox("No CTD Path Present", this);
        }
    }

================================================================

Nov 16, 2011

How to Send value return from child form/page to parent form/page via window.open() in java script

------------------------------------------In Default4.aspx------------------------------------------------

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="YourTextBox" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="open" OnClientClick="openPopup();" /></div>
    </form>
</body>


<script type="text/javascript">
<!--
function openPopup()
{
 var elementId = '<%= YourTextBox.ClientID %>';
 var windowUrl = 'PopupPage.aspx?ElementId=' + elementId;
 var windowId = 'NewWindow_' + new Date().getTime();
 var windowFeatures =
  'channelmode=no,directories=no,fullscreen=no,' +
  'location=no,dependent=yes,menubar=no,resizable=no,scrollbars=yes,' +
  'status=no,toolbar=no,titlebar=no,' +
  'left=0,top=0,width=400px,height=200px';
 var windowReference = window.open(windowUrl, windowId, windowFeatures);
 windowReference.focus();

}
// -->
</script>
</html>
------------------------------------------------------------------------------------------------


------------------------------------------PopupPage.aspx----------------------------------
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" OnClientClick="closeWindow();" Text="Close" /></div>
    </form>
</body>



<script type="text/javascript">
<!--
function closeWindow()
{
 // C#
  window.opener.document.getElementById('<%= Request["ElementId"] %>').value = 'Some new value';


 window.opener.focus();
 window.close();
}
// -->
</script>
</html>
-------------------------------------------------------------------------------------------------

Oct 29, 2011

Sql Function for padding text to field output


create function ULPAD(@vInput varchar(max), @iLenght smallint,@cPadChar char(1))
   returns varchar(max)
as
begin
   if @vInput is not null
   begin
      if LEN(@vInput) <= @iLenght
      begin
         set @vInput = RIGHT (REPLICATE(@cPadChar, @iLenght)+ CAST (@vInput AS varchar), @iLenght)
      end
   end
   return @vInput
end

Ex:
SELECT @NewEmpNo =dbo.ULPAD((Select com_empsrno +1  from Mcompany  where com_code=@Emp_Org_srno) , 5,'0')             

Oct 20, 2011

Add Dynamicaly Row in Grid view





'Designer page------------------------------------------------------------


<asp:GridView id="GridQuote" runat="server" DataKeyNames="Quote_srno" ShowHeader="False" GridLines="None" AutoGenerateColumns="False" CellPadding="0" __designer:wfdid="w31"><Columns>
<asp:TemplateField HeaderText="quotes"><ItemTemplate>
<TABLE style="WIDTH: 428px"><TBODY><TR><TD vAlign=top align=right><asp:Label id="Label1" runat="server" Text="Quote :" __designer:wfdid="w38"></asp:Label></TD><TD><uc1:cgTextbox id="txtQuote" runat="server" Height="150" MaxLength="1000" Width="325" TextMode="MultiLine" Text='<%# Eval("Quote") %>' Required="true" __designer:wfdid="w39"></uc1:cgTextbox></TD><TD vAlign=top>&nbsp;<asp:ImageButton id="btnRemQuote" onclick="btnRemQuote_Click" runat="server" ImageUrl="~/App_Themes/images/btnRemove.jpg" CausesValidation="False" __designer:wfdid="w40">
                                                                        </asp:ImageButton>&nbsp;</TD></TR><TR><TD align=right><asp:Label id="Label2" runat="server" Text="Quote By :" Width="65px" __designer:wfdid="w41"></asp:Label></TD><TD><asp:TextBox id="txtQuoteBy" runat="server" Text='<%# Eval("QuoteBy") %>' MaxLength="50" Width="98%" __designer:wfdid="w42"></asp:TextBox></TD><TD></TD></TR><TR><TD align=right><asp:Label id="Label3" runat="server" Text="Posted By :" Width="71px" __designer:wfdid="w43"></asp:Label></TD><TD><uc2:cgSearchEmp id="CgSearchEmp1" runat="server" UserId='<%#Eval("PostUserId") %>' EmpName='<%# Eval("PostUserNm") %>' EmpNo='<%# Eval("PostEmpNo") %>' __designer:wfdid="w44"></uc2:cgSearchEmp> </TD><TD align=right>&nbsp;<asp:ImageButton id="btnAddMoreQuote" onclick="btnAddMoreQuote_Click" runat="server" ImageUrl="~/App_Themes/images/btnAdd.jpg" Visible="False" CausesValidation="False" __designer:wfdid="w45"></asp:ImageButton>&nbsp;</TD></TR></TBODY></TABLE>
</ItemTemplate>
</asp:TemplateField>
</Columns>

<AlternatingRowStyle BackColor="WhiteSmoke"></AlternatingRowStyle>
</asp:GridView>



 'Code Behind..........................................
'On Load page--------------------------------------------------------
 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then

                If IsNothing(ViewState("Quote")) Then
                    MakeTableQuote()
                    btnAddMoreQuote_Click(sender, TryCast(e, System.Web.UI.ImageClickEventArgs))
                End If

  End If

End Sub

 Protected Sub MakeTableQuote()
        Dim dt As New DataTable
        Dim dc As DataColumn
        dc = New DataColumn("Quote_srno", System.Type.GetType("System.Int32"))
        dt.Columns.Add(dc)
        dc = New DataColumn("Quote", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)
        dc = New DataColumn("QuoteBy", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)
        dc = New DataColumn("PostUserId", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)

        dc = New DataColumn("PostUserNm", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)

        dc = New DataColumn("PostEmpNo", System.Type.GetType("System.String"))
        dt.Columns.Add(dc)

        ViewState("Quote") = dt
    End Sub


    Protected Sub btnAddMoreQuote_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
        Dim dt As DataTable = ViewState("Quote")
        Dim dr As DataRow
        For i As Integer = 0 To GridQuote.Rows.Count - 1

            dt.Rows(i).Item(1) = DirectCast(GridQuote.Rows(i).FindControl("txtQuote"), UserControl.TextBox).Text
            dt.Rows(i).Item(2) = DirectCast(GridQuote.Rows(i).FindControl("txtQuoteBy"), TextBox).Text
            dt.Rows(i).Item(3) = DirectCast(GridQuote.Rows(i).FindControl("CgSearchEmp1"), UserControl.cgSearchEmp).UserId
            dt.Rows(i).Item(4) = DirectCast(GridQuote.Rows(i).FindControl("CgSearchEmp1"), UserControl.cgSearchEmp).EmpName
            dt.Rows(i).Item(5) = DirectCast(GridQuote.Rows(i).FindControl("CgSearchEmp1"), UserControl.cgSearchEmp).EmpNo

        Next
        dr = dt.NewRow
        dr.Item(0) = 0
        dr.Item(1) = ""
        dt.Rows.Add(dr)
        ViewState("Quote") = dt
        bindGridQuote()
    End Sub





  


  Protected Sub bindGridQuote()
        Dim dt As DataTable = ViewState("Quote")
        GridQuote.DataSource = dt
        GridQuote.DataBind()

        If HiddenFieldMode.Value = "New" Or HiddenFieldMode.Value = "" Then
            GridQuote.Rows(GridQuote.Rows.Count - 1).FindControl("btnAddMoreQuote").Visible = True
            GridQuote.Rows(GridQuote.Rows.Count - 1).FindControl("btnRemQuote").Visible = False
        Else
            GridQuote.Rows(GridQuote.Rows.Count - 1).FindControl("btnAddMoreQuote").Visible = False
            GridQuote.Rows(GridQuote.Rows.Count - 1).FindControl("btnRemQuote").Visible = False
        End If
       
        'For i As Integer = 0 To GridQuote.Rows.Count - 2
        '    GridQuote.Rows(i).FindControl("btnAddMoreQuote").Visible = False
        'Next
    End Sub






  Protected Sub btnRemQuote_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
        Dim row As GridViewRow = TryCast(DirectCast(sender, ImageButton).Parent.Parent, GridViewRow)
        'lblMsg.Text = row.RowIndex

        Dim dt As DataTable = ViewState("Quote")
        Dim dr As DataRow
        For i As Integer = 0 To GridQuote.Rows.Count - 1

            dt.Rows(i).Item(1) = DirectCast(GridQuote.Rows(i).FindControl("txtQuote"), UserControl.TextBox).Text
            dt.Rows(i).Item(2) = DirectCast(GridQuote.Rows(i).FindControl("txtQuoteBy"), TextBox).Text
            dt.Rows(i).Item(3) = DirectCast(GridQuote.Rows(i).FindControl("CgSearchEmp1"), UserControl.cgSearchEmp).UserId
            dt.Rows(i).Item(4) = DirectCast(GridQuote.Rows(i).FindControl("CgSearchEmp1"), UserControl.cgSearchEmp).EmpName
            dt.Rows(i).Item(5) = DirectCast(GridQuote.Rows(i).FindControl("CgSearchEmp1"), UserControl.cgSearchEmp).EmpNo

        Next

        dt.Rows(row.RowIndex).Delete()
        ViewState("Quote") = dt
        bindGridQuote()
    End Sub

Oct 6, 2011

Split function for Sql Server

CREATE FUNCTION dbo.Split
(
@RowData nvarchar(2000),
@SplitOn nvarchar(5)
)
RETURNS @RtnValue table
(
Id int identity(1,1),
Data nvarchar(100)
)
AS
BEGIN
Declare @Cnt int
Set @Cnt = 1

While (Charindex(@SplitOn,@RowData)>0)
Begin
Insert Into @RtnValue (data)
Select
Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))

Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
Set @Cnt = @Cnt + 1
End

Insert Into @RtnValue (data)
Select Data = ltrim(rtrim(@RowData))

Return
END

Sep 28, 2011

How to Get and change style of all dropdown in Jquery

 <script type="text/javascript">

  $("select").focusin(function() {
   jQuery(this).closest("table").css("height","+35"); 
    });

 $("select").focusout(function() {
 jQuery(this).closest("table").css("height","auto");      
    });
   
</script>

Sep 25, 2011

How to add hyperlink in Grid View with DataBinder.Eval()


 <asp:datagrid id="Datagrid3" runat="server" AutoGenerateColumns="False" BorderColor="black" 
       HeaderStyle-CssClass="tableHeader" ItemStyle-CssClass= "tableItem">
        <Columns>
                  <asp:TemplateColumn HeaderText="Order">
                      <ItemTemplate>
                         <asp:Hyperlink runat= "server" Text='<%# DataBinder.Eval(Container.DataItem,"ProductName").tostring%>' 
                          NavigateUrl='<%# "page.aspx?Name=" & DataBinder.Eval (Container.DataItem,"ProductName").tostring & _  
                          "&ProductID=" & DataBinder.Eval(Container.DataItem,"ProductID").tostring %>' ID="ProductName"/>  
  
                       </ItemTemplate>
                     </asp:TemplateColumn>                                    
         </Columns>
</asp:datagrid>

Sep 20, 2011

Up and Down List Box Item Java Script In ASP.NET

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>

</head>
<body>
    <form id="form1" runat="server">
    <input type="button" value="Up"onclick="moveUp(this.form['_lb2']);" />
    <asp:ListBox ID="_lb2" name="_lb2" runat="server" Height="100px" Width="170px">
        <asp:ListItem>Data1</asp:ListItem>
        <asp:ListItem>Data2</asp:ListItem>
        <asp:ListItem>Data3</asp:ListItem>
        <asp:ListItem>Data4</asp:ListItem>
    </asp:ListBox>
  <input type="button" value="Down"onclick="moveDown(this.form['_lb2']);" />
    <div>
        <br />
        </div>
    </form>
</body>


<script type="text/javascript">

function moveUp(sel)
{
  var idx = sel.selectedIndex;
  var opt;

  // Only move up if not first
  if (idx > 0)
  {
    opt = sel.options[idx];
    sel.insertBefore(opt, sel.options[--idx]);
  }
}

function moveDown(sel)
{
  var idx = sel.selectedIndex;
  var opt;

  // Only move up if not first
  
  if (idx < sel.length-1)
  {
    opt = sel.options[idx];  
    sel.insertBefore(sel.options[++idx],opt);
  }
}

</script>
</html>

How to use XML To Save the data in Store Procedure in MS SQL 2005/2008


DECLARE @XMLDOC VARCHAR(MAX)
DECLARE @xml_hndl INT



SET @XMLDOC='<?xml version="1.0" encoding="ISO-8859-1"?>

<SBU><row><SBU_code>QQQ</SBU_code><SbuOrder></SbuOrder></row><row><SBU_code>WW</SBU_code><SbuOrder></SbuOrder></row><row><SBU_code>zz</SBU_code><SbuOrder></SbuOrder></row><row><SBU_code>PS</SBU_code><SbuOrder>1</SbuOrder></row><row><SBU_code>IS</SBU_code><SbuOrder>2</SbuOrder></row><row><SBU_code>CP</SBU_code><SbuOrder>3</SbuOrder></row><row><SBU_code>DG</SBU_code><SbuOrder>4</SbuOrder></row><row><SBU_code>RG</SBU_code><SbuOrder>5</SbuOrder></row><row><SBU_code>CT</SBU_code><SbuOrder>6</SbuOrder></row><row><SBU_code>test</SBU_code><SbuOrder>7</SbuOrder></row><row><SBU_code>CC</SBU_code><SbuOrder>8</SbuOrder></row><row><SBU_code>PW</SBU_code><SbuOrder>9</SbuOrder></row><row><SBU_code>RR</SBU_code><SbuOrder>10</SbuOrder></row></SBU>'



EXEC Sp_xml_preparedocument  @xml_hndl OUTPUT,  @XMLDOC


--Below Read the whole data and Insert it into table --


SELECT * FROM   OPENXML(@xml_hndl, '/SBU/row', 1)
          
WITH ( sbu_code VARCHAR(MAX) 'SBU_code',
                 
sbuorder VARCHAR(MAX) 'SbuOrder' )


--Remove document ----
EXEC sp_xml_removedocument @xml_hndl                  

Sep 16, 2011

Here's a link to an article about some free .NET profilers, and paid ones too ,which help You to increase performance

Profiling is an important part of your software development process and allows you to determine improvements in your applications. In simple words, it is tuning your application to increase its performance. Here are some free and paid .NET profilers to do the job for you
Free
EQATEC v3.0 – An easy to use code profiler to spot your app's slow code. Profiles only methods as of this writing. You can use it freely for non-commercial use. Check the pricing page for the free license
CLR Profiler for .NET Framework – Free memory allocation profiler which works for .NET 2.0 and 3.5 as well
slimTune - Free profiler and performance analysis/tuning tool for .NET based applications
Commercial
Visual Studio Team System Profiler – Ships with Visual Studio Team System (Developer and Suite) for finding performance issues in your native, managed or ASP.NET applications
ANTS Profiler v5.1 – Highly recommended profiler to identify performance bottlenecks and optimize performance
dotTrace 3.1 – Performance and memory profiler for .NET
MemProfiler 3.5 - powerful tool for finding memory leaks and optimizing the memory usage in programs written in C#, VB.NET or any other .NET Language
AQTime 6 - performance profiling and memory and resource debugging toolset for .NET applications

Sep 9, 2011

How to validate validation in cliient side in java script

function chkValidation(nextTab)
{
if (tab.name=='EmployeeDetails')
{
var btnSave = document.getElementById("<%=btnSave.clientID%>");
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions('ctl00$ContentPlaceHolder1$btnSave', '', true, '', '', false, false));
if (Page_ClientValidate()==false)
return false;
}
else
{
tab.name = nextTab;
}
}

How to check user validation in java script


{

WebForm_DoPostBackWithOptions(


}
if (tab.name=='EmployeeDetails') var btnSave = document.getElementById("<%=btnSave.clientID%>"); new WebForm_PostBackOptions('ctl00$ContentPlaceHolder1$btnSave', '', true, '', '', false, false));if (Page_ClientValidate()==false)return false;

Sep 5, 2011

Export in DevexGrid

Visit the following link...

http://demos.devexpress.com/aspxgridviewdemos/Exporting/ExportSelected.aspx

How to use filter expression to return an array of DataRow objects.

Private Sub GetRowsByFilter()

    Dim table As DataTable = DataSet1.Tables("Orders")

    ' Presuming the DataTable has a column named Date.
    Dim expression As String
    expression = "Date > #1/1/00#"
    Dim foundRows() As DataRow

    ' Use the Select method to find all rows matching the filter.
    foundRows = table.Select(expression)

    Dim i As Integer
    ' Print column 0 of each returned row.
    For i = 0 to foundRows.GetUpperBound(0)
       Console.WriteLine(foundRows(i)(0))
    Next i
End Sub
 
 
--------------------------------- OR ----------------------------------------
 
Protected Sub DDLCompany_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim ds As New DataSet
        ds = ViewState("ViewDDLMaster")

        ' Filter Division as per Company

        Dim tempDView As DataView
        tempDView = ds.Tables(1).DefaultView
        tempDView.RowFilter = "div_company ='" + DDLCompany.SelectedValue.Trim + "'"

        'GridView1.DataSource = tempDView.ToTable()
        'GridView1.DataBind()
        DDLDivision.DataSource = tempDView.Table
        DDLDivision.DataTextField = "div_desc"
        DDLDivision.DataValueField = "div_code"
        DDLDivision.DataBind()
        DDLDivision.Items.Insert(0, "Select")

    End Sub

Aug 26, 2011

Create proerties and Declare variable through MsSql Store Procedure , thanks to PC PATEL

-- =============================================                   
-- Author:  PC PATEL                   
-- Create date: 5-Aug-2011                   
-- Description: Used when updating routes                   
-- =============================================                   
CREATE PROCEDURE Usp_makepropertiesvb @TableName VARCHAR(max) 
AS 
  BEGIN 
      DECLARE @Temp VARCHAR(max) 
      DECLARE @Temp1 VARCHAR(max) 
       
      DECLARE @Variables varchar(max) 
      set @Variables = '' 
      DECLARE @Properties varchar(max) 
      set @Properties = '' 
       
      DECLARE CUR1 CURSOR forward_only FOR 
        SELECT i_s.COLUMN_NAME, 
               CASE i_s.DATA_TYPE 
                 WHEN 'smallint' THEN 'Integer' 
                 WHEN 'int' THEN 'Integer' 
                 WHEN 'varchar' THEN 'String' 
                 WHEN 'char' THEN 'String' 
                 WHEN 'datetime' THEN 'Date' 
               END AS DATA_TYPE 
        FROM   INFORMATION_SCHEMA.COLUMNS AS i_s 
               LEFT OUTER JOIN sys.extended_properties AS s 
                 ON s.major_id = Object_id(i_s.TABLE_SCHEMA + '.' + i_s.TABLE_NAME) 
                    AND s.minor_id = i_s.ORDINAL_POSITION 
                    AND s.name = 'MS_Description' 
        WHERE  ( Objectproperty(Object_id(i_s.TABLE_SCHEMA + '.' + i_s.TABLE_NAME), 'IsMsShipped') = 0 ) 
               AND ( i_s.TABLE_NAME = @TableName ) 
        ORDER  BY i_s.ORDINAL_POSITION 
        FOR READ ONLY 
 
      OPEN CUR1 
 
      FETCH NEXT FROM CUR1 INTO @Temp, @Temp1 
 
      WHILE @@FETCH_STATUS = 0 
        BEGIN 
            SET @Variables += 'Private _' + @Temp + ' As ' + @Temp1 + CHAR(10) 
 
            set @Properties += 'Public Property ' + @Temp + '() As ' + @Temp1 + CHAR(10) 
 
            set @Properties += 'Get' + CHAR(10) 
 
            set @Properties += 'Return _' + @Temp + CHAR(10) 
 
            set @Properties += 'End Get' + CHAR(10) 
 
            set @Properties += 'Set(ByVal value As ' + @Temp1 + ')' + CHAR(10) 
 
            set @Properties += '_' + @Temp + ' = value' + CHAR(10) 
 
            set @Properties += 'End Set' + CHAR(10) 
 
            set @Properties += 'End Property' + CHAR(10) 
 
            FETCH NEXT FROM CUR1 INTO @Temp, @Temp1 
        END 
 
      CLOSE CUR1 
 
      DEALLOCATE CUR1 
       
      print '#Region " Variables "' 
      print @Variables 
      print '#End Region' 
      print '#Region " Properties "' 
      print @Properties 
      print '#End Region' 
  END  

Aug 25, 2011

How to select table column name and datatype in Ms Sql

 SELECT i_s.table_name
       AS
       [Table Name],
       i_s.column_name
       AS [Column Name],
       i_s.data_type
       AS [Data Type],
       Isnull(Isnull(i_s.character_maximum_length, i_s.numeric_precision), '')
       AS
       [Max Length],
       Isnull(s.VALUE, '')
       AS DESCRIPTION
FROM   information_schema.columns AS i_s
       LEFT OUTER JOIN sys.extended_properties AS s
         ON s.major_id = Object_id(i_s.table_schema + '.' + i_s.table_name)
            AND s.minor_id = i_s.ordinal_position
            AND s.name = 'MS_Description'
WHERE  ( Objectproperty(Object_id(i_s.table_schema + '.' + i_s.table_name),
                'IsMsShipped'
         ) = 0 )
       AND ( i_s.table_name = 'v_QTW_EMPProfile' )
ORDER  BY [Table Name],
          i_s.ordinal_position
 

Aug 10, 2011

How to Get Treeview selected node in javascript

To start with I have added a simple ASP.Net TreeView and a button on my ASPX Page


<div>
    <asp:TreeView ID="TreeView1" runat="server">
        <SelectedNodeStyle ForeColor="Black" />
    </asp:TreeView>
</div>
<asp:Button ID="Button1" runat="server" Text="GetSelectedNode" OnClientClick="return GetSelectedNode();" />



Now here’s the script that will get the reference of the TreeView selected node and also extract its Text and Value part.


<script type="text/javascript">
function GetSelectedNode() {
    var treeViewData = window["<%=TreeView1.ClientID%>" + "_Data"];
    if (treeViewData.selectedNodeID.value != "") {
        var selectedNode = document.getElementById(treeViewData.selectedNodeID.value);
        var value = selectedNode.href.substring(selectedNode.href.indexOf(",") + 3, selectedNode.href.length - 2);
        var text = selectedNode.innerHTML;
        alert("Text: " + text + "\r\n" + "Value: " + value);
    } else {
        alert("No node selected.")
    }
    return false;
}
</script


On Page Load In Vb.net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Try    
If Not IsPostBack Then                                                  MakeTree1()
      tvMenu.CollapseAll()    End If
Catch ex As ExceptionEnd Try
  lblMsg.ForeColor = Drawing.Color.Red
  lblMsg.Text = "Error on page."


 
End Sub

Aug 9, 2011

Simple Cursor in Sql Sqerver/ How to use cursor in MS Sql Server

ALTER PROCEDURE Usp_removrights @userList   VARCHAR(MAX),
                                @menu       SMALLINT,
                                @submenu    SMALLINT,
                                @subsubmenu SMALLINT
AS
  DECLARE @count INT

  SET @count=0

  DECLARE @user_no VARCHAR(MAX)
  DECLARE @user_id VARCHAR(MAX)

  BEGIN TRY
      --Find out the cursors that are opened and not close
      SELECT @count = COUNT(*)
      FROM   sys.Dm_exec_cursors(0)
      WHERE  is_open = 1
             AND name = 'cur_RemovRight'

      IF ( @count > 0 )
        BEGIN
            CLOSE cur_removright;

            DEALLOCATE cur_removright;
        END

      DECLARE cur_removright CURSOR FOR
        SELECT VALUE
        FROM
dbo.Split('00011 ,00261 , 01014 , 01019 ,  01022 ,  80011 ,  80012 ,  80013 ,  80014 ', ',')

    OPEN cur_removright

    FETCH NEXT FROM cur_removright INTO @user_no;

    WHILE @@FETCH_STATUS = 0
      BEGIN
          SELECT @user_id = muser_userid
          FROM   infoview
          WHERE  muser_empno = @user_no

          INSERT INTO userlevelrights1
                      (userid,
                       menu,
                       submenu,
                       subsubmenu)
          VALUES     (@user_id,
                      @menu,
                      NULL,
                      NULL)

          PRINT @user_id

          --Delete from userlevelrights1 where userid=@user_id
          FETCH NEXT FROM cur_removright INTO @user_no;
      END

    CLOSE cur_removright;

    DEALLOCATE cur_removright;
END TRY

  BEGIN CATCH
      INSERT INTO errorlog_sp
      SELECT Error_number()    AS errornumber,
             Error_severity()  AS errorseverity,
             Error_state()     AS errorstate,
             Error_procedure() AS errorprocedure,
             Error_line()      AS errorline,
             Error_message()   AS errormessage,
             Getdate()

      RAISERROR ('Error catch',
                 10,
                 1)
  END CATCH 

What is the use of n-tier architecture and 3-tier architecture?

how to implement 3-tier architecture in asp.net using c#. 3-Tier architecture is also called layered architecture. Some people called it ...