Wednesday, September 25, 2013

linq using Store Procedure

Add class……

using System;
using System.Data.Linq;
using System.Data.Linq.Mapping;

[Table(Name="student")]
public class E_modal
{
    [Column(Name = "roll_no", IsPrimaryKey = true)]
    public int rno { get; set; }

    [Column(Name = "stud_name")]
    public string sn { get; set; }

    [Column(Name = "stud_course")]
    public string sc { get; set; }

    [Column(Name = "stud_fees")]
    public int sf { get ;set; }
      
}

.aspx page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Linq;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        DataContext d = new DataContext("initial catalog=batch4;data source=dev-pc;integrated security=yes");
       Table< E_modal > e1= d.GetTable< E_modal >();
       GridView1.DataSource = e1;
       GridView1.DataBind();
    }
}


 

Using stored procedure


Add class EM<ENTITY MODAL>
using System;
using System.Data.Linq;
using System.Data.Linq.Mapping;

[Table(Name = "student")]
public class EM
{
    [Column(Name = "roll_no", IsPrimaryKey = true)]
    public int rno { get; set; }

    [Column(Name = "stud_name")]
    public string sn { get; set; }

    [Column(Name = "stud_course")]
    public string sc { get; set; }

    [Column(Name = "stud_fees")]
    public int sf { get; set; }

}

ADD CLASS DAL
using System;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Reflection;

public class DAL : DataContext
{
    public DAL(string x)
        : base(x)
    {

    }
    [Function(Name = "s_show")]
    public ISingleResult<EM> show()
    {
        IExecuteResult res = this.ExecuteMethodCall(this, (MethodInfo)MethodInfo.GetCurrentMethod());
        ISingleResult<EM> s = (ISingleResult<EM>)res.ReturnValue;
        return s;
    }

}


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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        DAL d = new DAL("initial catalog=batch4;data source=dev-pc;integrated security=yes");
        GridView1.DataSource = d.show();
        GridView1.DataBind();
    }
}




[3/29/2010 7:52:12 PM] sandeep karan: http://msdn.microsoft.com/en-us/library/ms998549.aspx
[3/29/2010 9:15:56 PM] sandeep karan: using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using System.Data.Linq;
using System.Data.Linq.Mapping;     

public class Class2:DataContext
{
 public Class2(string c):base(c)

 {
 
 }
    [Function(Name="sel_prod")]
    public ISingleResult<Class1> show()
    {
      IExecuteResult res=this.ExecuteMethodCall(this,(MethodInfo)MethodInfo.GetCurrentMethod());
      ISingleResult<Class1> s = (ISingleResult<Class1>)res.ReturnValue;
      return s;
    }
}
[3/29/2010 9:20:01 PM] sandeep karan: using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Data.Linq;
using System.Data.Linq.Mapping;

public class DAL:DataContext
{
    public DAL(string connection)
        : base(connection)
    {

    }


    [Function(Name="usp_SelectCustomer")]
    public ISingleResult<st>  getdata()
    {
       IExecuteResult obj=this.ExecuteMethodCall(this, (MethodInfo)MethodInfo.GetCurrentMethod());
       ISingleResult<st> ret=(ISingleResult<st>)obj.ReturnValue;
       return ret;
    }
    [Function(Name = "customerbyid")]
    public ISingleResult<st> getdataid([Parameter(Name = "cid", DbType = "Int")] System.Nullable<int> id)

    {
        IExecuteResult obj = this.ExecuteMethodCall(this, (MethodInfo)MethodInfo.GetCurrentMethod(),id);
        ISingleResult<st> ret = (ISingleResult<st>)obj.ReturnValue;
        return ret;
    }
   
    [Function(Name = "insertc")]
    public int InsertCustomer([Parameter(Name = "Cid", DbType = "Int")]
 int  CustId, [Parameter(Name = "Cname",DbType = "nvarchar(20)")]string custname)
    {
        IExecuteResult result = this.ExecuteMethodCall(this,
        ((MethodInfo)(MethodInfo.GetCurrentMethod())), CustId, custname);
        return (int)result.ReturnValue;
    }
}


transport layer security

// transport layer security -client side

ServiceReference1.ServiceClient s = new ServiceReference1.ServiceClient();
s.ClientCredentials.UserName.UserName = "windows";
s.ClientCredentials.UserName.Password = "omomsandeepkaran";
Response.Write(s.GetData()); 

// web config

<system.serviceModel>

<bindings>
    <wsHttpBinding>
       <binding name ="narang">
        <security mode ="Transport">
          <transport clientCredentialType ="Basic">

          </transport>
       </security>
      </binding>
     </wsHttpBinding>
</bindings>

<services>

<service name="Service" behaviorConfiguration="ServiceBehavior">
<!-- Service Endpoints -->
<endpoint address="" binding="wsHttpBinding" bindingConfiguration ="narang" contract="IService">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the identity under which the deployed service runs. If removed, WCF will infer an appropriate identity automatically.
-->
<identity>
   <dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

==========================
//Transport layer security 
<wsHttpBinding>
<binding name ="narang">
<security mode ="Transport">
<transport clientCredentialType ="Basic">

</transport>
</security>
</binding>
</wsHttpBinding>
// Attach with EndPoint
<endpoint address="" binding="wsHttpBinding" bindingConfiguration ="narang" contract="IService">

step-2

Go to IIS --create certificate

step-3
Add HTTPS and assign ceritificate name

step-4 netsh http show sslcert
netsh http delete sslcert ipport=0..0.0.0:8080

netsh http add sslcert ipport=0.0.0.0:8080 certhash=2b626efa63a083bbf868d2b8dfc2bcab263d9857 appid={4B04E6AD-E432-40EB-9A11-9081F5DDEC88}

Tuesday, September 24, 2013

ASP.NET provides a few ways to move to different pages


Two approaches to redirection in ASP.NET

The user may initiate the transfer to another page any number of ways, including clicking a button or link or selecting a value in a drop-down list. ASP.NET provides a few ways to move to different pages.


Client vs. server

A key aspect of the various ways to send a user to another page within an ASP.NET application is where the transfer occurs; that is, it is handled within the client browser or on the Web server. The following list outlines two options for controlling page navigation.

Response.Redirect: The Redirect method of the Response object provides a way to implement client-side redirection.
Server.Transfer: The Transfer method of the Server object performs redirection using the server and avoiding HTTP requests.

Let's take a closer look at each approach.Response.Redirect The default behavior of the Response.Redirect method is execution of the current page halts, and the user is sent to the new URL. The Web server issues HTTP headers and sends a 302 response to the client browser; this instructs the client to make redirected calls to the target URL. The result is two server requests for each redirection: the original and redirected requests. The following C# snippet shows it in action:Response.Redirect("http://www.news.com");


Now, the Redirect method has two signatures with the second format accepting another Boolean parameter that signals whether execution of the current page should terminate (the default behavior). We could tell the system to continue execution of the current page while redirecting the user to the News.com site with the following snippet:Response.Redirect("http://www.news.com", false);
Server.Transfer The Server.Transfer method transfers the execution of a target URL to the server and halts execution of the current page. The result is only one request (as opposed to the two involved with the Response.Redirect method) since the server does not notify the client browser of the change. The experience can be a little disconcerting for users since the page address does not change in the browser. This C# snippet shows how you may use this method.Server.Transfer("/default.aspx");


When using Server.Transfer, the target URL must be a virtual path on the same server since the Web server's worker process is used, so you can't use an address containing "http" or "https." It has three signatures, with a second variation allowing you to transfer control to an IHttpHandler and the third adding a second parameter to the first version; whereas, the second value is a Boolean signaling whether the current form's querystring and Form collections are preserved.

The PreviousPage property of the Page class provides code access to properties of the previous page in the browsing session, so Form and querystring variables are persisted between pages whereas they are not when using Response.Redirect.
Server.Execute

The Server.Execute method is a bit antiquated, as there are other ways to accomplish the task, but it basically allows you to execute a resource request without leaving the current page. It is not really used for redirection, but it is mentioned here only to avoid any confusion with the Server.Transfer method.

Server.Execute has five signatures, but the basic version accepts a path to a resource as the following snippet displays:Server.Execute(ResourcePath);

Pros and cons of each approach

Redirecting a user to another Web resource is feasible in ASP.NET using one of the techniques discussed. However, you may be wondering why you would choose one approach over the other. The following list covers some of the advantages or disadvantages of Server.Transfer and Response.Redirect.
AJAX usage: The lack of browser interaction with the Server.Transfer method means it may break some AJAX and/or JavaScript functionality.
Bookmarking: Since Server.Transfer does its work on the server, the address within the client browser is not updated. The user sees the previous page's address while viewing a new page. Consequently, the user is unable to bookmark certain pages.
Page refreshes: There is an issue when a true value is used with the second parameter of the Server.Transfer method. When users refresh a page located via this approach, it can trigger an invalid ViewState error message. This can be alleviated by disabling the enableViewStateMac property on a page, but this isn't the best approach to security.
Performance: Response.Redirect introduces an extra call while making the roundtrip between client and server; since there is only one call with Server.Transfer, it offers better performance.
Scalability: The extra roundtrips associated with using Response.Redirect are often stated as a drawback with using it. However, I have seen it used in large applications without experiencing any performance issues.
Errors: While Server.Transfer can cause some user confusion as the URL displayed in the browser address bar, it can also lead to some confusion with error logging, as the page URL recorded during logging will display incorrectly.
Basic security: An interesting twist with using Server.Transfer is the ability to send data to another page without the user seeing it. This is enabled via the use of the QueryString, which is appended to the end of the target address. This new address will not show in the browser address bar with Server.Transfer, so it offers a simple layer of security. Of course, the Response.Redirect approach makes the QueryString visible to the user.

Monday, September 23, 2013

Exception Handling in WCF using Fault Contract

//Create Services Contract (Interface)
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService" in both code and config file together.
[ServiceContract]
public interface IService   //name of interface
{

[OperationContract]        // Name of Method
[FaultContract(typeof(MyReason))]
string GetData(int value);

}

[DataContract]

public class MyReason
{
[DataMember]
private string Reason;
public string MyCause { get; set; }
}

//class to implement 
Services Contract 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data.SqlClient; 
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.

public class Service : IService
{
  SqlConnection con;
  string ret;
  public string GetData(int r)
   {
     try
      {
         con = new SqlConnection("initial catalog=Tblname;data source=Dbname;integrated security=yes");
SqlCommand cmd = new SqlCommand("select name from student where seat_no=" + r + "", con);
con.Open();
SqlDataReader rd = cmd.ExecuteReader();
bool b = rd.Read();
if (b == false)
{
ret = null;
}
else
{
ret = rd["name"].ToString();
}

}

catch (Exception e1)
{
MyReason m = new MyReason();
m.MyCause = "he has internal pain in stomach";
throw new FaultException<MyReason>(m);
}
finally
{
con.Close();

}

return ret;
}
}

//Call 
That Services Client Side
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ServiceModel;    //First Client Add ServiceModel NameSpace

public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
try
 {
   int s1 = Convert.ToInt32(TextBox1.Text);
ServiceReference1.ServiceClient s=new 
ServiceReference1.ServiceClient();
string y = s.GetData(s1);
if (y == null)
{
Label1.Text = "Rec not found";
}
else
{
  Label1.Text = y;
}
}
catch (FaultException<ServiceReference1.MyReason> m)
{

Label1.Text = m.Detail.MyCause; //
Services Error Here
}
}
}
//

Wednesday, September 18, 2013

create Custom Event in C#

using System;

public delegate void CarOwnerChanged(string o);
public class car
{

       public event CarOwnerChanged OwnerChanged;
       private string owner;

         public string car_owner
          {

           get
              {
                return owner;
              }

           set
              {
                 owner = value;
                  if (OwnerChanged != null)
                     {
                        OwnerChanged(owner);
                      }
                }

            }

}
class office
{

     public static void Main()
     {

         car Viru= new car();
          
Viru.OwnerChanged+=new CarOwnerChanged(parking_call);
          
Viru.car_owner = "Viru Maurya";
      }

      public static void parking_call(string ow)
       {
          Console.WriteLine(ow);
       }
}