Tuesday, April 30, 2013

[Resolved] JavaScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException


1. This below error occurs when your controls like button, image button etc is under the Ajax update panel and is not registered for postback.



2. In my case this issue gets generated on the button click which is inside the gridview <ItemTemplate> field. Hence OnPreRender property of the button i will call a codebehind method so as to register the button control  for postback.

    <asp:Button ID="Button1" runat="server" OnPreRender="RegisterButton_PreRender" Text="Button" />

3. Below is the method which i will call OnPreRender


protected void RegisterButton_PreRender(object sender, EventArgs e)
    {
        if (sender is Button)
        {
            Button MyButton = (Button)sender;
            this.ToolkitScriptManager1.RegisterPostBackControl(MyButton);
        }
    }

using jquery .slideToggle in asp.net


using jquery .slideToggle in asp.net

1. In this post i will show how to toggle between slide up and slide down.
For example :
if we click on a button a label is shown again we click on that button that label will go hidden,
This sequence of getting shown and hidden is known as Toggle. i.e. something which is getting on and off.

2. Iam going to take two scenarios here.

In one of the scenario i will show and hide a label control on the button click event.
while for another example i will show and hide a veritcal menu bar on the Panel header click.

3. Jquery slideToggle Syntax:

 $("#youControlID").slideToggle(Speed,easing,callback);

4.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="jquerySlideToggle.aspx.cs"
    Inherits="jquerySlideToggle" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.js"></script>
    <script type='text/javascript'>
        function FnMenu1() {
            $("#Menu").slideToggle("Fast");
        }

        function FnMenu2() {
            $("#Submenu").slideToggle("slow","linear");
        }

         
    </script>
</head>
<body>
    <form id="form1" runat="server">
    -------Example 1---------
    <br />
    <input id="Button2" type="button" onclick="FnMenu1()" value="button" />
    <div id="Menu" style="background-color: Red; width: 100px;">
        <asp:Panel ID="Panel1" runat="server" HorizontalAlign="Left">
            <table width="100%" cellpadding="0" cellspacing="0" border="1">
                <tr>
                    <td>
                        <asp:Label ID="Label1" runat="server" Text="Redemption"></asp:Label>
                    </td>
                </tr>
            </table>
        </asp:Panel>
    </div>
    <br />
    <br />
    -------Example 2---------
    <br />
    <div id="Menu2" style="background-color: White; width: 100px;">
        <asp:Panel ID="Panel2" runat="server" onClick="FnMenu2()" HorizontalAlign="Left">
            <table width="100%" cellpadding="0" cellspacing="0" border="1">
                <tr>
                    <td>
                        <asp:Label ID="Label3" runat="server" Text="Menu"></asp:Label>
                    </td>
                </tr>
            </table>
        </asp:Panel>
        <div id="Submenu" style="background-color: Aqua; width: 100px;">
            <table width="100%" cellpadding="0" cellspacing="0" border="0">
                <tr>
                    <td>
                        <asp:LinkButton ID="LinkButton1" runat="server">Sub menu 1</asp:LinkButton>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:LinkButton ID="LinkButton2" runat="server">Sub menu 2</asp:LinkButton>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:LinkButton ID="LinkButton3" runat="server">Sub menu 3</asp:LinkButton>
                    </td>
                </tr>
            </table>
        </div>
    </div>
    </form>
</body>
</html>

5.Run the project to get expected Final Result.






Monday, April 29, 2013

disable Enter Keyboard Button using Javascript.


In this post i will show how to disable Enter Keyboard Button using Javascript.

Below is the Javascript code we will be using. "Enter" keyboard button code is 13, Hence in the javascript code we will return false for keycode 13. Thus Event for Enter button would not get triggered.
We will call this function in the html body tag on the onkeydown property of it.


<script type="text/javascript">
        function disableEnter() {
            if (event.keyCode == 13) {
                return false;
            }
        }
    </script>




















After adding this javascript function run your project to get the expected output.



Bind XML Data to Dropdown control in asp.net


Lets see how to bind XML Data to Dropdown in asp.net

1. Add a dropdrown control into your markup page

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server">
        </asp:DropDownList>
     
    </div>
    </form>
</body>
</html>

2. Create XML Data file which will be used to bind the dropdownlist control.

<?xml version="1.0" encoding="utf-8" ?>

<Department>
  <Dept Text="--Select--" Value="0"></Dept>
  <Dept Text="IT" Value="1"></Dept>
  <Dept Text="Accounts" Value="2"></Dept>
  <Dept Text="HR" Value="2"></Dept>
</Department>

3.Now we will add XML Datasource for the dropdown control.
Go to Designer page add click on choose data source

1. Choose DataSource


2. Select XML File


3. Browse and select the XML File


4. Select Text and Value field

5. Check on Markup page, there you Should see XML Datasource control


6. Run the project and finally you should see Expected Result.

Note :
Do not use XML file with this below format as it wont work here. But It can be accessed by writing code for it in the codebehind.


<?xml version="1.0" encoding="utf-8" ?>
<Departments>
  <Dept>
    <DeptId>1</DeptId>
    <DeptName>IT</DeptName>
  </Dept>
  <Dept>
    <DeptId>2</DeptId>
    <DeptName>ACCOUNTS</DeptName>
  </Dept>
 <Dept>
    <DeptId>3</DeptId>
    <DeptName>HR</DeptName>
  </Dept>
</Departments>

Sunday, April 28, 2013

Disable Enter button in Jquery

In this post i will show how to disable Enter Keyboard Button using Jquery.

Below is the Jquery code. "Enter" keyboard button code is 13, Hence under if condition in the jquery code i have written if the keycode equals 13 it will return false and Enter Event would not get triggered.


 <script type="text/javascript">
        $("#form1").keypress(function (e) {
            if (e.keyCode == 13) {
                return false;
            }
        });
 </script>






1


2
3






Saturday, April 27, 2013

Call a code-behind method from javascript using pagemethods in asp.net

Lets see how to call a code-behind method from javascript using pagemethods.

1. Here i will be calling the codebehind method on the button click event.

2. In the form tag add the Scriptmanager and  button element.
On button "onClientClick" property i will call the JavaScript function and in that i will call the codebehind method.

To call a code behind method in the JavaScript function we need to prefix the code behind method name with "pagemethods.<your code behind method name>".

Below is the html markup code. Here CallJS() function will get called on the button click and under onSucceed() function i will display the message returned from the codebehind method and if there is any error while returning the message onError() will get called.



3. Now in the code behind page we will define the required method which has to be called. Just above the method name we will write "[System.Web.Services.WebMethod]" so that the method is available on the client side.

4.Now Run the project to get the expected result.


Thursday, April 25, 2013

MVC Demo using razor engine


MVC:
Model : All the operations related to fetching of data is handled here and also application state is maintained.
View: It the User Interface of an application.
Controller: All the web request are first accepted by the controller and also it acts as a intermediate to view and model. Controller decides what action has to be taken for all web requests.

Now lets create a sample MVC application:
1. Go to file –> New --> project –> select asp.net MVC 4 web application and click ok.
1


2. Enter name for your application. Select an Empty Project and then select view engine as razor. uncheck the create unit test project and then click ok.
3. Then after this go to solution explorer. Right click on controller and add controller. The name of the controller should be always anynameController, as in my case its HomeController.
Click on add and the HomeController.cs will get added to the controller folder of the application.

5. Now in models folder add one class file like in my case its Model1.cs and write this below code inside the class.
6. Again going back to the controller , change the namespace to as of models so that we can access properties of model class. Then describe method implementation for method Index(). After this build the application(This is compulsory) . Then Right click on index() and add view.
 7. This below window will get appear. The view name should be same as of the name of method index() in the controller. Select View engine as Razor and select create a strongly typed view and from drop-down select model class, then add.

8. In view we will display the empid and empname to the user whose value has been set in index() method inside the controller. As we are using RAZOR engine , @ symbol is used to describe a razor syntax.

 9. Now run the application it should the below output as shown below:
Protected by Copyscape Duplicate Content Detection Tool

Tuesday, April 23, 2013

SQL Optimization Techniques



1. Include Schema name along with the table name.
 
2. Make transaction as less as possible.

3. The DB cache should be ON.

4. While Using UNION try using UNION ALL statement wherever necessary as it works faster.
UNION ALL will not discard duplicate rows whereas UNION looks for Duplicate rows. Thus UNION ALL works faster.

5. Add SET NOCOUNT ON statement into your stored procedures to stop the message indicating the number of rows affected by a T-SQL statement.
It will reduce the network traffic.

6. Use Clustered Indexes, it will help in achieving index seek instead of a index scan.

7. Remove user-defined inline scalar functions as it works on row by row basis.

8. Using the DISTINCT clause will result in some performance degradation, you should use this clause only when it's necessary.

9. Use stored procedure instead of text queries. As stored procedure gets precompliled after its first execution.

10. Try using constraints as an alternative to triggers, whenever possible.
example : suppose if we are using instead of trigger while inserting data in table and raising error whenever the value of a column is greater than 100.
Here  instead of using a trigger we should use constraints.

11. Avoid cursors as it increases the execution time.

12. Less use of sub queries.

13. Try using CTE common table expression instead of using temp tables so as to avoid network overhead created while using temp variables.

14. Do not create Stored procedure name starting with prefix "sp_". As the master database consists of stored procedures names starting with "sp_" and
if your sp name and the sp in the master database is same your stored procedure will never get executed.
Other disadvantage is when a sp name with sp_ prefix is getting called then it will be first searched in the master database then into the actual Database.Thus taking more time for execution.

15. Using of sp_executesql can help where just the parameter values is getting changed , as the same execution plan is used again and again.

Protected by Copyscape Duplicate Content Detection Tool

validate email id and password in javascript



Below is the code to validate email id and the password field in javascript on Login button click.
After successful validation will redirect from login page to Home Page.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script language="javascript" type="text/javascript">

        function validate() {

            var useridlength = document.getElementById('EmailID').value.length;
            var passlength = document.getElementById('Pwd').value.length;

              if (useridlength == 0) {
                alert('Enter Email ID');
                return;

            }

            else if (passlength < 8) {
                alert('Password should be of 8 or more characters');
                return;
            }

            var email = document.getElementById('EmailID');
            var EmailExpression = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

            if (!EmailExpression.test(email.value)) {
                alert('Enter Proper Email ID');
                return;
            }

            else {
                window.location.href = "Home.aspx";// redirect page after login
            }
        }

    </script>

    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Email id:<input id="EmailID" type="text" /> <br />
        Password:<input id="Pwd" type="text" />
        <br />
        <input id="Button2" type="button" value="Login" onclick="validate()" />
        <br />
        <hr />
    </div>
    </form>
</body>
</html>


Protected by Copyscape Duplicate Content Detection Tool

Monday, April 22, 2013

Host WCF service to console application


Host WCF to console application:

1. After you have created your WCF application now lets see how to host it in a console application.

2. Go to New Project and select console application. Now Add your working WCF Project to the Console application. To add right click on the solution file of the console app and go to "add existing project" option.
After u add the project it should look like this.






















3. Right click on the console project and add reference of namespace System.servicemodel.




4. Now in the class file of the console application

add this below code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main()
        {
            Uri baseAddress = new Uri("http://localhost:8080/ServiceWCFApp");

            var host = new ServiceHost(
                typeof(Service1),
                baseAddress
                );

            host.AddServiceEndpoint(
                typeof(IService1),
                new BasicHttpBinding(),
                "http://localhost:8080/ServiceWCFApp/ServiceWCF");

                       
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                host.Description.Behaviors.Add(smb);
                host.Open();
                Console.WriteLine("The service is ready");
                Console.ReadLine();
                host.Close();
       

        }

    }
}



Note.: Make sure the namespace for all the project is the same.As in my case its "ConsoleApplication1".

5. Now run the project and in the console screen you should see the message as "The Service is Ready"



6. After this to check whether the service is hosted successfully or not.
Go to Visual studio 10 or 12 and then go to visual studio tools --> command prompt and type wcftestclient.exe and enter.

Go to file and add service, here copy the base address from the class file of the console app. click ok and test the hosted service.







Protected by Copyscape Duplicate Content Detection Tool

Sunday, April 21, 2013

Difference between Delete and Truncate

Difference between Delete and Truncate:


Delete  Truncate
1 Delete activates Triggers Truncate does not activates Triggers
2  It’s a DML Command It’s a DDL Command
3 Can be Roll-backed Cannot be Roll-backed
4 It is slower as compared to truncate Its is Faster
5 Can use Where clause in the delete command Cannot use Where clause in the truncate command
6 Each Table Row is locked while deleting Whole Table is Locked while performing truncate operation 
7 Maintains the identity of the column Does not maintain the identity of the column


Delete Command Maintains Identity of the Column

Protected by Copyscape Duplicate Content Detection Tool

Thursday, April 18, 2013

convert datetime to various date formats in sql

convert datetime to various date format using convert function in sql.

Suppose you have a date :
select getdate()

o/p: 2013-04-18 17:27:54.167

Now how to convert to various date format:

Example 1:

select getdate()
select CONVERT(VARCHAR(20),getdate(),100)
select CONVERT(VARCHAR(20),getdate(),101)
select CONVERT(VARCHAR(20),getdate(),103)
select CONVERT(VARCHAR(20),getdate(),106)
select CONVERT(VARCHAR(20),getdate(),110)
select CONVERT(VARCHAR(20),getdate(),112)

Example 2:

declare @date as datetime = '12-April-2013'
select @date
select CONVERT(VARCHAR(20),@date,100)
select CONVERT(VARCHAR(20),@date,101)
select CONVERT(VARCHAR(20),@date,103)
select CONVERT(VARCHAR(20),@date,106)
select CONVERT(VARCHAR(20),@date,110)
select CONVERT(VARCHAR(20),@date,112)


where 100,101,102 etc are the date format code.

for more date format codes refer.

Wednesday, April 17, 2013

Handle Session Timeout in an application and redirect to custom error page

How to Handle Session Timeout in an application and redirect to custom error page.

By Default the Session timeout occurs after 20 Mins. To change the Timeout value you can change it in the webconfig file of the application as <sessionstate timeout="30"/>


Public Sub issessionvalid()

        If IsNothing(Trim(Session("YourSessionKeyword"))) Or Trim(Session("YourSessionKeyword")) = "" Or  Trim(Session("YourSessionKeyword")).Length = 0 Then

            'Response.Write("<script>parent.location.href=('CustomErrorPage.aspx');</script>")
            'Response.Redirect("CustomErrorPage.asp")
            Response.Redirect("CustomErrorPage.aspx")

       End If
     
End Sub

Tuesday, April 16, 2013

Linkbuilding in SEO


In SEO Link-building is given major importance as most number of traffic is generated through link-building.  It comes under the off-page SEO techniques.

1.From where we can get back-links:
   a) Blog Posting
   b) Article Submission
   c) Directory Submission
   d) Forums
   e) Blog Commenting
   f) Social Media like Facebook, LinkedIn etc
   g) Press Release
   h) Paid Links


2. Always get back-links(link on other website redirecting to our website) from relevant websites. As it will give more value to your website. Getting back-links from irrelevant website will give a less values hence no chances of getting on search results first page.

3. Check the domain authority and  the page authority of the website where you will be doing link building.
If the domain and page authority of the website are high, then good values will be given to your website by the search engines as the back link is coming from high domain authority websites.
to check this go to opensiteexplorer.org and enter the URL of the website.

4. While doing link-building don't just copy the websites URL. Pay More attention to your targeted Keywords and include that keywords in the anchor text and in href add your website URL or the page of the targetted keyword.

<a href="www.myseocompany.com/seo"> SEO </a>

5. The maximum the number of traffic your getting through link building means the more link popularity.
And your website would get regularly crawled.

6. Getting back-links from sites relevant with your website is of more value other than getting back links from    some other different sources. i.e If your running a website on seo services and your getting back links from an restaurant website then search engines would give very less value to your website.

7. Link-building is important in SEO, as it will determine the popularity of your website which will indicate search engines that its good site and thus will play a major role during the ranking in search engine results.






Protected by Copyscape Duplicate Content Detection Tool

Monday, April 15, 2013

SQL User Defined Functions

Sql User Defined Functions(UDF) was introduced with SQL Server 2000.
Sql User Defined Functions returns single value or table and it can accept max of 1024 parameters or min of zero parameters.

We can use this functions in SELECT , WHERE AND CASE clause.


Advantages of using UDF(User Defined Functions)

1. Make Sql code less complex.
2. Execution is Faster.
3. Create Less Network Traffic.
4. Can be used where we want to do perform repeated tasks on some data.

Disadvantages:

1. Stored procedures cannot be called inside a function.
2. Temporary tables cannot be used.
3. Transaction Statements cannot be used.

Types of User Defined functions in SQL :


1. Scalar Function

This returns a single value. That can be of datatype int, varchar etc

Example of Scalar Function:

create function AddNumbers(@num int, @num2 int) returns int
as
begin
 declare @result int
   set @result = @num + @num2
 return @result
end

Now lets call the function:

select AddNumbers(10,10) --> this will throw error when u call , to resolve this add schema name along with the function name i.e. dbo.AddNumbers

select dbo.AddNumbers(10,10) 



2. Inline Table User Defined Function

This type of function returns a table. Such function are used where we want to do some reapeadted tasks on a table.

Example:
First create a sample employee table.


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Employee](
[EmpDeptID] [int] NULL,
[EMpName] [varchar](100) NULL,
[salary] [numeric](18, 0) NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
INSERT [dbo].[Employee] ([EmpDeptID], [EMpName], [salary]) VALUES (2, N'Peter', CAST(5000 AS Numeric(18, 0)))
GO
INSERT [dbo].[Employee] ([EmpDeptID], [EMpName], [salary]) VALUES (3, N'Peter', CAST(100 AS Numeric(18, 0)))
GO
INSERT [dbo].[Employee] ([EmpDeptID], [EMpName], [salary]) VALUES (24, N'Mary', CAST(5000 AS Numeric(18, 0)))
GO
INSERT [dbo].[Employee] ([EmpDeptID], [EMpName], [salary]) VALUES (6, N'Anthony', CAST(500 AS Numeric(18, 0)))
GO
INSERT [dbo].[Employee] ([EmpDeptID], [EMpName], [salary]) VALUES (5, N'Jacob', CAST(1000 AS Numeric(18, 0)))
GO
INSERT [dbo].[Employee] ([EmpDeptID], [EMpName], [salary]) VALUES (3, N'Peter', CAST(5000 AS Numeric(18, 0)))
GO
INSERT [dbo].[Employee] ([EmpDeptID], [EMpName], [salary]) VALUES (0, N'Jacob', CAST(1500 AS Numeric(18, 0)))
GO
INSERT [dbo].[Employee] ([EmpDeptID], [EMpName], [salary]) VALUES (2, N'Peter', CAST(4500 AS Numeric(18, 0)))
GO



Create function returnTbl(@Salary int) returns table
as
return
select * from employee where salary > @salary

Call returnTbl function:
select * from dbo.returnTbl(2000)



3. Multi Statement Table valued User defined Function

This function too returns a table. But here we can perform other DML operations i.e Insert,delete,update other than using Select on the locally defined table variable.

Example:

Create function MultiFuncDemo(@flag int) returns @tbl table(empname varchar(50), salary numeric)
as 
begin
  if @flag = 0 
     insert into @tbl
     select EMpName,salary from employee
 else
     insert into @tbl
      select 'No Data found',0000
return 
end

call MultiFuncDemo Function:
select * from dbo.MultiFuncDemo(0)


Subscribe in a reader
Protected by Copyscape Duplicate Content Detection Tool

how to export gridview data to Excel in Asp.net


1. First i will bind data to grid and then will export the grid data to excel on Export To Excel Button Click.

This below code i have written on the page_load


  protected void Page_Load(object sender, EventArgs e)
    {


         string conStr = ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionString.ToString();
        SqlConnection s1 = new SqlConnection(conStr);
        s1.Open();

        string queryString = "SELECT * FROM employee";
        SqlDataAdapter adapter = new SqlDataAdapter(queryString, s1);

        DataSet employee = new DataSet();
        adapter.Fill(employee, "employee");

        s1.Close();

        GridView1.DataSource = employee.Tables[0];
        GridView1.DataBind();

}
Employee Data in Gridview

2. Now on export to excel button click i will call the method to export data into excel.

add Namespace : using System.IO;


      Protected void ExportToExcel_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/vnd.ms-excel";
        Response.Charset = "";
        Response.AppendHeader("content-disposition", "attachment; filename=DemoExcel.xls");
        System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
     
        GridView1.RenderControl(oHtmlTextWriter);
        Response.Write("<TABLE><TR><TD></TD><TD></TD><TD></TD><TD></TD><TD colspan=3 align=\"center\"><B>" + "Employee List" + "</B></TD></TR>".ToString());
        Response.Write("<TR><TD></TD><TD colspan=3><br><br></TD></TR></TABLE>".ToString());
        Response.Write(oStringWriter.ToString());
        Response.End();

    }

I got this error below when i called the method to export the data to excel on button click:

















To resolve this above error i used this following code and added it inside the class:

public override void VerifyRenderingInServerForm(Control control)
    {
        return;
    }





3. Now Run Your project and click on export to excel button to get the data in excel :




Delete Duplicate Rows In SQL


1. To delete duplicate records from a table having no identity column in it.

lets take an example to implement this:

create table Employee
(
EmpDeptID int,
EMpName varchar(100),
salary numeric
)

insert into Employee values(2,'Peter',5000)
insert into Employee values(3,'Peter',100)
insert into Employee values(24,'Mary',5000)
insert into Employee values(6,'Anthony',500)
insert into Employee values(5,'Jacob',1000)
insert into Employee values(3,'Peter',5000)
insert into Employee values(0,'Jacob',1500)
insert into Employee values(2,'Peter',4500)

select * from employee

Now we will delete the duplicate rows using this below query :

;with getdata as
(
select *,ROW_NUMBER() OVER(partition by EMpName ORDER BY EmpDeptID ) as UniqueCol from employee 
)
delete from getdata where UniqueCol > 1


I deleting duplicate rows Using CTE. i.e Common Table Expression.

Another way of deleting the duplicate records without using CTE :

delete test from 
(select *,ROW_NUMBER() OVER(partition by EMpName ORDER BY EmpDeptID ) as UniqueCol from employee) test 
where UniqueCol > 1


2. Now lets take an example for a table having an identity column in it.

Here, we can use the above two queries. But there is also an another way of deleting records for a table having identity column.

create table EmployeeIdentity
(
EmpDeptID int identity,
EMpName varchar(100),
salary numeric
)


insert into EmployeeIdentity(EMpName,salary) values('Peter',5000)
insert into EmployeeIdentity(EMpName,salary) values('Peter',100)
insert into EmployeeIdentity(EMpName,salary) values('Mary',5000)
insert into EmployeeIdentity(EMpName,salary) values('Anthony',500)
insert into EmployeeIdentity(EMpName,salary) values('Jacob',1000)
insert into EmployeeIdentity(EMpName,salary) values('Peter',5000)
insert into EmployeeIdentity(EMpName,salary) values('Jacob',1500)
insert into EmployeeIdentity(EMpName,salary) values('Peter',4500)


select * from EmployeeIdentity

Query to delete duplicate records:

--For Tables with Identity Coloumns:

delete from EmployeeIdentity where EmpDeptID not in
 (select min(EmpDeptID) from EmployeeIdentity group by Empname)




Saturday, April 13, 2013

WCF creation and consuming in to an application example

//WCF Demo Application 
Goto : File --> New Project --> WCF --> WCF service Application
Give a name to your WCF application and Click on OK :

1. Goto Solution Explorer open service1.svc.cs . if u want u can rename the file. Here we will declare the methods signature in the interface.


code :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService1

{
   /*In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does.
   WCF defines four types of contracts:
   ==> Data Contracts
   ==> Fault Contracts
   ==> Message Contracts
   ==> Service Contracts
   Service contracts :
   1.Describe which operations the client can perform on the service.
 
     There are two types of Service Contracts :
     1.ServiceContract - This attribute is used to define the Interface.
     2.OperationContract - This attribute is used to define the method inside Interface.
   */

    [ServiceContract]

    public interface IService1
    {
        [OperationContract]
        int addNumbers(int number1, int number2);
    }
}

2. Now after defining the interface we will go the IService1.cs file and will write the method implementation for the defined method signatures.

//Describe method for addnumbers(int number1, int number2 ) in IService1.cs

using System;

using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService1

{
    public class Service1 : IService1
    {
        public int addNumbers(int number1, int number2)
        {
            return (number1 + number2);
        }
    }
}



3. Build the application and check if there is no error. Now run the application and you should get this below screen. Here we can test our service by entering the values and checking the desired result. thus we can check that our WCF service is working correctly or not. Now will see how to consume this WCF service in our application.



4. I'm taking a console application where i will consume this service.

To add a service in to our application we need to have the URL of the service. Now go back to your WCF application and copy the address i.e the URL of the application as shown in below image.

Please note we need to keep running the WCF project if we want to consume the service in our application or else host WCF application into IIS.



Now in our main application in the solution explorer right click on the project and click on add service reference.




5. Add the copied URL in the service reference window and click on Go









Give whatever name you like to the service and then click on OK.


6.  Create the object for the service added and call the addNumbers Method. Now Run the Project and check the result !!!








Protected by Copyscape Duplicate Content Detection Tool