Thursday, August 23, 2012

Create an AJAX-Enabled WCF Service and an ASP.NET Client that Accesses the Service

To create the ASP.NET client application

  1. Open Visual Studio 2012.
  2. From the File menu, select New, then Project, then Web, and then select ASP.NET Web Application.
  3. Name the Project SandwichServices and click OK.

To create the WCF AJAX-enabled service

  1. Right-click the SandwichServices project in the Solution Explorer window and select Add, then New Item, and then AJAX-enabled WCF Service.
  2. Name the service CostService in the Name box and click Add.
  3. Open the CostService.svc.cs file.
  4. Specify the Namespace for ServiceContractAttribute as SandwichService:
    1.    namespace SandwichServices
         {
           [ServiceContract(Namespace = "SandwichServices")]
           [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
            public class CostService
            {
              …
            }
          }
      
    2. Implement the operations in the service. Add the OperationContractAttribute to each of the operations to indicate that they are part of the contract. The following example implements a method that returns the cost of a given quantity of sandwiches.
      public class CostService
      {
          [OperationContract]
          public double CostOfSandwiches(int quantity)
          {
              return 1.25 * quantity;
          }
      
      // Add more operations here and mark them with [OperationContract]
      } 

      To configure the client to access the service

      1. Open the Default.aspx page and select the Design view.
      2. From the View menu, select Toolbox.
      3. Expand the AJAX Extensions node and drag and drop a ScriptManager on to the Default.aspx page.
      4. Right-click the ScriptManager and select Properties.
      5. Expand the Services collection in the Properties window to open up the ServiceReference Collection Editor window.
      6. Click Add, specify CostService.svc as the Path referenced, and click OK.
      7. Expand the HTML node in the Toolbox and drag and drop an Input (Button) on to the Default.aspx page.
      8. Right-click the Button and select Properties.
      9. Change the Value field to Price for 3 Sandwiches.
      10. Double-click the Button to access the JavaScript code.
      11. Pass in the following JavaScript code within the <script> element.
        function Button1_onclick() {
        var service = new SandwichServices.CostService();
        service.CostOfSandwiches(3, onSuccess, null, null);
        }
        
        function onSuccess(result){
        alert(result);
        }
        

      To access the service from the client

      1. Use Ctrl +F5 to launch the service and the Web client. Click the Price for 3 Grilled Sandwiches button to generate the expected output of "3.75".

      Example

      This example contains the service code contained in the WCFService.svc.cs file and the client code contained in the Default.aspx file.
      //The service code contained in the CostService.svc.cs file.
      
      using System;
      using System.Linq;
      using System.Runtime.Serialization;
      using System.ServiceModel;
      using System.ServiceModel.Activation;
      using System.ServiceModel.Web;
      
      namespace SandwichServices
      {
          [ServiceContract(Namespace="SandwichServices")]
          [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
          public class CostService
          {
              // Add [WebGet] attribute to use HTTP GET
              [OperationContract]
              public double CostOfSandwiches(int quantity)
              {
                  return 1.25 * quantity;
              }
      
              // Add more operations here and mark them with [OperationContract]
          }
      }
      //The code for hosting the service is contained in the CostService.svc file.
      
      <%@ ServiceHost Language="C#" Debug="true" Service="SandwichServices.CostService" CodeBehind="CostService.svc.cs" %>
      
      //The client code contained in the Default.aspx file.
      
      @ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SandwichServices._Default" 
       Untitled Page
      function Button1_onclick() {
      var service = new SandwichServices.CostService();
      service.CostOfSandwiches(3, onSuccess, null, null);
      }
      
      function onSuccess(result){
      alert(result);
      }
       
      //Here add a Service Reference file and and input button in the .Aspx file and 
      call the above java function. 
      
       

Tuesday, January 17, 2012

Show the spaces in between values of dropdown

protected void ddlRack_DataBound(object sender, EventArgs e)
{
ddlRack.Items.Cast().ToList().ForEach(a => a.Text = a.Text.Replace(" ", HttpUtility.HtmlDecode(" ")));
}

Show the space in between the values of gridview

protected void gvRack_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblStatus = e.Row.FindControl("lblStatus") as Label;
Label lblRackNo = e.Row.FindControl("lblRackNo") as Label;
Label lblRackName = e.Row.FindControl("lblRackName") as Label;
lblRackNo.Text = lblRackNo.Text.Replace(" ", " "); //for showing the spaces in between the words

Show the decimal format of a value in gridview

we have to add like this while binding the data...
Label ID="lbl_PackageRate" runat="server" Text='<%#Eval("Rate","{0:0.00}") %>'

Text Box Properties




AutoCompleteType="Disabled" ---> this is used to remove the history of the textbox in browser

onFocus="this.select()" ---> this is used to select the entire text in textbox

Upload and download a file in the appn, asp.net

write this in a asp botton after browse the file using file upload button:

if (FileUpload1.HasFile)
{
string strFileExtension = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);

if (strFileExtension.ToUpper() == ".DOC" || strFileExtension.ToUpper() == ".DOCX" || strFileExtension.ToUpper() == ".TXT" || strFileExtension.ToUpper() == ".XLS" || strFileExtension.ToUpper() == ".XLSX" || strFileExtension.ToUpper() == ".PDF" || strFileExtension.ToUpper() == ".JPG" || strFileExtension.ToUpper() == ".JPEG" || strFileExtension.ToUpper() == ".PNG")
{
string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(FileUpload1.FileName);
string fn = fileNameWithoutExtension + "" + txtMRNNO.Text + "_" + DateTime.Now.ToString().Replace("/", string.Empty).Replace(" ", string.Empty).Replace(":", string.Empty) + "" + strFileExtension;
string SaveLocation = Server.MapPath("~/MedicalRecords/Uploads/") + fn;
FileUpload1.PostedFile.SaveAs(SaveLocation);
FileUpload1.Visible = false;
Label1.Text = fn;
imgAttachmentsSave.Focus();
btnUpload.Visible = false;
}




for dowloading:


if (e.CommandName == "Download")
{
int Count = Convert.ToInt32(e.CommandArgument);
//GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
Label lblFileName = new Label();
lblFileName = gvAttachments.Rows[Count].FindControl("lblFileName") as Label;

string filename = Server.MapPath("Uploads/" + "" + Convert.ToString(lblFileName.Text));
FileInfo fileInfo = new FileInfo(filename);
if (fileInfo.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileInfo.Name);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.Flush();
Response.WriteFile(fileInfo.FullName);
Response.End();
}
}

To Save the data from Excel into Database

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Data.OleDb;

public partial class _Default : System.Web.UI.Page
{
private string strConnection = "Persist Security Info=False;User ID=sa;Password=123456aA;Data Source=DI-PALLAVI; Initial Catalog=Practice";

protected void Page_Load(object sender, EventArgs e)
{


}
protected void btn_Click(object sender, EventArgs e)
{
//Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;Extended Properties="Excel 8.0;HDR=Yes;IMEX=1";
string excelConnectionString =
@"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=D:\Employee.xls;
Extended Properties=""Excel 8.0;HDR=YES;""";

//Create Connection to Excel work book
OleDbConnection excelConnection =
new OleDbConnection(excelConnectionString);

//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand
("Select [EmpID],[EmpName],[ESal] from [Sheet1$]",// sheet1 is name of the sheet in Excel Emp.xls
excelConnection);

excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();

SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "Emp"; // Name of the existing table
//sqlBulk.ColumnMappings.Add("ID", "ID");
//sqlBulk.ColumnMappings.Add("Name", "Name");
sqlBulk.WriteToServer(dReader);

}
}