Ayo Softech

ASP

POPULAR LINK FOR ASP.NET
1.http://csharp.net-informations.com/
2.http://www.codeproject.com/Articles/13678/The-DataGridViewPrinter-- for class
3.http://developers.facebook.com/docs/reference/plugins/login/--for Login Facebook
4.http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=8195&lngWId=10 --Product Mngt
5.http://myqol.com/Video_Sub_Categories_No_Edit.aspx?SubCategory=35&SubCategoryName=Visual%20Basic.NET
6.http://weblogs.asp.net/scottgu/archive/2007/08/10/the-asp-listview-control-part-1-building-a-product-listing-page-with-clean-css-ui.aspx-- list Product
7.http://msdn.microsoft.com/en-us/magazine/cc188767.aspx--for print
8.http://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/standard/imagemap.aspx --at a time run Program Example
9.For AZEX control

Example: date report
--------------------------
DateTime startDate = new DateTime(2005, 2, 1, 3, 4, 12, 56);
// End date
DateTime endDate = new DateTime(2005, 12, 12, 4, 30, 45, 12);
// Time span
TimeSpan diffDate = endDate.Subtract ( startDate );
// Spit it out
Console.WriteLine( "Time Difference: ");
Console.WriteLine(diffDate.Days.ToString() + " Days");
Console.WriteLine(diffDate.Hours.ToString() + " Hours" );
Console.WriteLine(diffDate.Minutes.ToString() + " Minutes");
Console.WriteLine(diffDate.Seconds.ToString() + " Seconds ");
Console.WriteLine(diffDate.Milliseconds.ToString() + " Milliseconds ");


1.Building ASP.NET Ajax Custom Controls
2.How to call method of master to other page in asp.net
3.Collapsible Panel UserControl using JavaScript
 
Building ASP.NET Ajax Custom Controls
In this article I will take you through the creation of ASP.NET Ajax Custom Client Controls. ASP.NET allows you to create your own AJAX client controls which can be any one of the following.
1. Background client functionality (No UI impact. An ideal example would be a ASP.NET AJAX timer control)
2. Custom Client Controls (Displayed on the UI. Like a custom TextBox)
3. Custom Extenders (Extenders for the existing AJAX controls)
This article will include the steps involved in creating an AJAX custom client control entirely through client javascript and the steps involved in using it on the client web page.
For demonstration purposes I will create a TextBox client control, which will change its style during focus and on blur.

Creating an Ajax Custom Client Control

To create a custom client control you can make use of the existing AJAX methods like get_element(), etc, since all the AJAX libraries will be loaded onto the web page at runtime. There are several steps involved in creating an AJAX Custom Client Control. Below is the summary of it.
1. Register a namespace.
1.  Type.registerNamespace("CustomClientControlDemo");
2. Define a class and initialize it.
1.  //Define a class
2.  CustomClientControlDemo.CustomAjaxTextBox = function (element) {
3.      CustomClientControlDemo.CustomAjaxTextBox.InitializeBase(this, [element]);
4.  }
3. Define the prototype for the class.
4. Bind the required event handlers for the client events.
5. Register the class, which derives from Sys.UI.Control as shown below.
1.  //Register the class deriving from Sys.UI.Control
2.  CustomClientControlDemo.CustomAjaxTextBox.registerClass('CustomClientControlDemo.CustomAjaxTextBox', Sys.UI.Control);
Now create an empty ASP.NET web application and add a script file named CustomAjaxTextBox.js. Here is the complete javascript control class for the demo application.


1.  //Register a namespace
2.  Type.registerNamespace("CustomClientControlDemo");
3.   
4.  //Define a class
5.  CustomClientControlDemo.CustomAjaxTextBox = function (element) {
6.      CustomClientControlDemo.CustomAjaxTextBox.initializeBase(this, [element]);
7.   
8.      //Initialize the private properties
9.      this._focusClass = null;
10.    this._blurClass = null;
11.}
12. 
13.//Define the prototype including properties and event handlers
14.CustomClientControlDemo.CustomAjaxTextBox.prototype = {
15. 
16.    //Define the get and set accessors for the properties.
17.    get_FocusClass: function () {
18.        return this._focusClass;
19.    },
20.    set_FocusClass: function (value) {
21.        this._focusClass = value;
22.    },
23.    get_BlurClass: function () {
24.        return this._blurClass;
25.    },
26.    set_BlurClass: function (value) {
27.        this._blurClass = value;
28.    },
29. 
30.    initialize: function () {
31.        var ajaxElement = this.get_element();
32.        //Call the base initialize
33.        CustomClientControlDemo.CustomAjaxTextBox.callBaseMethod(this, 'initialize');
34. 
35.        //Create handlers
36.        this._onFocusHandler = Function.createDelegate(this, this.onFocus);
37.        this._onBlurHandler = Function.createDelegate(this, this.onBlur);
38. 
39.        //AddHandlers
40.        $addHandlers(ajaxElement, { 'focus': this.onFocus, 'blur': this.onBlur }, this);
41. 
42.        //Set a default style for the control
43.        ajaxElement.className = this._blurClass;
44.    },
45. 
46.    onFocus: function (eventArgs) {
47.        this.get_element().className = this._focusClass;
48.    },
49. 
50.    onBlur: function (eventArgs) {
51.        this.get_element().className = this._blurClass;
52.    },
53.    dispose: function () {
54.        //Have the resource clean up code go in here.
55.    }
56.}
57. 
58.//Register the class deriving from Sys.UI.Control
59.CustomClientControlDemo.CustomAjaxTextBox.registerClass('CustomClientControlDemo.CustomAjaxTextBox', Sys.UI.Control);
60. 
61.if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

Using the AJAX Client Control on a Web Page

As we have created the client control’s code, in this section we will see about using it on a web page. Below are the high level steps in achieving it.
1. Add a web page to the sample web application that we created.
2. Add a ScriptManager control onto the webpage and add a ScriptReference to the CustomAjaxTextBox.js file.
3. Add an HTML text box to the form.
4. Use the $create script command to create the CustomTextBox control along with passing the required information like the setting the property values, etc., in the Sys.Application.add_init event handler.
Below is the web page code.


1.  <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AJAXClientControlDemo.aspx.cs"
2.      Inherits="WebApplication1.AJAXClientControlDemo" %>
3.   
4.  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
5.  <html xmlns="http://www.w3.org/1999/xhtml">
6.  <head runat="server">
7.      <style type="text/css">
8.          .Focus
9.          {
10.            background-color: Green;
11.            color: White;
12.        }
13.        .Blur
14.        {
15.            background-color: Black;
16.            color: White;
17.        }
18.    </style>
19.</head>
20.<body>
21.    <form id="form1" runat="server">
22.    <asp:ScriptManager ID="ScriptManager1" runat="server">
23.        <Scripts>
24.            <asp:ScriptReference Path="~/Scripts/CustomAjaxTextbox.js" />
25.        </Scripts>
26.    </asp:ScriptManager>
27.    <script type="text/javascript">
28.        Sys.Application.add_init(function (sender, args) {
29.            $create(CustomClientControlDemo.CustomAjaxTextBox, { FocusClass: 'Focus', BlurClass: 'Blur' }, null, null, $get('txtAjaxSample'));
30.        });
31.    </script>
32.    <div>
33.        <input type="text" id="txtAjaxSample" />
34.    </div>
35.    </form>
36.</body>
37.</html>
How to call method of master to other page in asp.net
DB.Advertisements.AddObject(obj);
        DB.SaveChanges();
        Clear();
        ((SiteMaster)this.Page.Master).bindListview();

Collapsible Panel UserControl using JavaScript

<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="HotPanel3.ascx.vb"
    Inherits="E_Component_Web3.HotPanel3" %><style type="text/css">
    .collapsePanel
    {
        width: 100%;
        overflow: hidden;
        padding-top: 10px;
        background-color: #F5F5F5;
        display:block;
    }
    

    .TitleBar
    {
        width: 100%;
        height: 20px;
        background-image: url('../images/bg-gray-menu.png');
        font-weight: bold;
        float: none;
        cursor: hand;
        vertical-align: middle;
    }
   

    .Image1
    {
        width: 16px;
        height: 16px;
        float: right;
        margin-right: 5px;
        margin-top: 2px;
    }
    .TitleLabel
    {
        float: left;
        font-weight: bold;
        margin-left: 5px;
    }
    .HotPanelDiv
    {
        margin: 5px;
        border: 1px solid #B0C4DE;
        float: left;
        width: 100%;
    }
    
</style>

<script type="text/javascript">


  function toggleMe(a) {
            var e = document.getElementById(a);
            if (!e) return true;
            if (e.style.display == "none") {
                e.style.display = "block"
            } else {
                e.style.display = "none"
            }
            return true;
        }
</script>

<div id="HotPanelDiv" runat="server" class="HotPanelDiv">
    <div id="TitleBar" class="TitleBar" onclick="toggleMe('DivContent')">
        <asp:Label ID="TitleLabel" runat="server" Text="Title Label" CssClass="TitleLabel"></asp:Label>
        <asp:Image ID="Image1" runat="server" CssClass="Image1" ImageUrl="../Images/expand.png" />
    </div>
    <div id="DivContent" class="collapsePanel">
        <asp:PlaceHolder ID="HotPanelPlaceHolder" runat="server"></asp:PlaceHolder>
    </div>
</div>
Structure of Join
GridList.DataSource =(from objdes in DB.DisciplinaryActionHdrtemps
             join emp in DB.Employees on objdes.EmpCode equals emp.Number
            join dept in DB.Departments on emp.DeptCode equals dept.Code
select new {dept.Descr,emp.Fname, objdes.Date,objdes.EmpCode,objdes.TcNo});

  File Upload 

 if (FileUpload2.HasFile)
        {


            if (_Attachment != null)
            {
                FileUpload2.SaveAs(Server.MapPath("Upload/") + FileUpload2.FileName);
                _Attachment.AttachmentFileName = FileUpload2.FileName;
            }
            else
            {
                _Attachment = new Attachment();
                FileUpload2.SaveAs(Server.MapPath("Upload/") + FileUpload2.FileName);
                _Attachment.AttachmentFileName = FileUpload2.FileName;
                _Attachment.AttachedObjID = ID;
                _Attachment.AttachmentType = AttachmentType;
                DB.Attachments.AddObject(_Attachment);
            }
            DB.SaveChanges();
            BindImage();
        }

 

Get Current Path of Specific File

 var fileName = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory,path); 

Validations

1.Only Numeric Number

 <cc1:FilteredTextBoxExtender ID="FilteredTextBoxExtender2" TargetControlID="txtticketentitled" FilterType="Custom, numbers"  runat="server" /> 

2.Not Null TextBox

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtcustomerID"
                    ErrorMessage="Required field." CssClass="Validation" ValidationGroup="Submit"></asp:RequiredFieldValidator> 

3.Confirm Passord

<asp:TextBox runat="server" ID="txtCpass" CssClass="text-form" ValidationGroup="Submit"
                                TextMode="Password" />
                            <asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="Password Not Match"
                                ValidationGroup="Submit" CssClass="Validation" ControlToCompare="txtPass" ControlToValidate="txtCpass"></asp:CompareValidator> 

4.Email

 <asp:TextBox ID="txtEmail" CssClass="text-form" runat="server" ValidationGroup="Submit"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtEmail"
                                ErrorMessage="Email Required" ValidationGroup="Submit" CssClass="Validation"></asp:RequiredFieldValidator>
                            <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ValidationGroup="Submit"
                                CssClass="Validation" ErrorMessage="Email not Valid" ControlToValidate="txtEmail"
                                ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
 

4.File Upload

 

 <asp:FileUpload ID="FileUpload1" runat="server" />
                                <asp:RequiredFieldValidator ID="rqfvInputFile" runat="server" ControlToValidate="FileUpload1" ErrorMessage="File is required"></asp:RequiredFieldValidator> 

 

5.Checkbox Validation

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script type = "text/javascript">
        function ValidateCheckBox(sender, args) {
            if (document.getElementById("<%=CheckBox1.ClientID %>").checked == true) {
                args.IsValid = true;
            } else {
                args.IsValid = false;
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:CheckBox ID="CheckBox1" runat="server" />
    <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Required" ClientValidationFunction = "ValidateCheckBox"></asp:CustomValidator><br />
    <asp:Button ID="Button1" runat="server" Text="Submit"/>
    </form>
</body>
</html>

 

6.Maximum character length Validation (Maximum 8 characters allowed)

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator Display = "Dynamic" ControlToValidate = "TextBox1" ID="RegularExpressionValidator1" ValidationExpression = "^[\s\S]{0,8}$" runat="server" ErrorMessage="Maximum 8 characters allowed."></asp:RegularExpressionValidator>
 
 
7.Minimum character length Validation (Minimum 8 characters required)
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator Display = "Dynamic" ControlToValidate = "TextBox2" ID="RegularExpressionValidator2" ValidationExpression = "^[\s\S]{8,}$" runat="server" ErrorMessage="Minimum 8 characters required."></asp:RegularExpressionValidator>
 
 
8.Minimum and Maximum character length Validation (Minimum 5 and Maximum 8 characters required)
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator Display = "Dynamic" ControlToValidate = "TextBox3" ID="RegularExpressionValidator3" ValidationExpression = "^[\s\S]{5,8}$" runat="server" ErrorMessage="Minimum 5 and Maximum 8 characters required."></asp:RegularExpressionValidator>

4.Date Filter (dd/MM/yyyy) 

STEP :1

<script type="text/javascript">
        function dateFormat(event, formfield) {
            var e = event || evt; // for trans-browser compatibility
            var val = formfield.value;
            var charCode = e.which || e.keyCode;

            if (charCode != 8 && (val.length == 2 || val.length == 5))
                formfield.value = formfield.value + '/';

            if ((charCode >= 48 && charCode <= 57) || charCode == 8 || charCode == 9 || (cCode < 96 || cCode > 105)) {

                return true;
            }
            return false;
        }
    </script>

STEP :2

<asp:TextBox ID="txtDOB" CssClass="inp-form" runat="server" MaxLength="10" onkeydown="return dateFormat(event, this);"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="RequiredFieldValidator9" runat="server" ControlToValidate="txtDOB"
                                                ErrorMessage="Required field." CssClass="Validation" ValidationGroup="Submit"></asp:RequiredFieldValidator>
                                                <cc1:filteredtextboxextender id="FilteredTextBoxExtender2" targetcontrolid="txtDOB" ValidChars="/"    filtertype="Custom, numbers" runat="server" />
 

Output: 22/11/1987 

 

Send Mail in Yahoo

 
protected void Button1_Click(object sender, EventArgs e)
    {
        SmtpClient client = new SmtpClient("smtp.mail.yahoo.com",587);

        MailMessage mail_msg = new MailMessage();

        MailAddress fromAdd = new MailAddress("yogeshkhandala22@yahoo.com");

        mail_msg.From = fromAdd;

        mail_msg.To.Add(new MailAddress("bulkemailt10@yahoo.com")); 

        mail_msg.Subject = "dfgdfhdfbdb";

        mail_msg.IsBodyHtml = true;

        mail_msg.Body = "Message From: Subject: Email: Content: ";

        System.Net.NetworkCredential basicCredential = new System.Net.NetworkCredential("yogeshkhandala22@yahoo.com", "p@ssw0rd");

        client.EnableSsl = false;

        client.UseDefaultCredentials = true;

        client.Credentials = basicCredential;

        client.Send(mail_msg);
    } 

 

PopUp in C#

<asp:Panel ID="PnlUser" runat="server" CssClass="modalPopup">
<table>
<tr>
<td>
<strong>Upload Image</strong>
</td>
<td align="right">
<asp:HyperLink ID="lnkClose" Style="cursor: pointer" runat="server">X</asp:HyperLink>
</td>
</tr>
<tr>
<td class="lable">
Upload File :
</td>
<td>
<div class="inputBox">
<asp:FileUpload ID="FileUpload2" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="FileUpload2"
ErrorMessage="Message Required" ValidationGroup="image" CssClass="Validation"></asp:RequiredFieldValidator>
</div>
</td>
</tr>
<tr>
<td>
&#160;&#160;
</td>
<td align="left">
<asp:Button ID="btnSave" runat="server" CssClass="frmsubmit" ValidationGroup="image"
Text="Save" OnClick="btnSave_Click" />
</td>
</tr>
</table>
</asp:Panel>
<cc1:ModalPopupExtender ID="ModalPopupExtender1" runat="server" DynamicServicePath=""
BackgroundCssClass="modalBackground" CancelControlID="lnkClose" Enabled="True"
PopupControlID="PnlUser" TargetControlID="EditAvtar">
</cc1:ModalPopupExtender> 

OR 

Page.ClientScript.RegisterStartupScript(this.GetType(), "popup", "<script language=javascript>window.open('PaymentEntryMaster.aspx','','width=1200px,height=500px,menubar=no,titlebar=no,toolbar=no,top=100,left=75')</script>"); 

 Menu Selection In C#

 <div class="nav" style="margin-top: 0;">
                <!--nav st-->
                <ul>
                <% if(Page.Request.Path.Contains("Default.aspx")){ %>

                    <li id="active"><a href="Default.aspx">Home</a></li>
                    <% } else {%>
                     <li ><a href="Default.aspx">Home</a></li>
                    <%} %>


                    <% if (Page.Request.Path.Contains("Search.aspx")){ %>
                    <li id="active"><a href="Search.aspx">Search</a></li>
                    <% } else {%>
                     <li ><a href="Search.aspx">Search</a></li>
                    <%} %>

                    <% if (Page.Request.Path.Contains("#")){ %>
                    <li id="active"><a href="#">Browse</a></li>
                    <% } else {%>
                     <li ><a href="#">Browse</a></li>
                    <%} %>

                    <% if (Page.Request.Path.Contains("AddProperty.aspx")){ %>
                    <li id="active"><a href="AddProperty.aspx">place ad</a></li>
                    <% } else {%>
                     <li ><a href="AddProperty.aspx">place ad</a></li>
                    <%} %>

                     <% if (Page.Request.Path.Contains("MyAccount.aspx")){ %>
                    <li id="active"><a href="MyAccount.aspx">My account</a></li>
                    <% } else {%>
                     <li ><a href="MyAccount.aspx">My account</a></li>
                    <%} %>

                     <% if (Page.Request.Path.Contains("AboutUs.aspx")){ %>
                    <li id="active"><a href="AboutUs.aspx">About us</a></li>
                    <% } else {%>
                     <li ><a href="AboutUs.aspx">About us</a></li>
                    <%} %>
                  
                 

                    <li id="Li1"><a href="#">Info &amp; advice</a></li>

                    <asp:Panel ID="pnlRegisterHide" runat="server">
                     <% if (Page.Request.Path.Contains("Login.aspx")) { %>
                    <li id="active"><a href="Login.aspx">Login/Register</a></li>
                    <% } else {%>
                     <li ><a href="Login.aspx">Login/Register</a></li>
                    <%} %>
                  
                    </asp:Panel>
                    <asp:Panel ID="pnlLogOutHide" Visible="false" runat="server">
                    <li>
                        <asp:LinkButton ID="btnLogout" runat="server" onclick="btnLogout_Click">LogOut</asp:LinkButton></li>
                    </asp:Panel>
                </ul>
            </div> 

 

Block or Disable Cut, Copy and Paste operation in ASP.Net

 

Block or Disable Cut, Copy and Paste operation in ASP.Net TextBox Using jQuery
It is required to block the cut, copy and paste operations on some of the textbox in an ASP.Net. For example, it will be better if we do not allow users to copy paste the data entered in Email and Confirm Email field in order to make the user to type themselves.
The below jQuery code will help us to do the same using preventDefault() method.

<script src="_scripts/jquery-1.4.1.min.js" type="text/javascript"></script>   
    <script type="text/javascript">
        $(function() {
        $("#<% =txtEmail.ClientID %>,#<% =txtConfirmEmail.ClientID%>").bind("cut copy paste", function(event) {
                event.preventDefault();
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>   
        <b>Email </b><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><br />
        <b>Confirm Email </b><asp:TextBox ID="txtConfirmEmail" runat="server"></asp:TextBox>


Block Right Click in asp.net
If you want to block right click copy code in master page.
<SCRIPT language=JavaScript>
<!--  -->
    var message = "function disabled";
    function rtclickcheck(keyp){ if (navigator.appName == "Netscape" && keyp.which == 3){     alert(message); return false; }
    if (navigator.appVersion.indexOf("MSIE") != -1 && event.button == 2) {     alert(message);     return false; } }
    document.onmousedown = rtclickcheck;
</SCRIPT>

Request.Url parameters & details (Asp.net)


Here I will explain you Request.Url Parameters and its details.
Full URL : http://localhost:2000/virtual_dir/myrep/page.aspx?q=qvalue
Request.ApplicationPath : /virtual_dir
Request.CurrentExecutionFilePath : /virtual_dir/myrep/page.aspx
Request.FilePath : /virtual_dir/myrep/page.aspx
Request.Path : /virtual_dir/myrep/page.aspx
Request.PhysicalApplicationPath : d:\Inetpub\wwwroot\Websitename\virtual_dir\
Request.QueryString : /virtual_dir/myrep/page.aspx?q=qvalue
Request.Url.AbsolutePath : /virtual_dir/myrep/page.aspx
Request.Url.AbsoluteUri : http://localhost:2000/virtual_dir/myrep/page.aspx?q=qvalue
Request.Url.Host : localhost
Request.Url.Authority : localhost:2000
Request.Url.LocalPath : /virtual_dir/myrep/page.aspx
Request.Url.PathAndQuery : /virtual_dir/myrep/page.aspx?q=qvalue
Request.Url.Port : 2000
Request.Url.Query : ?q=qvalue
Request.Url.Scheme : http
Request.Url.Segments : /
virtual_dir/
myrep/
page.aspx


 

C# String Tips


Fill a String with Repeating Characters

To fill a string with repeating characters, use the string class constructor. For example, to fill a string with twenty asterisks:
string s = new string( '*', 20 );


Check for Blank String



A blank string can be represented by a null reference or empty string (String.Empty or ""). If you attempt to call a method on a null string, an exception will occur. Hence, to check for a blank string, you should use the new .NET v2.0 static function String.IsNullOrEmpty:
String.IsNullOrEmpty( s )


String.Empty vs. ""? It Doesn't Matter



There has been endless debate on the Web whether it's better to represent an empty string with String.Empty or blank quotes "". However, tests show there is minimal performance difference between String.Empty and "" even when creating a billion empty strings.

Reverse a String



There has been extensive analysis on algorithms to reverse a string. The following is a good balance between speed and clarity and works well with Unicode and alternate character sets:
static public string Reverse( string s )
{
    char[] charArray = s.ToCharArray();
    Array.Reverse( charArray );
    return new string( charArray );
}

Compare Strings

Because a string reference can be null, you should avoid using the equality symbol == or the Compare member function when comparing strings. Instead, use the static String.Compare method. This method has the advantage that it can handle null string references, compare strings ignoring case, and compare strings using a specific culture:
if (String.Compare( s1, s2, true ) == 0) 

Convert String to Numeric Value

Each numeric data type such as int, Int32, double, etc. has a static TryParse method that converts a string to that data type without throwing an exception. The method returns a bool whether the string contained a value with the specified data type. For example:
string s = "42";
int i;
int.TryParse( s, out i );

Use Literal Strings for File Paths

A literal string enables you to use special characters such as a backslash or double-quotes without having to use special codes or escape characters. This makes literal strings ideal for file paths that naturally contain many backslashes. To create a literal string, add the at-sign @ before the string's opening quote. For example:
string path = @"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe";

String Right

Noticeably absent from the string class is the Right method. But you can replicate it easily using the Substring method. Here is a simple method that wraps this up nicely:
static string Right( string s, int count )
{
    string newString = String.Empty;
    if (s != null && count > 0)
    {
        int startIndex = s.Length - count;
        if (startIndex > 0)
            newString = s.Substring( startIndex, count );
        else
            newString = s;
    }
    return newString;
}

IndexOf Ignoring Case

The string's IndexOf methods are all case-sensitive. Fortunately, the Globalization namespace contains the CompareInfo class that includes a case-insensitive IndexOf method. For example:
using System.Globalization;


string s1 = "C# is a GREAT programming language.";
string s2 = "great";

CompareInfo Compare = CultureInfo.InvariantCulture.CompareInfo;
int i = Compare.IndexOf( s1, s2,CompareOptions.IgnoreCase);
file download
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + obj.Attachment);
                    Response.TransmitFile(Server.MapPath("~/Docs/" + obj.Attachment));
                    Response.End();

 

2 comments: