Pages

Monday, 20 January 2014

How to read random records from a table



SELECT top 10  *
FROM CbzInventory
Order by newid()


SELECT top 10 *
FROM CbzInventory
WHERE InvIntLocation=7
ORDER BY NEWID()


select top (@intTopWeight)   q.QuesDesc,o.choice1,o.choice2,o.choice3,o.Answer
from Question q join Options o
on  q.QuesID=o.QuesId and q.UserLevelID=1   join ExamWeightage e on e.TopicID=q.TopicID where e.TopicId=1  Order by newid()

How to read more than one table from database using DataReader

                        if (dr.HasRows)
                        {                          
                            while (dr.Read())
                            {                            
                            }
                        }
                        if (dr.NextResult())
                        {                          
                            if (dr.HasRows)
                            {                            
                                while (dr.Read())
                                {                                  
                                }                            
                            }
                        }
                        dr.Close();

SQL Server Best Practices

SQL Server Best Practices
1. Drop temp table variable  in procedure end of procedure.
2. Don't use indexes for the column(s) are defined as Text,NText or Image data types.
3. Create index on integer data type columns is best .
4. use the sp_executesql stored procedure instead of the EXECUTE statement. 
5. Execute Sp using exec dbo.ProcName.
6. Use stored procedures instead of views.
7.  If you use LIKE in your WHERE clause, try to use one or more leading characters in the clause
8. When you have a choice of using the IN or the BETWEEN clauses in your Transact-SQL, you will generally want to use the BETWEEN clause, as it is much more efficient
9. If possible, try to avoid using the SUBSTRING function in your WHERE clauses. 
10. Practice to avoid nchar and nvarchar data type since both the data types takes just double memory as char and varchar
11. Practice to use Table varible in place of Temp table since Temp table resides in the TempDb database. Hence use of Temp tables required interaction with TempDb database that is a little bit time taking task.
12. Practice to use TRY-CATCH for handling errors in T-SQL statements. Sometimes an error in a running transaction may cause deadlock if you have no handle error by using TRY-CATCH
13. Use BEGIN , COMMIT  and  ROLLBACK  in sp to avoid unnecessary 



Performance Related:
1. Set NO count on
2. Set Statistics io off
3. For better performance, if you need a temporary table in your Transact-SQL code, consider using a table variable instead of creating a conventional temporary table.
4. Unwanted joining  tables  removed 
5. Don't use select distinct for single row selection instead of that  use Select Top 1 
6. Don't use select count(*) form row exists or not checking instead of  that use Select Top 1.
7. If you need to verify the existence of a record in a table, don't use SELECT COUNT (*) in your Transact-SQL code to identify it. This is very inefficient and wastes server resources. Instead, use the Transact-SQL IF EXISTS to determine if the record in question exists, which is much more efficient.
8. Use dynamic query and condition checking.
9. Avoid sub query and use join for inserting one table record into another table.
10. Use clustered index and multiple column non clustered indexes for order by and group by function.
11. Removed un used indexes from tables.
12. Don't add indexes to small tables.
13. Index should be added to which column frequently used Top,Order by,Distinct,Where,Group By
14. Don't add more indexes to OLTP tables it gives increases overhead on table .
15. Do not add the same index more than once on a table with different names.
16. Avoid Index for rarely queried but insertion, updating is frequent.
17. Where clause with AND operator with index column filter boost performance.
18. Try to create stored procedure inline sql querys.
19. Avoid function and UDF in where class 
20. Instead of cursor use some loop (while)
21.  If possible, avoid using SQL Server cursors. They generally use a lot of SQL Server resources and reduce the performance and scalability of your applications.
22. Use foreign key to avoid duplication and correct data insert and delete from a table.
23. Foreign key also give some performance wise improvement.(Execution Plan).
24. Keep Procedure T-Sql lines as short as possible it will reduce no of locks so speed will  automatically improve.
25. Don't Use SP_ in front of Stored Procedures.
26. Remove Un used lines in stored procedure affect performance speed so remove it
27. If you use input parameters in your stored procedures, you should validate all of them at the beginning of your stored procedure. This way, if there is a validation problem and the client application needs to be notified of the problem, it happens before any stored procedure processing takes place, preventing wasted effort and boosting performance.
28. I you use BULK INSERT to import data into SQL Server, then use the TABLOCK hint along with it. This will prevent SQL Server from running out of locks during very large imports and will also boost performance due to the reduction of lock contention
29. If you need to store large strings of data and they are less than 8000 characters, use a VARCHAR data type instead of a TEXT data type. TEXT data types have extra overhead that drag down performance.
30. Don't use the DATETIME data type as a primary key. From a performance perspective, it is more efficient to use a data type that uses less space.
31. Don't use Upper Lower function in where clause it will reduce speed of executions.
32. Choose appropriate SQL Data Type to store your data since it also helps in to improve the query performance.
33. Don't use ORDER BY in your SELECT statements unless you really need to, as it adds a lot of extra overhead. For example, perhaps it may be more efficient to sort the data at the client than at the server.
34. Practice to use EXISTS to check existence instead of IN since EXISTS is faster than IN.

ASP.NET Best Practices

ASP.NET Best Practices

1. Caching Improves web application Performance
2. Don't give more no of request to DB .Single request to DB and get more result. Round trip time will reduced and seconds per request will improved.
3. While you can return multiple resultsets using dynamic SQL, I prefer to use stored procedures. It's arguable whether business logic should reside in a stored procedure, but I think that if logic in a stored procedure can constrain the data returned (reduce the size of the dataset, time spent on the network, and not having to filter the data in the logic tier), it's a good thing.
4. Using a SqlCommand instance and its ExecuteReader method to populate strongly typed business classes, you can move the resultset pointer forward by calling NextResult. 
5. Apply Connection Pooling in sql server to Application.
6. Dont trust CLR to for sqlconnection will automatically closed.try to closed you sql connection  when your operation was completed.
7. Use Connection Pooling (Default size:100)
8. Use Output Caching (Kernal mode Caching give more Speed).
9. Enable gzip compression in IIS will reduce the byte of response sent from server.
10. Always set debug=”false” in web.config production environment.
11. Always set trace=”false” in web.config production environment.
12. Always compile your project in Release Mode before uploading application to production environment.
13. Decrease your html kb as much as you can for that use tables less html using div’s and if possible  then do not give big name to your control it will increase your html kb as asp.net uses client Id to differentiate all the controls. If you are creating custom controls then you can overwrite your clientid and uniqueId.
14. Remove blank spaces from your html it will increase your kb. You can use regular expression t0 remove white spaces. I will post the code for removing white spaces next posts.
15. Prefer database reader over dataset unless and until you have specific reason to use database
16. Use ADO.NET asynchronous calls for ado.net methods. asp.net 2.0 or higher version is supporting your performance. If you are using same procedure or command multiple time then use ADO.NET Prepare command it will increase your performance.
17. Use  Server.Transfer instead of response.redirect.
18. Use Ajax for your application wisely. Lots of Ajax calls for a page will also decrease your performance
19. User System.Text.StringBuilder for string concatenation its 4 times more faster then the normal strings.
20. Right JavaScript in .Js files and place it as bottom of the application
21. Use Separate CSS files for styling of application
22. Call web service from java script instead of server side. Use asynchronous calls to call a web method from web service
23. Disable View State :View state is used to allow ASP.NET to keep the state of the page between postbacks performed by user. View state data is stored in HTML output inside hidden field. If your page displays many controls that contains a huge data, the view state field will be big enough to affect the response time of your page. if your page just display data without need any postback so it will be better to disable the view state of the whole page by set EnableViewState to false.
24.  Pre-Compiling ASP.NET Application:
25. When compiling an ASP.NET application project, a single assembly is created to hold all application's code but web pages(.aspx) and user controls(.ascx) not compiled and be deployed as it is. In the first request ASP.NET dynamically compiles the web pages and user control and places the compiled files in the ASP.NET temporary files folder.
To reduce the time of first request the web application can be pre-compiled, including all code, pages, and user controls, by using the ASP.NET compilation tool (Aspnet_compiler.exe). Running this tool in production servers can reduce the delay users experience on first requests.
You can pre-compile web pages in your application to reduce the working set size and boost application performance. SetAutoEventWireup attribute to false in thesection of the server's Machine.config file to improve performance further, e.g.:
   <configuration> <system.web> <pages autoEventWireup="true|false" /> </system.web>    </configuration>
You can pre-compile web pages in your application to reduce the working set size and boost application performance. SetAutoEventWireup attribute to false in thesection of the server's Machine.config file to improve performance further, e.g.:
   <configuration> <system.web> <pages autoEventWireup="true|false" /> </system.web>    </configuration>

a. Open a command prompt in your production server.
b. Navigate to the %windir%\Microsoft.Net folder
c. Navigate to either the Framework or Framework64 according to the configuration of web application's application pool.
d. Navigate to framework version's folder.
e. Enter the following command to start the compilation
Aspnet_compiler.exe  -v  /FullPathOfYourWebApplication
26. Reducing Page Load Time:
Avoid excessively large images, redundant tags, and nested tables to facilitate faster page loads. Always avoid unnecessary roundtrips to the web server. Use client side scripts to dramatically reduce server roundtrips, thereby boosting the perceived, if not the actual application performance. Take advantage of the Page.IsPostback property to avoid unnecessary server processing on a roundtrip, reducing network traffic. I suggest you leave page buffering on (it is turned on by default) for a page unless you have a specific reason to turn it off.
27. ViewState is great for storing control state but can degrade performance—especially on web sites with large page sizes. If you've ever looked at a page that contains a large DataSet, you know the amount of data stored in ViewState can be overwhelming. Every byte added to a web page by enabling its ViewState causes two bytes of network traffic, one in each direction. Evaluate whether each web page you write requires ViewState and avoid it when possible to speed up the page-load cycle in your applications. You should typically use ViewState only for controls that need to persist state. You can turn ViewState on or off at four levels: machine, application, page, and control. Limiting the size of the ViewState and eliminating its unnecessary usage would boost the application performance to a large extent due to the reduced size of the rendered pages and hence the network traffic. It should be noted that each byte of the view state causes two bytes of network traffic for each request, one from the server to the client and the other from the client to the server. For more information on ViewState and how to turn it off at control, page, application, or machine levels.
28. You can remove the runat="server" form tag completely to reduce page size by 20 bytes. If you don't remove this tag, the page itself passes on about 20 bytes of information to ViewState—even when the page's ViewState property is set to false.
29. Caching is one of the best strategies for storing relatively static application data. Caching reads data from memory to avoid repeatedly retrieving data from a database, file, or any other repository, and it can provide huge application performance gains. Use Page Output, Page Fragment or Data Caching directives depending on your requirements. Cache application-wide data that multiple users of the application need to share and access, but avoid storing user-specific data in the cache.
30. Use Session State only for storing a single user's session data. Avoid storing too many objects in the Session and turn Session State off for pages that do not need to access session data. You can turn Session State on or off at the same four levels as ViewState: machine, application, page, and control.
31. Note that there are three Session State storage modes. The right type of storage mode to choose depends on factors such as, speed, security, scalability, and reliability. Even though the InProc mode of Session State storage is the fastest, it is not at all well suited to a production environment and not scalable for large sites. The OutProc storage mode is well-suited for web sites with heavy traffic, while the SqlServer mode is great for securing session data. No matter which mode you choose though, Session State has one major disadvantage: the resource will be increasingly strained as you scale up. There are always tradeoffs. The best mode for security, scalability, and reliability is not always the best mode for performance, and vice versa.

Sunday, 19 January 2014

How to Sorting (order by) A generic list

public static string GetCollectionRefNos()
        {
            string CollRefNosObj = string.Empty;
            string StatusCode = "200";
            string StatusMsg = "Success";
            string[] TempCollRefNo;
            try
            {
                using (CollectionRefNos CollRefNos = new CollectionRefNos())
                {
                    List<CollectionRefNos> lstColRef = new List<CollectionRefNos>();
                    using (workflow.Components.Inventory DAL = new workflow.Components.Inventory())
                    {
                        SqlDataReader Dr;
                        SqlParameter[] Param = new SqlParameter[1];
                        Param[0] = new SqlParameter("@Flag", "A");
                        using (Dr = DAL.ReadData(Usp_CollectionRefOpr, Param))
                        {
                            if (Dr.HasRows)
                            {
                                while (Dr.Read())
                                {
                                    TempCollRefNo = EsHelper.EsGetValidString(Dr["PrdCollRefNo"]).Split('|');
                                    foreach (var Temp in TempCollRefNo)
                                    {
                                        lstColRef.Add(new CollectionRefNos()
                                        {
                                            CollRefNo =int.Parse(Temp)
                                        });
                                    }
                                }
                            }
                        }
                    }
                    lstColRef.Sort(delegate(CollectionRefNos p1, CollectionRefNos p2)
                    {
                        return p1.CollRefNo.CompareTo(p2.CollRefNo);
                    });
                    if (lstColRef.Count <= 0)
                    {
                        StatusCode = "204"; StatusMsg = "No Records Found";
                    }
                    CollRefNosObj = EsHelper.ListToJson<CollectionRefNos>(lstColRef, "CollRefNos", StatusCode, StatusMsg);
                }
            }
            catch (Exception ex)
            {
                EsHelper.EsADLogger("EstoreCollectionRef.aspx GetCollectionRefNos()", EsHelper.EsGetValidString(ex.Message));
            }
            return CollRefNosObj;
        }



   public class CollectionRefNos : IDisposable
        {
            #region Properties
            public int CollRefNo { get; set; }
            #endregion

            public void Dispose()
            {
            }
        }

How to solve Cross domain issue during Wcf host in iis


Add below code in your global .asax file


 protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept,x-requested-with");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

JQuery class with inheritance with constructors


var helper = (function () {
            var alertmsg = function () {
                alert("hi alert1");
            };
            return { ALERTMSG: alertmsg };
        })();

 helper.ALERTMSG()








/** new, preferred syntax **/
   
// properties are directly passed to `create` method
var Person = Class.create({
  initialize: function(name) {
    this.name = name;
  },
  say: function(message) {
    return this.name + ': ' + message;
  }
});
   
// when subclassing, specify the class you want to inherit from
var Pirate = Class.create(Person, {
  // redefine the speak method
  say: function($super, message) {
    return $super(message) + ', yarr!';
  }
});
   
var john = new Pirate('Long John');
john.say('ahoy matey');
// -> "Long John: ahoy matey, yarr!"




How to use json data in Ajax jQuery function

JSON String access in AJAX
 $.ajax({
                url: "Logistics.aspx/GetShippingInfo",
                type: "POST",
                data: '{Object:"LogObject",Dtls:"ShipingDtls|ShippedOnceDtls"}',
                contentType: "application/json",
                dataType: "json",
                success: OnsuccessGetShippingCounts,
                error: function (xhr) {
                    $('#aShipInfo').stop();
                    $('#aShipInfo').fadeIn();
                    $('#aShipInfo').hide();
                    $('#aShipInfo').show();
                    $('#aShipInfo').css('opacity', 1.0);
                    $("#aShipInfo").text('Shipping Info');
                    alert("Failed to get Data.");
                }
            });
        }
        function OnsuccessGetShippingCounts(data) {
            if (data.d != null) {
                var temp = '{' + data.d + '}';
            }
            var values = $.parseJSON(temp);
            for(var Idx=0;Idx<=values.LogObject[0].ShipingDtls.length-1; Idx++)
            {
                if(values.LogObject[0].ShipingDtls[Idx].Guide=="Complete Ship")
                    spnCompleteShip.innerHTML = values.LogObject[0].ShipingDtls[Idx].CNT;
                if (values.LogObject[0].ShipingDtls[Idx].Guide == "Cross Check")
                    spnCrossCheck.innerHTML = values.LogObject[0].ShipingDtls[Idx].CNT;
                if (values.LogObject[0].ShipingDtls[Idx].Guide == "Force Ship")
                    spnForceShip.innerHTML = values.LogObject[0].ShipingDtls[Idx].CNT;
                if (values.LogObject[0].ShipingDtls[Idx].Guide == "Hold")
                    spnHold.innerHTML = values.LogObject[0].ShipingDtls[Idx].CNT;
            }
            for (var Idx = 0; Idx <= values.LogObject[1].ShippedOnceDtls.length - 1; Idx++) {
                if (values.LogObject[1].ShippedOnceDtls[Idx].History == "Yes")
                    spnShippedOnce.innerHTML = values.LogObject[1].ShippedOnceDtls[Idx].HisCnt;                
            }

Convert dictionary into json in .net

public static string DictionaryToJson<T>(Dictionary<string, List<T>> Dict, string Object, string StatusCode, string Message)
    {
        StringBuilder sb = new StringBuilder();
        int DictCount = 0;
        int TempCount = 0;
        try
        {
            if (Dict != null && StatusCode == "200" && Message == "Success")
            {
                sb.Append("{\"Status\":\"" + StatusCode + "\",");
                sb.Append("\"Message\":\"" + Message + "\",");
                sb.Append("\"" + Object + "\":");
                sb.Append("[{");
                DictCount = Dict.Count;
                foreach (var lst in Dict)
                {
                    sb.Append("\"" + lst.Key + "\":");
                    sb.Append(JsonConvert.SerializeObject(lst.Value));
                    TempCount++;
                    sb.Append("},{");
                    if (DictCount == TempCount)
                    {
                        int index = EsHelper.EsGetValidString(sb).Length;
                        sb.Remove(index - 2, 2);
                    }
                }
                sb.Append("]}");
                //string error=HttpContext.Current.Session["error"].ToString();
            }
            else
            {
                sb.Append("{\"Status\":\"" + StatusCode + "\",");
                sb.Append("\"Message\":\"" + Message + " \"}");
            }
        }
        catch (Exception ex)
        {
            EsHelper.EsADLogger("Logistics.aspx DictionaryToJson<T>()", ex.Message.ToString());
            StringBuilder ExSb = new StringBuilder();
            ExSb.Append("{\"Status\":\"" + StatusCode + "\",");
            ExSb.Append("\"Message\":\" Service Failed During Json Conversion  \"}");
            return EsHelper.EsGetValidString(ExSb);
        }
        return EsHelper.EsGetValidString(sb);
    }

Convert dataset to json in .net

public static string DataSetToJson(DataSet ds, string Object,string[] arrDlts, string StatusCode, string Message)
    {
        StringBuilder sb = new StringBuilder();
        try
        {
            if (ds != null && StatusCode == "200" && Message == "Success")
            {

                sb.Append("{\"Status\":\"" + StatusCode + "\",");
                sb.Append("\"Message\":\"" + Message + "\",");
                sb.Append("\"" + Object + "\":");
                sb.Append("[{");
                int tblCount=ds.Tables.Count;
                int TempCount=0;
                foreach (var dt in ds.Tables)
                {
                    sb.Append("\"" +arrDlts[TempCount]  + "\":");
                    sb.Append(JsonConvert.SerializeObject(dt));
                    TempCount++;
                    sb.Append("},{");
                    if (tblCount == TempCount)
                    {
                        int index = EsHelper.EsGetValidString(sb).Length;
                        sb.Remove(index - 2, 2);
                    }
                }
                sb.Append("]}");
            }
            else
            {
                sb.Append("{\"Status\":\"" + StatusCode + "\",");
                sb.Append("\"Message\":\"" + Message + "\"}");
            }
        }
        catch (Exception ex)
        {
            EsHelper.EsADLogger("Logistics.aspx DataSetToJson<T>()", ex.Message.ToString());
            StringBuilder ExSb = new StringBuilder();
            ExSb.Append("{\"Status\":\"" + StatusCode + "\",");
            ExSb.Append("\"Message\":\" Service Failed During Json Conversion  \"}");
            return EsHelper.EsGetValidString(ExSb);
        }
        return EsHelper.EsGetValidString(sb);
    }

Convert datareader to json in .net

public static string DataReaderToJson(SqlDataReader dr, string Object, string Dtls)
    {
        string json = string.Empty; ;
        string SucessCode = "200";
        StringBuilder sb = new StringBuilder();
        sb.Append("{");
        sb.Append("\"Status\":\"" + SucessCode + "\",");
        sb.Append("\"Message\":\"Sucess\",");
        sb.Append("\"" + Object + "\":");
        sb.Append("[");
        sb.Append("{");
        if (dr.HasRows)
        {
            int rowCount = 0;
            sb.Append("\"" + Dtls + "\":");
            sb.Append("[");
            while (dr.Read())
            {
                sb.Append("{");
                for (int i = 0; i < dr.FieldCount; i++)
                {
                    sb.Append("\"" + EsHelper.EsGetValidString(dr.GetName(i)).Replace("\"", "\\\"") + "\":");
                    sb.Append("\"" + EsHelper.EsGetValidString(dr[i]).Replace("\"", "\\\"") + "\"");
                    sb.Append(i == dr.FieldCount - 1 ? "" : ",");

                }

                sb.Append("},");

                rowCount++;

            }
            if (rowCount > 0)
            {
                int index = EsHelper.EsGetValidString(sb).LastIndexOf(",");
                sb.Remove(index, 1);
            }

            sb.Append("]},");
        }
        dr.NextResult();
        sb.Append("{");
        if (dr.HasRows)
        {
            int rowCount = 0;
            sb.Append("\"" + Dtls + "\":");
            sb.Append("[");
            while (dr.Read())
            {
                sb.Append("{");
                for (int i = 0; i < dr.FieldCount; i++)
                {
                    sb.Append("\"" + EsHelper.EsGetValidString(dr.GetName(i)).Replace("\"", "\\\"") + "\":");
                    sb.Append("\"" + EsHelper.EsGetValidString(dr[i]).Replace("\"", "\\\"") + "\"");
                    sb.Append(i == dr.FieldCount - 1 ? "" : ",");
                }

                sb.Append("},");
                rowCount++;
            }
            if (rowCount > 0)
            {
                int index = EsHelper.EsGetValidString(sb).LastIndexOf(",");
                sb.Remove(index, 1);
            }
            sb.Append("]}");
        }
        sb.Append("]}");
        return json = JsonConvert.SerializeObject(sb);
    }