Monday, 25 June 2012

Find version of sqlserver


select @@version

ajaxcascading dropdown


Client
 <%@ register namespace="AjaxControlToolkit" assembly="AjaxControlToolkit" tagprefix="ajax" %>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <asp:ScriptManager ID="scriptmanager1" runat="server">
        </asp:ScriptManager>
        <div>
            <table>
                <tr>
                    <td>
                        Select Country:
                    </td>
                    <td>
                        <asp:DropDownList ID="ddlcountry" runat="server">
                        </asp:DropDownList>
<ajax:CascadingDropDown ID="ccdCountry" runat="server" Category="Country" TargetControlID="ddlcountry"
PromptText="Select Country" LoadingText="Loading Countries.."       ServiceMethod="BindCountryDetails"
                            ServicePath="CascadingDropdown.asmx">
                        </ajax:CascadingDropDown>
                    </td>
                </tr>
                <tr>
                    <td>
                        Select State:
                    </td>
                    <td>
                        <asp:DropDownList ID="ddlState" runat="server">
                        </asp:DropDownList>
   <ajax:CascadingDropDown ID="ccdState" runat="server"  Category="State" ParentControlID="ddlcountry"
TargetControlID="ddlState" PromptText="Select State"    LoadingText="Loading States.."
           ServiceMethod="BindStateDetails" ServicePath="CascadingDropdown.asmx">
                        </ajax:CascadingDropDown>
                    </td>
                </tr>
            </table>
        </div>
        </form>
    </body>
    </html>


Webservice
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using AjaxControlToolkit;


/// <summary>
/// Summary description for CascadingDropdown
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class CascadingDropdown : System.Web.Services.WebService
{
//Database connection string
private static string strconnection = ConfigurationManager.AppSettings["ConnectionString"].ToString();
//database connection
SqlConnection concountry = new SqlConnection(strconnection);
public CascadingDropdown () {

//Uncomment the following line if using designed components
//InitializeComponent();
}
/// <summary>
/// WebMethod to Populate COuntry Dropdown
/// </summary>
[WebMethod]
public CascadingDropDownNameValue[] BindCountryDetails(string knownCategoryValues,string category)
{
concountry.Open();
SqlCommand cmdcountry = new SqlCommand("select * from Country", concountry);
cmdcountry.ExecuteNonQuery();
SqlDataAdapter dacountry = new SqlDataAdapter(cmdcountry);
DataSet dscountry = new DataSet();
dacountry.Fill(dscountry);
concountry.Close();
//create list and add items in it by looping through dataset table
List<CascadingDropDownNameValue> countrydetails = new List<CascadingDropDownNameValue>();
foreach(DataRow dtrow in dscountry.Tables[0].Rows)
{
string CountryID = dtrow["CountryID"].ToString();
string CountryName = dtrow["CountryName"].ToString();
countrydetails.Add(new CascadingDropDownNameValue(CountryName, CountryID));
}
return countrydetails.ToArray();
}
/// <summary>
/// WebMethod to Populate State Dropdown
/// </summary>
[WebMethod]
public CascadingDropDownNameValue[] BindStateDetails(string knownCategoryValues,string category)
{
int countryID;
//This method will return a StringDictionary containing the name/value pairs of the currently selected values
StringDictionary countrydetails =AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
countryID = Convert.ToInt32(countrydetails["Country"]);
concountry.Open();
SqlCommand cmdstate = new SqlCommand("select * from State where CountryID=@CountryID", concountry);
cmdstate.Parameters.AddWithValue("@CountryID", countryID);
cmdstate.ExecuteNonQuery();
SqlDataAdapter dastate = new SqlDataAdapter(cmdstate);
DataSet dsstate = new DataSet();
dastate.Fill(dsstate);
concountry.Close();
//create list and add items in it by looping through dataset table
List<CascadingDropDownNameValue> statedetails = new List<CascadingDropDownNameValue>();
foreach (DataRow dtrow in dsstate.Tables[0].Rows)
{
string StateID = dtrow["StateID"].ToString();
string StateName = dtrow["StateName"].ToString();
statedetails.Add(new CascadingDropDownNameValue(StateName, StateID));
}
return statedetails.ToArray();
}


need to write webmethods this format only

In More Detail



Drop Time in DateTime-SQL


SELECT DATEADD(dd, DATEDIFF(d, 0, Getdate()), 0)

Result
2012-06-25 00:00:00.000

Determine No of users connected to sqlserver database


select spid, status, loginame, hostname, blocked, db_name(dbid),
cmd from master..sysprocesses where db_name(dbid) = 'IMarque_db'
and spid>50

Find Index on a table


sp_helpindex 'tablename'

Friday, 22 June 2012

Invalid postback or callback argument. Event validation is enabled using in configuration..


Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

Solution
          <%@ Page EnableEventValidation="false" %>



Encrypt or Decrypt Connection Strings in web.config file using ASP.NET in IIS


In Command Prompt, Goto this location and type that command
C:\Windows\Microsoft.Net\Framework\v2.0.50727
(this v2.0.50727 folder contains  aspnet_regiis.exe )

Encrypt connectionStrings  in web.config of IIS based site:
aspnet_regiis.exe -pe "connectionStrings" –app "/SampleWebSite”

Decrypt connectionStrings in web.config of IIS based site:
aspnet_regiis.exe -pd "connectionStrings" –app "/SampleWebSite

Thursday, 21 June 2012

WCF - Proxy

To enable proxy in wcf


Find Proxy Address
IE ->Tools->internet options->Connections->LAN Settings
Proxy Sever
Address:
Port:


<system.net>
    <defaultProxy  useDefaultCredentials="true">
      <proxy bypassonlocal="True" proxyaddress="http://[proxy address]:[proxy port]"/>
    </defaultProxy>

Monday, 18 June 2012

Sys.ParameterCountException: Parameter count mismatch.


I used AutocompleteExtender within update panel and used contextKey to pass additional parameter.
That time i received this error

I have set ScriptMode="Release" in ScriptManager. Default Value is Auto. 
It solved the my problem. You can also used auto for the same but you have to set When retail is set to true, ASP.NET disables certain configuration settings such as trace output, custom errors, and debug capabilities.I have just set retail = true.So you can use ScriptMode= Auto.

Friday, 15 June 2012

AJAX AutoCompleteExtender: Pass Additional Parameter using ContextKey


<cc1:AutoCompleteExtender ServiceMethod="SearchCustomers" MinimumPrefixLength="2"
        CompletionInterval="100" EnableCaching="false" CompletionSetCount="10" TargetControlID="txtContactsSearch"
        UseContextKey="true" ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false">
    </cc1:AutoCompleteExtender>

<asp:TextBox ID="txtContactsSearch" runat="server" onkeyup = "SetContextKey()"></asp:TextBox>

javascript



<script type="text/javascript">
function SetContextKey()  {
      $find('AutoCompleteExtender1').set_contextKey($get("<%=ddlCountries.ClientID%>").value);
}
</script>


c#

[System.Web.Script.Services. ScriptMethod ()]
[System.Web.Services. WebMethod]
public static List<string> SearchCustomers(string prefixText, int count, string contextKey)
{
        //do something

}






Highlight selected row when onclick javascript


C#
    e.Row.Attributes.Add("onclick""onGridViewRowClick(this);");   


Javascript:

       // highlight selected row javascript
        function onGridViewRowClick(row) {
            var table = document.getElementById("grid");
            for (var i = 1; i < table.rows.length - 1; i++) {
                if (i % 2 != 1) {
                    table.rows[i].className = 'gvRowStyle';
                }
                else {
                    table.rows[i].className = 'gvAlternatingRowStyle';
                }
            }
           // highlight selected row
            row.className = 'gvonclickstyle';
        }


Thursday, 14 June 2012

C# Null Coalescing Operator


The C# Null Coalescing Operator (??)  is a binary operator that simplifies checking for null values. 

Eg:
X??y

While executing code, if x evaluates to null, y is returned as the value. Also remember that the
 null coalescing operator (??) is right-associative which means it is evaluated from right to left. So if you have an expression of the form x ?? y ?? z, this expression is evaluated as x?? (y?? z).


Eg:
int? a = 0;
int b = a ?? 0;

Answer b=0

int? a = 6;
int b = a ?? 0;

Answer b=6

While executing code, if a evaluates to null, b is returned as the value. 



Get Datasource,Username,Password from Connection String


string conString = "SERVER=localhost;DATABASE=db;UID=root;PASSWORD=test;";
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(conString);
                string user = builder.UserID;
                string pass = builder.Password;
                string datasource = builder.DataSource;

Add New column with default value in existing table


  System.Data.DataColumn newColumn = new System.Data.DataColumn("columnName", typeof(System.String));
newColumn.DefaultValue = "Your DropDownList value";
table.Columns.Add(newColumn);

Monday, 11 June 2012

The maximum message size quota for incoming messages (65536) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element.

I got this error
"The maximum message size quota for incoming messages (65536) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element."
when i received data from the server.
for this problem i set MaxReceivedMessageSize in my client side.


<wsHttpBinding>
    <binding name="test" closeTimeout="00:01:00" openTimeout="00:01:00"
     receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false"
     transactionFlow="false" hostNameComparisonMode="StrongWildcard"
     maxBufferPoolSize="524288" maxReceivedMessageSize="2147483647" messageEncoding="Text"
     textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
(or)


WSHttpBinding binding = new WSHttpBinding();
            binding.MaxReceivedMessageSize = 2147483647;
            EndpointAddress endpointAddress = new EndpointAddress("http://localhost:59167/Service1.svc");
            ServiceReference1.Service1Client sc = new ServiceReference1.Service1Client(binding,endpointAddress);

Hope this helps.

Wednesday, 6 June 2012

short cut for show desktop

shortcut for show desktop - windows+D
Visual Studio
Ctrl-.[dot  Display options on smarttag menu.
                  Very useful for showing using/Imports options.

Ctrl+k Ctrl+D Format source code 


http://www.dofactory.com/ShortCutKeys/ShortCutKeys.aspx

ClientScript.RegisterStartupScript+ navigating to another page + while pressing back button alert


 ClientScript.RegisterStartupScript(this.GetType(), "script", "alert('hello !');__doPostBack('__Page', 'EmptyPostback');", true);


To avoid alert message using RegisterStartupScript  while click on browser back button.


When we register the startup script with the alert, immediately follow the alert statement with one which will refresh the page. This ensures that the startup script is removed from the page as soon as the OK is clicked, and if the user returns to the page the alert pop up does not reappear.

Tuesday, 5 June 2012

debug javascript using IE


First thing is to make sure the Internet Explorer breaks for the JavaScript. By default, the script debugging is disabled in IE. To enable this, go to: Tools - Internet Options - Advanced (the Advanced tab in Internet Option dialog box) Under the ’Browsing’ section, uncheck the following item: Disable Script Debugging (Internet Explorer)
With the script debugging enabled, Visual Studio will now step through the JavaScript code as well. If the asp.net application you are debugging has any global JavaScript code, pressing F11 to start the program will break the execution at the very first line of the JavaScript code. From there on, if you keep pressing F11, you will be able to step through every line in the application.

eg:
<script type="text/javascript">
function test()
{
        debugger;
        alert('debugging');
}
    </script>

Table valued parameters sql server 2008


In SQL Server 2005 and earlier, it is not possible to pass a table variable as a parameter to a stored procedure. When multiple rows of data to SQL Server need to send multiple rows of data to SQL Server, developers either had to send one row at a time or come up with other workarounds to meet requirements. While a VB.Net developer recently informed me that there is a SQLBulkCopy object available in .Net to send multiple rows of data to SQL Server at once, the data still can not be passed to a stored proc.
Possibly the most anticipated T-SQL feature of SQL Server 2008 is the new Table-Valued Parameters. This is the ability to easily pass a table to a stored procedure from T-SQL code or from an application as a parameter.

User-Defined Table Type

When first taking a look at the new table-valued parameters, I thought that using this feature is a bit complicated. There are several steps involved. The first thing to do is to define a table type. If you look at the Types section under Programmability in the 2008 Management Studio, you will see the new “User-Defined Table Types” (Image 1).
Image 1
Image 1
At the time of this writing, RC0 is the latest release of SQL Server 2008, and the only way to create this new object is with a T-SQL script. I’m not sure it this will change with the released version, known as RTM, but it is not difficult to create the type. I found that there is a right-click option “New User-Defined Table Type…” that creates a template in the Query Window shown in Image 2.
Image 2
Image 2
By clicking the “Specify Values for Template Parameters” button, a dialog box pops up that will help complete the definition. Image 3 shows the dialog box after some of the values have been modified.
Image 3
Image 3
After filling in the appropriate values and clicking OK, a CREATE TYPE statement replaces the template. At this point, additional columns and constraints can be added before clicking OK. Here is the code that was generated:
-- ================================
-- Create User-defined Table Type
-- ================================
USE Test
GO

-- Create the data type
CREATE TYPE dbo.MyType AS TABLE 
(
 col1 int NOT NULL, 
 col2 varchar(20) NULL, 
 col3 datetime NULL, 
    PRIMARY KEY (col1)
)
GO

After running the code, the object definition is created and viewable in the “User-Defined Table Type” section (Image 4). You can view the properties there, but not modify them. To modify the type, you will have to drop it and then create it again with the modified definition.
Image 4
Image 4

Using the User-Defined Table Type

So far, it seems like we have done quite a bit of work, but we only have the type definition created. Like other programmable objects, it will stick around unless it is dropped. To use it in T-SQL code, you must create a variable of the new type and then populate it as you would any other table. Once it is populated, you can use it in other T-SQL statements. Because it is a variable, it goes out of scope automatically when the batch is completed. Notice in the code below that the name of the data type is the same as the type we just created.
DECLARE @MyTable MyType

INSERT INTO @MyTable(col1,col2,col3)
VALUES (1,'abc','1/1/2000'),
 (2,'def','1/1/2001'),
 (3,'ghi','1/1/2002'),
 (4,'jkl','1/1/2003'),
 (5,'mno','1/1/2004')
 
SELECT * FROM @MyTable 
As long as the variable does not go out of scope, you can do just about anything with it that you can do with a regular table variable, such as join another table or be used to populate another table. Like a table variable, you can not modify the table definition.
As I mentioned, the variable is gone once it goes out of scope. For example if you have a T-SQL script that is composed of more than one batch, the variable is only valid within the batch where it was created.

Using the Variable as a Parameter

So far, we haven’t seen anything that is not possible with a regular table variable. The benefit is being able to pass the variable of the new type to a stored procedure. A stored procedure must be created that uses the new type. Here is an example of that along with the code to create a regular table that we will be populating.
USE [Test]
GO

CREATE TABLE [dbo].[MyTable] (
 [col1] [int] NOT NULL PRIMARY KEY,
 [col2] [varchar](20) NULL,
 [col3] [datetime] NULL,
 [UserID] [varchar] (20) NOT NULL
 ) 

GO

CREATE PROC usp_AddRowsToMyTable @MyTableParam MyType READONLY,
 @UserID varchar(20) AS
 
 INSERT INTO MyTable([col1],[col2],[col3],[UserID])
 SELECT [col1],[col2],[col3],@UserID 
 FROM @MyTableParam
 
GO
Notice the READONLY qualifier after the table parameter. This is required because a copy of the user-defined table variable is not passed to the procedure. To be more efficient, a pointer is passed to the proc. Therefore, to eliminate changes to the variable inside the proc that would affect the original, no changes are allowed.
Finally, let’s put it all together and call the stored procedure. In the next code snippet, code from the previous section is used to create and populate the variable.
DECLARE @MyTable MyType

INSERT INTO @MyTable(col1,col2,col3)
VALUES (1,'abc','1/1/2000'),
 (2,'def','1/1/2001'),
 (3,'ghi','1/1/2002'),
 (4,'jkl','1/1/2003'),
 (5,'mno','1/1/2004')

EXEC usp_AddRowsToMyTable @MyTableParam = @MyTable, @UserID = 'Kathi'

SELECT * FROM MyTable
In order for a user to use the User-Defined Table Type, EXECUTE or CONTROL permission must be granted. This is the command to grant permission to a user:
GRANT EXECUTE ON TYPE::dbo.MyType TO TestUser;

Calling from a .Net Application

The coolest way to use the table-valued parameter is from a .Net application. To do so, you need to have .NET 3.5 installed and make sure you are using the System.Data.SQLClient namespace. This gives you a new SQL data type called Structured that you will use when creating the parameter.
First create a local DataTable and populate it. Be sure that the DataTable that you create matches the user-defined table type’s column count and data types.
'Create a local table
Dim table As New DataTable("temp")
Dim col1 As New DataColumn("col1", System.Type.GetType("System.Int32"))
Dim col2 As New DataColumn("col2", System.Type.GetType("System.String"))
Dim col3 As New DataColumn("col3", System.Type.GetType("System.DateTime"))
table.Columns.Add(col1)
table.Columns.Add(col2)
table.Columns.Add(col3)
        
'Populate the table
For i As Integer = 20 To 30
    Dim vals(2) As Object
    vals(0) = i
    vals(1) = Chr(i + 90)
    vals(2) = System.DateTime.Now
    table.Rows.Add(vals)
Next
Since we will be working with a stored proc, create a command object and add the two parameters. This code assumes that you have an open connection to your test database.
'Create a command object that calls the stored proc
Dim command As New SqlCommand("usp_AddRowsToMyTable", conn)
command.CommandType = CommandType.StoredProcedure

'Create a parameter using the new type
Dim param As SqlParameter = command.Parameters.Add("@MyTableParam", SqlDbType.Structured)
command.Parameters.AddWithValue("@UserID", "Kathi")
Notice the data type of the @MyTableParam parameter. This is the new type added with .Net 3.5 to work with this new functionality. Finally, assign the local table to the parameter and execute the command.
'Set the value of the parameter
param.Value = table

'Execute the query
command.ExecuteNonQuery()