Hunt

Friday, October 5, 2012

Backup ALL your SQL Server databases using ONE script


DECLARE @DBName varchar(255)

DECLARE @DATABASES_Fetch int

DECLARE DATABASES_CURSOR CURSOR FOR
    select
        DATABASE_NAME   = db_name(s_mf.database_id)
    from
        sys.master_files s_mf
    where
       -- ONLINE
        s_mf.state = 0

       -- Only look at databases to which we have access
    and has_dbaccess(db_name(s_mf.database_id)) = 1

        -- Not master, tempdb or model
    and db_name(s_mf.database_id) not in ('Master','tempdb','model')
    group by s_mf.database_id
    order by 1

OPEN DATABASES_CURSOR

FETCH NEXT FROM DATABASES_CURSOR INTO @DBName

WHILE @@FETCH_STATUS = 0
BEGIN
    declare @DBFileName varchar(256)  
    set @DBFileName = datename(dw, getdate()) + ' - ' +
                       replace(replace(@DBName,':','_'),'\','_')

    exec ('BACKUP DATABASE [' + @DBName + '] TO  DISK = N''d:\db\' +
        @DBFileName + ''' WITH NOFORMAT, INIT,  NAME = N''' +
        @DBName + '-Full Database Backup'', SKIP, NOREWIND, NOUNLOAD,  STATS = 100')

    FETCH NEXT FROM DATABASES_CURSOR INTO @DBName
END

CLOSE DATABASES_CURSOR
DEALLOCATE DATABASES_CURSOR


------------------------------

URL:
http://www.geekzilla.co.uk/View487F82A5-C96B-4660-A070-F7C8B7FC4431.htm

Wednesday, September 12, 2012

add new line in a generic list c#


 public  StringBuilder SpliceText(string datetme, string text, int lineLength)
        {
           // return Regex.Replace(text, "(.{" + lineLength + "})", "$1" + Environment.NewLine);
            string _s= Regex.Replace(text, "(.{" + lineLength + "})", "$1" + Environment.NewLine);
            //sb.Append(datetme+"\n"+ _s);
            sb.Append(Environment.NewLine);

            sb.Append(_s);
            sb.Append(Environment.NewLine);
            _list.Add(datetme.ToString());
           // _list.Add("\n");
            _list.Add(_s);
            _list.Add("\n");
            return sb;

        }
---------------------------------------------------------
        static IEnumerable Split(string str, int chunkSize)
        {
            return Enumerable.Range(0, str.Length / chunkSize)
                .Select(i => str.Substring(i * chunkSize, chunkSize));
        }
------------------------------------
call
-------

cust.ForEach(p => SpliceText(p.Name.ToString(), p.Comment.ToString(), 140));


            IEnumerable ss = Split(sb.ToString(), 800);  

get stackpanel inside control values in datagrid in silverlight


Stackpanel Inside Controls in datagrid:

if we have button inside datagrid the click the button and add the below lines
 StackPanel stackpanel = ((Button)sender).Parent as StackPanel;
    TextBox txtName = stackpanel.Children[0] as TextBox;
    TextBox txtLName = stackpanel.Children[1] as TextBox;
URL:http://forums.silverlight.net/t/173626.aspx/1

Thursday, May 10, 2012

web service reference not adding in serviceref.clientconfig in SL class library or failed to generate code for the service reference in SL5



i have created a silverlight application.

in silverlight.web application i created web service after that i created a silverlight class library project .

now i try to adding the reference of the web service , i added it successfully but the service informations are not in serviceref.clientconfig file.

or 

it will also throw a error message like below
"Silverlight - failed to generate code for the service reference"

it shows only in my serviceref.clientconfig file.

to solve this issue do the following,


Option 1:

Use this option if your WCF service reference is not added into your project.

In “Add Service Reference” dialog click on “Advanced…” button. This will open Service Reference Settings dialog box.

In the Settings dialog box uncheck the “Reuse types in referenced assemblies” check box and click on Ok button.

Once you click on Ok button in Service Reference dialog box, the client code will be generated and you will not get any error. Now if you open “Reference.cs” file you can see the generated code.

Option 2:

Use this option if the service reference is already added into your project.

Right click on the service reference and select “Configure Service Reference…” option.


This will open “Service Reference Settings” dialog box (see image #2 in Option 1). Now as I mentioned in Option #1, uncheck “Reuse types in referenced assemblies” and click on Ok button.

Right click on service reference and select “Update Service Reference”. Once the service reference is updated you can see the client code is generated, you may verify this in “Reference.cs” file.


URL:
http://www.c-sharpcorner.com/Blogs/2115/...efere.aspx

Monday, April 16, 2012

The Given Key was not present in Dictionary Error in Silver light

if the silverlight application is in .net4.0 and the SL wcf service application is in .net3.5 then we receive the below error as "The Given Key was not present in Dictionary".

to rectify this..

go to your wcf service web.config,
- change the endpoint tag binding text to "basicHttpBinding" (need to change the 2 lines of the end point tag)

URL:

http://forums.silverlight.net/t/18559.aspx/2/10
http://go4answers.webhost4life.com/Example/the-given-key-not-dictionary-161463.aspx

Wednesday, March 28, 2012

Genric List Sorting

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Reflection;

///
/// Summary description for GListSorting
///

public static class GListSorting
{
public static void Sort(this List list, string sortExpression)
{
string[] sortExpressions = sortExpression.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

List comparers = new List();

foreach (string sortExpress in sortExpressions)
{
string sortProperty = sortExpress.Trim().Split(' ')[0].Trim();
string sortDirection = sortExpress.Trim().Split(' ')[1].Trim();

Type type = typeof(T);
PropertyInfo PropertyInfo = type.GetProperty(sortProperty);
if (PropertyInfo == null)
{
PropertyInfo[] props = type.GetProperties();
foreach (PropertyInfo info in props)
{
if (info.Name.ToString().ToLower() == sortProperty.ToLower())
{
PropertyInfo = info;
break;
}
}
if (PropertyInfo == null)
{
throw new Exception(String.Format("{0} is not a valid property of type: \"{1}\"", sortProperty, type.Name));
}
}

SortDirection SortDirection = SortDirection.Ascending;
if (sortDirection.ToLower() == "asc" || sortDirection.ToLower() == "ascending")
{
SortDirection = SortDirection.Ascending;
}
else if (sortDirection.ToLower() == "desc" || sortDirection.ToLower() == "descending")
{
SortDirection = SortDirection.Descending;
}
else
{
throw new Exception("Valid SortDirections are: asc, ascending, desc and descending");
}

comparers.Add(new GenericComparer { SortDirection = SortDirection, PropertyInfo = PropertyInfo, comparers = comparers });
}
list.Sort(comparers[0].Compare);
}
}

public class GenericComparer
{
public List comparers { get; set; }
int level = 0;

public SortDirection SortDirection { get; set; }
public PropertyInfo PropertyInfo { get; set; }

public int Compare(T t1, T t2)
{
int ret = 0;

if (level >= comparers.Count)
return 0;

object t1Value = comparers[level].PropertyInfo.GetValue(t1, null);
object t2Value = comparers[level].PropertyInfo.GetValue(t2, null);

if (t1 == null || t1Value == null)
{
if (t2 == null || t2Value == null)
{
ret = 0;
}
else
{
ret = -1;
}
}
else
{
if (t2 == null || t2Value == null)
{
ret = 1;
}
else
{
ret = ((IComparable)t1Value).CompareTo(((IComparable)t2Value));
}
}
if (ret == 0)
{
level += 1;
ret = Compare(t1, t2);
level -= 1;
}
else
{
if (comparers[level].SortDirection == SortDirection.Descending)
{
ret *= -1;
}
}
return ret;
}
}
----------------------------

Ex.


List objListPro = category.GetcategoryproductsByEmail(Membership.GetUser(Page.User.Identity.Name).Email.ToString());
objListPro .Sort("ID ascending");

------------------------------------------------


URL:
http://www.codeproject.com/Articles/27834/Generic-List-Sort-Function

Tuesday, March 27, 2012

.NET Performance Tips & Tricks

Introduction

.NET Application performance Tips and Tricks



Changes have to be Done in Web.Config and Mechine.config File
-------------------------------------------------------------

1.Set debug=false under compilation as follows:-



When you create the application, by default this attribute is set to "true" which is very useful while developing. However,when you are deploying your application, always set it to "false"

Setting it to "true" requires the pdb information to be inserted into the file and this results in a comparatively larger file and hence processing will be slow.


2. Turn off Tracing unless until required.

Tracing is one of the wonderful features which enable us to track the application's trace and the sequences. However, again it is useful only for developers and you can set this to "false" unless you require to monitor the trace logging.

Before you deploy your application, disable tracing and debugging. Tracing and debugging may cause performance issues. Tracing and debugging are not recommended while your application is running in production. You can disable tracing and debugging in the Machine.config and Web.config using the syntax below.
You can turn off tracing as follows:-










3. Turn off Session State, if not required.

ASP.NET Manages session state automatically. However, in case you dont require Sessions, disabling it will help in improving the performance.

You may not require seesion state when ur pages r static or whn u dont need to store infor captured in the page.

You can turn off session state as follows:-

sqlconnectionstring="data source=127.0.0.1;Trusted_Connection=no">

For doing it in Page wise

<%@ Page EnableSessionState="false" %>



Changes have to be Done when building .NET Application
----------------------------------------

4. Select the Release mode before making the final Build for your application. This option is available in the Top Frame just under the Window Menu option. By default, the Mode is Debug

There are several things happening when you Build/Re-Build applications in the Debug Mode. First of all, it creates an additional PDB File under your BIN directory. This holds all the Debug information.

Secondly, the Timeout is very high since you require higher time out frequency while debugging such that your process hangs on until you get to the exact break point where error is there.

So, selecting Release Mode will greatly improve the performance of the application when u deploy.


General Methods to improve the Performance of Web Application
-------------------------------------------------------------

5. Disable ViewState when not required.

6. Avoid Frequent round trips to the Database.
Calls made to Database can be quite expensive in terms of response time as well as resources and it can be avoided by using Batch Processing.

Make calls to Database as mininal as possible and make them last even lesser time. Use of DataAdapter wherever applicable is very useful since, it automatically opens and closes Connection whenever required and doesnt require user to explicitly open the connection.

A number of connections opened and not closed adequately can directly influence in performance slow down.

7. Avoid Throwing Exceptions. It is very expensive.

8. Use Caching to improve the performance of your application.

9. Use appropriate Authentication Mechanism.

The Authentication Mechanism you choose determines the cost associated with it and hence select the appropriate mechanism. An informal but useful order is as follows:-

Authentication Modes

1. None
2. Windows
3. Forms
4. Passport

10. Validate all Input received from the Users.
Use Client Side Validations as much as possible. However, do a check at the Server side too to avoid the infamous
Javascript disabled scenarios.

11. Use Finally Method to kill resources.
In your Try..Catch.. Block, always use the Finally method to close Open connections, Open DataReaders, Files and other resources such that they get executed independent of whether the code worked in Try or went to Catch.

12. The String and Stringbuilder Usage.
If you are initially creating a string say s = "Hello". Then you are appending to it as s = s + " World"; You are actually creating two instances of string in memory. Both the original as well as the new string will be stored in the memory. For that matter, all the activities you do to the string are stored in the memory as separate references and it must be avoided as much as possible.

Use StringBuilder which is very useful in these kind of scenarios. For the example above, using a StringBuilder as
s.Append(" World"); which only stores the value in the original string and no additional reference is created.


Eg:

String Action
--------------
string str="";
DateTime startTime = DateTime.Now;
Response.Write(("
Start time:" + startTime.ToString()));
int i;

for(i=0;i<20000;i++)
{
str += i.ToString()+ "
";
}

DateTime EndTime= DateTime.Now;
Response.Write(("
End time:" + EndTime.ToString()));

Out Put:

Start time:3/22/2006 10:23:44 AM
End time:3/22/2006 10:25:08 AM

The above code took 1 minutes and 24 Seconds to complete its operation


String Builder Action
---------------------
StringBuilder strbuilder = new StringBuilder();
DateTime startTime1 = DateTime.Now;
Response.Write(("
Start time:" + startTime1.ToString()));
int i1;

for (i1 = 0; i1 < 20000; i1++)
{
strbuilder.Append(i1 + "
");
}

DateTime EndTime1 = DateTime.Now;
Response.Write(("
End time:" + EndTime1.ToString()));

Out Put:

Start time:3/22/2006 10:25:08 AM
End time:3/22/2006 10:25:09 AM

The above code took 1 Seconds to complete its operation

13. Avoid Recursive Functions / Nested Loops

14. Enable Option Strict and Option Explicit for your pages.

15. Use early binding in Visual Basic or JScript code.

16. Use Response.Write for String concatenation:
Use the HttpResponse.Write method in your pages or user controls for string concatenation.
This method offers buffering and concatenation services that are very efficient. If you are performing
extensive concatenation, however, the technique in the following example, using multiple calls
to Response.Write, is faster than concatenating a string with a single call to the Response.Write method.

Response.Write("a");
Response.Write(myString);
Response.Write("b");
Response.Write(myObj.ToString());
Response.Write("c");
Response.Write(myString2);
Response.Write("d");


17. Avoid unnecessary round trips to the server:
Use Page.IsPostback to avoid extra work on a round trip.

• Implement Ajax UI whenever possible. The idea is to avoid full page refresh and only update the portion of the page that needs to be changed. I think Scott's article gave great information on how to implement Ajax Atlas and control.

• Use Client Side Scripts. Client site validation can help reduce round trips that are required to process user’s request. In ASP.NET you can also use client side controls to validate user input.

• Use Page.ISPostBack property to ensure that you only perform page initialization logic when a page first time loaded and not in response to client postbacks.

If Not IsPostBack Then
LoadJScripts()
End If

• In some situations performing postback event handling are unnecessary. You can use client callbacks to read data from the server instead of performing a full round trip.


18. Keep IO Buffer Size Between 4KB and 8KB
For nearly every application, a buffer between 4KB and 8KB will give you the maximum performance. For very specific instances, you may be able to get an improvement from a larger buffer (loading large images of a predictable size, for example), but in 99.99% of cases it will only waste memory. All buffers derived from BufferedStream allow you to set the size to anything you want, but in most cases 4 and 8 will give you the best performance

19. Minimize the Use of Format()
When you can, use toString() instead of format(). In most cases, it will provide you with the functionality you need, with much less overhead.

20. Optimize Assignments
Use exp += val instead of exp = exp + val. Since exp can be arbitrarily complex, this can result in lots of unnecessary work. This forces the JIT to evaluate both copies of exp, and many times this is not needed. The first statement can be optimized far better than the second, since the JIT can avoid evaluating the exp twice.

21. Include Return Statements with in the Function

22. Use For Loops for String Iteration

23. Explicitly Dispose or Close all the resources:

Try
_con.Open()
Catch ex As Exception
Throw ex
Finally
If Not _con Is Nothing Then
_con.Close()
End If
End Try

24. Precompiling pages and disabling AutoEventWireup:
By precompiled pages, users do not have to experience the batch compile of your ASP.NET files; it will increase the performance that your users will experience.

Also setting the AutoEventWireup attribute to false in the Machine.config file means that the page will not match method names to events and hook them up (for example, Page_Load). If page developers want to use these events, they will need to override the methods in the base class (for example, they will need to override Page.OnLoad for the page load event instead of using a Page_Load method). If you disable AutoEventWireup, your pages will get a slight performance boost by leaving the event wiring to the page author instead of performing it automatically.

Database
--------
1.Use the Optimal Managed Provider

2.Use Stored Procedures Whenever Possible

3.Use SqlDataReader Instead of Dataset wherevr it is possible

3.Turn Off Features You Don't Use
Turn off automatic transaction enlistment if it's not needed. For the SQL Managed Provider, it's done via the connection string:

SqlConnection conn = new SqlConnection("Server=mysrv01;Integrated Security=true;Enlist=false");

When filling a dataset with the data adapter, don't get primary key information if you don't have to (e.g. don't set MissingSchemaAction.Add with key):

public DataSet SelectSqlSrvRows(DataSet dataset,string connection,string query){
SqlConnection conn = new SqlConnection(connection);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(query, conn);
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(dataset);
return dataset;
}

4.Keep Your Datasets Lean
Only put the records you need into the dataset. Remember that the dataset stores all of its data in memory, and that the more data you request, the longer it will take to transmit across the wire.

5.Use Connection Pooling and Object Pooling


-------------------------------------------

URL:

http://www.codeproject.com/Articles/13258/NET-Performance-Tips-Tricks