Friday, March 29, 2013

How to call Webservice from c#

//Written in html.aspx in

 <script type="text/javascript">
        function CreateTest(Path) {
            var pageUrl = '<%=ResolveUrl("~/SitemapService.asmx")%>'
            var parameters = "{path:'" + Path + "'}";
            $.ajax({
                type: "POST",
                url: pageUrl + "/CreateXMLBreadCrum",
                data: parameters,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccessCall,
                error: OnErrorCall
            });
        }
        function OnSuccessCall(response) {
            //alert('Hi');
        }
        function OnErrorCall(response) {
            //alert(response);
        }
    </script>

// CreateXMLBreadCrum is ametohd in a SitemapService.asmx

//Calling By C#
ScriptManager.RegisterStartupScript(UpdatePanel1, this.Page.GetType(), System.Guid.NewGuid().ToString(), "CreateTest('sitemap/Web.sitemap');", true);



Monday, March 25, 2013

How to set dynamic DEfault button in dot net whith master page and usercontrol in datalist


string st="BtnSubmit" ;//button control id, txtBox= Textbox id this is for gridviw or repeater or datalist

((TextBox)e.Item.FindControl("txtBox")).Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + st + "').click();return false;}} else {return true}; ");


hOW TO SET MAIL SETTING IN ASP.NET?

//IN WEB.CONFIG

<system.net>

<mailSettings>

<smtp>

<network host="smtp.servername" port="25" userName=noreply@servername password="*******"/>

</smtp>

</mailSettings>

</system.net>

how to set namespace in asp.net C#?

//IN Web.config 
<pages enableViewStateMac="true" enableEventValidation="false" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID" enableViewState="true">

<namespaces>

<add namespace="System.Collections.Generic"/>

<add namespace="System.IO"/>

<add namespace="System.Data"/>

<add namespace="System.Data.SqlClient"/>

</namespaces>

</pages>

How to set browser in .net C#

<system.webServer>

<httpProtocol>

<customHeaders>

<clear />

<add name="X-UA-Compatible" value="IE=9" />

</customHeaders>

</httpProtocol>
</system.webserver>

How to set Viewstate in .net

<add key="aspnet:MaxHttpCollectionKeys" value="100001" />
//in Web.config

Thursday, March 21, 2013

partition and paging in sql server

CREATE proc [dbo].[pagingandprtion]--

(

@FilterValue VARCHAR(MAX),

@SearchText VARCHAR(MAX),

@startindex INT ,

@pagesize INT,

@Flag VARCHAR(10),

@OrderBy VARCHAR(200)

)

AS

BEGIN

DECLARE @SQL varchar(MAX)

IF(@Flag='CODE')

BEGIN

SET @SQL = '



WITH PagingCTE AS (

SELECT ROW_NUMBER()OVER(ORDER BY ItemCode)AS Row_ID1,* from

(SELECT * ,ROW_NUMBER()OVER(partition by itemcode ORDER BY itemcode)AS Filt_Id FROM vw_allProductNew1 WHERE IsActive=1 AND

(ProductCode LIKE ''%'+ @SearchText + '%'' OR ProductName LIKE ''%'+ @SearchText + '%'') '+@FilterValue+') AS A )



select * from( SELECT ROW_NUMBER()OVER(ORDER BY ItemCode)AS Row_ID,* FROM PagingCTE WHERE Filt_id=1) as a WHERE

Row_ID >= ('+cast(@pagesize as varchar(10))+' * '+cast(@startindex as varchar(10))+') - ('+cast(@pagesize as varchar(10))+' -1) AND

Row_ID <= ('+cast(@pagesize as varchar(10))+' *'+ cast(@startindex as varchar(10))+') ' +'' +@OrderBy+''

--print @sql

END

ELSE

BEGIN

SET @SQL = '



WITH PagingCTE AS (

select ROW_NUMBER()OVER(ORDER BY ItemCode)AS Row_ID1,* FROM (select ROW_NUMBER()OVER(PARTITION BY ItemCode ORDER BY ItemCode)AS ID,* FROM

(SELECT *,ROW_NUMBER()OVER(partition by itemcode ORDER BY itemcode)AS Filt_Id FROM vw_allProductNew1 WHERE

IsActive=1 AND (ProductCode LIKE ''%'+ @SearchText + '%'' OR ProductName LIKE ''%'+ @SearchText + '%'')'+@FilterValue+')AS A) B WHERE B.ID=1 )



select * from( SELECT ROW_NUMBER()OVER(ORDER BY ItemCode)AS Row_ID,* FROM PagingCTE WHERE Filt_id=1) as a WHERE

Row_ID >= ('+cast(@pagesize as varchar(10))+' * '+cast(@startindex as varchar(10))+') - ('+cast(@pagesize as varchar(10))+' -1) AND

Row_ID <= ('+cast(@pagesize as varchar(10))+' *'+ cast(@startindex as varchar(10))+') ' +@OrderBy+''

END



--print @SQL

EXEC (@SQL)

END

ASP.Net Page Life Cycle


 Understanding the Pagelife cycle is important to develop ASP.Net application.

The general Page Life Cycle Stages are:
1. Page request - Here Page is requested by the user.
... 2. Start – Sets the properties such as Request, Response, IsPostBack and UICulture.
3. Page initialization - Controls on the page are available and each control's UniqueID property is set.
4. Load – Controls are loaded here if it is a PostBack request.
5. Validation – Sets the IsValid property.
6. Postback Event handling – Event handlers will be called if it is PostBack.
6. Rendering - the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream of the page's Response property.
7. Unload - Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded.

Common life cycle Events:
1. PreInit – Start event of the Page life cycle and here every page controls are initialized.
2. Init – This is used to read or initialize control properties.
3. InitComplete – Used for processing tasks that require all initialization be complete.
4. PreLoad - This is used before Perform any processing that should occur before Load.
5. Load - Use the OnLoad event method to set properties in controls and establish database connections.
6. Control Event - These are control specific events such as – Button Click, DropDownIndexChanged etc.
7. Load Complete - This event is used for performing those tasks which require load has been completed.
8. PreRender - In this event page insures that all child controls are created.
9. SaveStateComplete - This event occurs after viewstate encoded and saved for the page and for all controls.
10. Render – This is not an event. The page instance calls this method to output the control’s markup, after this event any changes to the page or controls are ignored.
11. Unload – Nothing but cleanup task like closing the files, database connections etc.,

This table shows stages and corresponding Events

Stage Events/Method
Initialization of the page Page_Init
Loading of the View State LoadViewState
processing of the Post back data LoadPostData
Loading of Page Page_Load
Notification of PostBack RaisePostDataChangedEvent
Handling of PostBack Event RaisePostBackEvent
Pre Rendering of Page Page_PreRender
Saving of view state SaveViewState
Rendering of Page Page_Render
Unloading of the Page Page_UnLoad

SQL SERVER – Best Practices for Better Database Performance

SQL SERVER – Best Practices for Better Database Performance

1. Store relevant and necessary information in the database instead of application structure or array.

2. Use normalized tables in the database. Small multiple tables are usually better than one large table.
...
3. If you use any enumerated field create look up for it in the database itself to maintain database integrity.

4. Keep primary key of lesser chars or integer. It is easier to process small width keys.

5. Store image paths or URLs in database instead of images. It has less overhead.

6. Use proper database types for the fields. If StartDate is database filed use datetime as datatypes instead of VARCHAR(20).

7. Specify column names instead of using * in SELECT statement.

8. Use LIKE clause properly. If you are looking for exact match use “=” instead.

9. Write SQL keyword in capital letters for readability purpose.

10. Using JOIN is better for performance then using sub queries or nested queries.

11. Use stored procedures. They are faster and help in maintainability as well security of the database.

12. Use comments for readability as well guidelines for next developer who comes to modify the same code. Proper documentation of application will also aid help too.

13. Proper indexing will improve the speed of operations in the database.

14. Make sure to test it any of the database programming as well administrative changes.

Tuesday, March 19, 2013

Array find method

using System;

class Program
{
    static void Main()
    {
// // Use this array of string references. //
string[] array1 = { "cat", "dog", "carrot", "bird" };
// // Find first element starting with substring. //
string value1 = Array.Find(array1,
    element => element.StartsWith("car", StringComparison.Ordinal));
// // Find first element of three characters length. //
string value2 = Array.Find(array1,
    element => element.Length == 3);
// // Find all elements not greater than four letters long. //
string[] array2 = Array.FindAll(array1,
    element => element.Length <= 4);

Console.WriteLine(value1);
Console.WriteLine(value2);
Console.WriteLine(string.Join(",", array2));
    }
}

Output

carrot
cat
cat,dog,bird


using System;

class Program
{
    static void Main()
    {
string[] array = { "dot", "net", "perls" };
// Find last string of length 3.
string result = Array.FindLast(array, s => s.Length == 3);
Console.WriteLine(result);
    }
}

Output

net

Array Sort, Binarysearch, and Reverse

using System;

class
linSearch{
    public static void Main()
    {
        int[] a = new int[3];
        Console.WriteLine("Enter number of elements you want to hold in the array (max3)?");
        string s = Console.ReadLine();
        int x = Int32.Parse(s);
        Console.WriteLine("--------------------------------------------------");
        Console.WriteLine("\n Enter array elements \n");
        Console.WriteLine("--------------------------------------------------");

        for (int i = 0; i < x; i++)
        {
            string s1 = Console.ReadLine();
            a[i] = Int32.Parse(s1);
        }

        Console.WriteLine("Enter Search element\n");
        Console.WriteLine("--------------------------------------------------");
        string s3 = Console.ReadLine();
        int x2 = Int32.Parse(s3);

        // Sort the values of the Array.        Array.Sort(a);

        for (int i = 0; i < x; i++)
        {
            Console.WriteLine("--------------Sorted-------------------------");
            Console.WriteLine("Element{0} is {1}", i + 1, a[i]);
        }

        // BinarySearch the values of the Array.        int x3 = Array.BinarySearch(a, (Object)x2);
        Console.WriteLine("--------------------------------------------------");
        Console.WriteLine("BinarySearch: " + x3);
        Console.WriteLine("Element{0} is {1}", x3, a[x3]);
        Console.WriteLine("--------------------------------------------------");

        // Reverse the values of the Array.        Array.Reverse(a);
        Console.WriteLine("-----------Reversed-------------------------------");

        for (int i = 0; i < x; i++)
        {
            Console.WriteLine("----------------------------------------------");
            Console.WriteLine("Element{0} is {1}", i + 1, a[i]);
        }
    }
}


Listing 20.15 is a more sophisticated example of using the IComparer interface and Sort function together. The IComparer interface allows you to define a Compare method in order to do a comparison between two elements of your array. This Compare method is called repeatedly by the Sort function in order to sort the array. Listing 20.15 defines a Compare method that does a comparison between two strings.
Listing 20.15: Array Sorting

// sort an array according to the Nth element

using
System;
using
System.Collections;

public
class CompareX : IComparer{
    int compareFrom = 0;
    public CompareX(int i)
    {
        compareFrom = i;
    }

    public int Compare(object a, object b)
    {
        return String.Compare(a.ToString().Substring(compareFrom),
        b.ToString().Substring(compareFrom));
    }
}


public
class ArrListEx{
    ArrayList arr = new ArrayList();
    public ArrListEx()
    {
        arr.Add("aaaa9999");
        arr.Add("bbbb8888");
        arr.Add("cccc7777");
        arr.Add("dddd6666");
        arr.Sort(new CompareX(4));
        IEnumerator arrList = arr.GetEnumerator();

        while (arrList.MoveNext())
        {
            Console.WriteLine("Item: {0}", arrList.Current);
        }
    }

    public static void Main(string[] args)
    {
        new ArrListEx();
    }
}

Linear Search in array

// Linear Search
using
System;

public
class LinearSearcher{
    public static void Main()
    {
        String[] myArray = new String[7] { "kama", "dama", "lama", "yama", "pama", "rama", "lama" };
        String myString = "lama";
        Int32 myIndex;

        // Search for the first occurrence of the duplicated value in a section of the        myIndex = Array.IndexOf(myArray, myString, 0, 6);
        Console.WriteLine("The first occurrence of \"{0}\" between index 0 and index 6 is at index {1}.", myString, myIndex);

        // Search for the last occurrence of the duplicated value in a section of the       myIndex = Array.LastIndexOf(myArray, myString, 6, 7);
        Console.WriteLine("The last occurrence of \"{0}\" between index 0 and index 6 is at index {1}.", myString, myIndex);
        Console.ReadLine();
    }
}