Wednesday, 30 May 2012

Find Table Column name and Datatype

SELECT column_name 'Column Name',
data_type 'Data Type',
CHARacter_maximum_length 'Maximum Length'
FROM information_schema.columns
WHERE table_name = 'tbl_table'

Open a Pop up window


<script language="javascript" type="text/javascript">

function popitup(url) {
newwindow=window.open(url,'name','height=200,width=150');
if (window.focus) {newwindow.focus()}
return false;
}


</script>

Tuesday, 29 May 2012

Get Files From a Folder C#


DirectoryInfo dirInfo = new DirectoryInfo("D:/Hema/Projects/Excel");
foreach (FileInfo f in dirInfo.GetFiles("*.xls"))
{
MessageBox.Show(f.Name);

}

Write Log File C#


// Create a writer and open the file:
            StreamWriter log;

            if (!File.Exists("logfile.txt"))
            {
                log = new StreamWriter("logfile.txt");
            }
            else
            {
                log = File.AppendText("logfile.txt");
            }

            // Write to the file:
            log.WriteLine(DateTime.Now);
            log.WriteLine(strLogText);
            log.WriteLine();

            // Close the stream:
            log.Close();

Begin and Commit Transaction


Create Proc TranTest
AS
BEGIN TRAN

INSERT INTO [authors]([au_id],
      [au_lname],
      [au_fname],
      [phone],
      [contract])
VALUES      ('172-32-1176',
      'Gates',
      'Bill',
      '800-BUY-MSFT',
      1)

IF @@ERROR <> 0
   BEGIN
      ROLLBACK TRAN
      return 10
   END

UPDATE      authors
SET   au_fname = 'Johnzzz'
WHERE au_id = '172-32-1176'

IF @@ERROR <> 0
   BEGIN
      ROLLBACK TRAN
      return 11
   END

COMMIT TRAN
GO

You'll notice that we check each statement for failure. If the statement failed (i.e. @@ERROR <> 0) then we rollback the work performed so far and use the RETURN statement to exit the stored procedure. It's very important to note that if we don't check for errors after each statement we may commit a transaction improperly.
http://www.sqlteam.com/article/introduction-to-transactions

Sharing Tab Missing

go to Tools->Folder Options and in the View tab check (enable) "Use simple file sharing"

Monday, 28 May 2012

use of @ symbol in c#


The @ symbol serves 2 purposes in C#:
The first is that it allows you to use a reserved keyowrd as a variable like this:
int @int = 15;
The second option lets you specify a string without having to excape any characters. For instance the '\' character is an escape character so typically you would need to do this:
var myString = "c:\\myfolder\\myfile.txt"
alternatively you can do this:
var myString = @"c:\myFolder\myfile.txt"

Multiple select statement for sqldataadapter

    SqlDataAdapter adapter = new SqlDataAdapter(
      "SELECT * FROM Customers; SELECT * FROM Orders", connection);
            adapter.TableMappings.Add("Table", " Customers ");
            adapter.TableMappings.Add("Table1", " Orders ");

            adapter.Fill(ds);
        }

Export excel without installing Excel 2007 in server

The following url used to create a excel file in specified location.
http://www.mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm

After storing the excel file in server, it should be transmitted to local.

if (CreateExcelFileOriginal.CreateExcelDocument(dt, location))
  {
       HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", attachment;filename=" + "sample.xlsx");
       HttpContext.Current.Response.ContentType = "application/spl.xlsx";
       HttpContext.Current.Response.Charset = "";
       HttpContext.Current.Response.TransmitFile(location);
       HttpContext.Current.Response.Flush();
       HttpContext.Current.Response.End();
   }

Response.TransmitFile() to explicitly send the file from your ASP.NET application and then add the Content Type and Content-Disposition headers.

PATINDEX And CHARINDEX


PATINDEX
Returns the starting position of the first occurrence of a pattern in a specified expression, or zeros if the pattern is not found, on all valid text and character data types.


Syntax:
PATINDEX ( '%pattern%', expression )
Eg: PATINDEX('%[0-9]%'@string)



PATINDEX for complex search
The following search will find all bikes which off-road yet comfortable. 
Select  ProductNumber ,[Description] from ProductDescription pd
where patindex( ‘%off-road%comfortable%’, pd.[Description]) > 0
ProductNumber
Description

BK-M18S-12
Suitable for any type of riding, on or off-road. Fits any budget. Smooth-shifting with a comfortable ride.

BK-M18S-21
Suitable for any type of riding, on or off-road. Fits any budget. Smooth-shifting with a comfortable ride.

CHARINDEX
Searches an expression for another expression and returns its starting position if found.
SYNTAX:
CHARINDEX ( expressionToFind ,expressionToSearch [ , start_location ] )
Eg:CHARINDEX(' ',@String)
start_location
        It is optional.
If start_location is not specified, is a negative number, or is 0, the search starts at the beginning of expressionToSearch.

Thursday, 24 May 2012

Find Page Control in Custom Gridview

 SqlDataSource d = this.Parent.FindControl("SqlDataSource1") as SqlDataSource;

Tuesday, 22 May 2012

Get DataTable From Gridview


bool firstTime = true;
    System.Data.DataTable dt;
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
            if (this.firstTime)
            {
                System.Data.DataView dv =
                     (e.Row.DataItem as System.Data.DataRowView).DataView;
                this.dt = dv.ToTable();               
                this.firstTime = false;
            }
    }

Add ListItemCollection Property To Custom Gridview

   private ListItemCollection m_Items=null;

   [DesignerSerializationVisibility(DesignerSerializationVisibility.Content),  
    NotifyParentProperty(true), 
    PersistenceMode(PersistenceMode.InnerProperty)
     ] 
        public virtual ListItemCollection Items
        {
            get
            {
                if (this.m_Items == null)
                {
                    this.m_Items = new ListItemCollection ();
                   
                }
                 return this.m_Items;
            }
        }

Saturday, 12 May 2012

Embedded StyleSheet File with Custom Control


How to embedded StyleSheet file with custom control? Question has been opened many time on ASP.NET forum.
So in this article, I will try to demonstrate how to achieve this task.
In General
In general, if you want to embedded any thing with custom control, you need first to make its "Build Action" property to be "Embedded Resource", and then you need to add to the custom control assemblies using the <Assembly> attribute typically above class name, and finally you need to register in the page so it can be rendered.
I will illustrate all these things in details through the article.

Step One: make it as Embedded Resource
 After you added the StyleSheet file to your Custom Control Class Library project, first thing you need to do is to make build action property for the stylesheet file as embedded resource, otherwise your page will not be able to see the stylesheet file.
To do this, from the VS do a right click on the stylesheet file, and click on Properties,  and then change the "Build Action" property to be "Embedded Resource".

Step Two: Add it to the Custom Controls Assemblies
 Second thing you need to do is to register the Css file to the custom control assemblies by adding the below code typically above class name

[assembly: WebResource("YourProjectName.StyleSheetFileName.css""text/css")]
namespace YourNameSpace
{
   public class MyCustomControl : CompositeControl
    {
       //Custom Control Rest Code

 Step Three: Register Css File on the Page
Finally, we have to tell the Page that our custom control has Css file needed to be registered when the final HTML is generated for that page. So we need to write a bit of code in the OnInit method.

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
   
    string css = "<link href=\"" + Page.ClientScript.GetWebResourceUrl(this.GetType(),
    "YourProjectName.CssFileName.css") + "\" type=\"text/css\" rel=\"stylesheet\" />";
   
               
    Page.ClientScript.RegisterClientScriptBlock(this.GetType, "cssFile", css, false);
}

And that's it, you can now use the CSS StyleSheet file within your Custom Control.

Wednesday, 2 May 2012

See Text Of Stored Proceure -sp_helptext

 sp_HelpText is used  to see the text of the stored procedure


 sp_helptext StoredProcedurename

 Eg.
 sp_helptext sp_helptext

watermark for Password Text box css and javascript


<style type="text/css">
        .WaterMarkedTextBox
        {
            height: 16px;
            width: 168px;
            padding: 2px 2 2 2px;
            border: 1px solid #BEBEBE;
            background-color: #F0F8FF;
            color: gray;
            font-size: 8pt;
            text-align: center;
        }
        .WaterMarkedTextBoxPSW
        {
            background-position: center;
            height: 16px;
            width: 168px;
            padding: 2px 2 2 2px;
            border: 1px solid #BEBEBE;
            background-color: #F0F8FF;
            color: white;
            vertical-align: middle;
            text-align: right;
            background-image: url(Images/psw_wMark.png);
            background-repeat: no-repeat;
        }
        .NormalTextBox
        {
            height: 16px;
            width: 168px;
        }
    </style>



 <script language="javascript" type="text/javascript">
         function Focus(objname, waterMarkText) {
             obj = document.getElementById(objname);
             if (obj.value == waterMarkText) {
                 obj.value = "";
                 obj.className = "NormalTextBox";
                 if (obj.value == "User ID" || obj.value == "" || obj.value == null) {
                     obj.style.color = "black";
                 }
             }
         }
         function Blur(objname, waterMarkText) {
             obj = document.getElementById(objname);
             if (obj.value == "") {
                 obj.value = waterMarkText;
                 if (objname != "txtPwd") {
                     obj.className = "WaterMarkedTextBox";
                 }
                 else {
                     obj.className = "WaterMarkedTextBoxPSW";
                 }
             }
             else {
                 obj.className = "NormalTextBox";
             }

             if (obj.value == "User ID" || obj.value == "" || obj.value == null) {
                 obj.style.color = "gray";
             }
         }
    </script>


<body>
    <form id="form2" runat="server">
    <div>
        <h3>
            Watermark Textbox using JavaScript and CSS</h3>
    </div>
    <table>
        <tr>
            <td>
                User Id
            </td>
            <td>
                <asp:TextBox ID="txtUserId" runat="server"
              onfocus="Focus(this.id,'User ID')"
                    onblur="Blur(this.id,'User ID')"
                  Width="126px" CssClass="WaterMarkedTextBox">User ID</asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                Password
            </td>
            <td>
                <asp:TextBox ID="txtPwd" TextMode="Password"
              runat="server" onfocus="Focus(this.id,'')"
                    onblur="Blur(this.id,'')" Width="126px"
                     CssClass="WaterMarkedTextBoxPSW" />
            </td>
        </tr>
        <tr>
            <td>
            </td>
            <td>
                <asp:Button ID="Button1" runat="server" Text="Submit" />
            </td>
        </tr>
    </table>
    </form>
</body>

 Image