Today we will look at how to build Export to Excel functionality by deriving new type from ActionResult class.
To get started, lets setup following:
An ASP.NET MVC project
New controller with name "ExcelController.cs" inside controller folder
ConnectionString to any database (in this one I am using Products table of Adventure works database)
[More]
Previous article 1
Part-2 Creating ASP.net client.
Code for ASP.net Client
[More]
76e53d9e-72db-4534-96b0-42e1265a22e5|2|3.0
Tags:
ASP.NET | WCF
In this article we are going to see Instance management provided by WCF and how we can use single WCF service in three different clients- ASP.net, C sharp Windows application and WPF application.
WCF provides three different instance management techniques per call, Per Session and Single.
[More]
jQuery Template helps a lot when it comes to bringing data back from server and present it in some kind of DOM element. I have found jQuery Template very easy to work with and with ASP.NET MVC it does wonders.
Today, we will work on how to call function inside template expression.
[More]
When we want to use the member variables of class Leader at client side, we will have to declare the object of that class Leader and through that object we will access its members.
Eg.
ServiceReference1.Leaders ldr = new ServiceReference1.Leaders();
Aspx code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!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>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"/>
<%--<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>--%>
<div>
<table>
<tr>
<td><h1>DevTechie</h1></td>
</tr>
<tr>
<td>
<table>
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="Enter Name of Leader"></asp:Label></td>
<td>
<asp:TextBox ID="txtenterleader" runat="server"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnsearch" runat="server" Text="Show Leader"
onclick="btnsearch_Click"/>
</td>
</tr>
</table>
</td>
</tr>
<tr><td>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</td></tr>
<tr>
<td>
<asp:Image ID="Image1" runat="server" Height="200px" />
</td>
<td>
<table>
<tr>
<td>
</td>
<td>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table>
<tr>
<td>
<asp:Button ID="btnAddLeader" runat="server" Text="Add New Leader"
onclick="btnAddLeader_Click" />
</td>
<td>
<%--<asp:Button ID="btnModifyLeaderInfo" runat="server" Text="Modify Info Of Leader" />--%>
</td>
</tr>
</table>
</td>
</tr>
<tr><td></td></tr>
<tr>
<td>
<asp:Panel ID="Panel1" runat="server" BackColor="Silver" BorderColor="Black"
BorderWidth="2px">
<table>
<tr>
<td>Enter the TextFields</td>
</tr>
<tr>
<td><asp:Label ID="lblName" runat="server" Text="Name"></asp:Label></td>
<td><asp:TextBox ID="txtname" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="lblCountry" runat="server" Text="Country"></asp:Label></td>
<td><asp:TextBox ID="txtCountry" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="lblPicture" runat="server" Text="Picture"></asp:Label></td>
<td>
<asp:AsyncFileUpload ID="AsyncFileUpload1" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnSaveClose" runat="server" Text="Save And Close" onclick="btnSaveClose_Click" /></td>
</tr>
</table>
</asp:Panel>
</td>
</tr>
</table>
<table>
<tr>
<td>
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" PopupControlID="Panel1" TargetControlID="btnAddLeader">
</asp:ModalPopupExtender>
<%--<asp:PopupControlExtender ID="PopupControlExtender1" runat="server" PopupControlID="Panel1" TargetControlID="btnAddLeader">
</asp:PopupControlExtender>--%>
</td>
</tr>
</table>
</div>
<%-- </ContentTemplate>
</asp:UpdatePanel>--%>
</form>
</body>
</html>
Webconfig for client side
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IService1" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"
bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="75536" messageEncoding="Text"
textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="Message">
<transport clientCredentialType="Windows" proxyCredentialType="None"
realm="">
<extendedProtectionPolicy policyEnforcement="Never" />
</transport>
<message clientCredentialType="Windows" negotiateServiceCredential="true"
algorithmSuite="Default" establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
Note: In the above article we have discussed only basic use of datacontract and datamember attributes but there is more to them which we will be covering in my coming article.
Also we have not discussed anything about instance management which hopefully we will be covering in my coming articles.
Jump to: Part 1, Part 2, Part 3, Part 4
32fcab6b-19aa-4072-a824-a0005ab7932f|0|.0
Tags:
ASP.NET | WCF
Client side:
Now as our client is a completely different application domain, we will have to select new website from visual studio template and add the service reference to the client side which I have already discussed in my previous article.
Below is the screen shot:
In the above screen shot when we write the name of the leader and click on "Show Leader" button the service will search the for required information and display the result. Now to add leader we have button "Add New Leader" once you click on it a popup window will appear so that you can write the info and click on "SAVE and Close " button, the record will be inserted to database and will appear on the page.
Screen shot is below:
Once you click on "Save and Close" button the popup window will get closed and newly added leader will appear on page.
Below is screen shot:
At client side we have used Ajax Toolkit model popup extender and Asynchronous File Upload control to show the popup box to add records and to add the picture respectively.
Below is the code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ServiceReference1.IService1 clientproxy = new ServiceReference1.Service1Client();
ServiceReference1.Leaders ldr = new ServiceReference1.Leaders();
DataTable dt = new DataTable();
ldr.p_name="Barak Obama";
dt = clientproxy.GetLeadersInfo(ldr);
GridView1.DataSource = dt;
GridView1.DataBind();
Image1.ImageUrl = "http://localhost:53137/images/"+Convert.ToString(dt.Rows[0]["Pic"]);
}
protected void btnAddLeader_Click(object sender, EventArgs e)
{
}
protected void btnSaveClose_Click(object sender, EventArgs e)
{
string filename="";
ServiceReference1.IService1 clientprxy = new ServiceReference1.Service1Client();
if (AsyncFileUpload1.HasFile)
{
var scheme = Request.Url.Scheme; // will get http, https, etc.
var host = Request.Url.Host; // will get www.mywebsite.com
var port = Request.Url.Port; // will get the port
var path = Request.Url.AbsolutePath;
string picpath = scheme.ToString() + "://" + host.ToString() + ":" + port.ToString() + Request.ApplicationPath + "/" + "images/";
// AsyncFileUpload1.SaveAs("F:\\programs\\dot net\\blog-webapp\\images\\" + AsyncFileUpload1.FileName);
AsyncFileUpload1.SaveAs("F:\\wcf programs\\Leaders Info Insert Update DELETE\\WcfServiceLeaders\\WcfServiceLeaders\\images\\" + AsyncFileUpload1.FileName);
filename = Convert.ToString(AsyncFileUpload1.FileName);
}
ServiceReference1.Leaders ldr = new ServiceReference1.Leaders();
ldr.p_name = txtname.Text;
ldr.p_country = txtCountry.Text;
ldr.p_pic = filename;
//clientprxy.AddLeader(txtname.Text, txtCountry.Text,filename);
clientprxy.AddLeader(ldr);
txtenterleader.Text = txtname.Text;
fillLeader();
// Panel1.Visible = false;
}
protected void btnsearch_Click(object sender, EventArgs e)
{
ServiceReference1.IService1 clientproxy = new ServiceReference1.Service1Client();
ServiceReference1.Leaders ldr = new ServiceReference1.Leaders();
ldr.p_name = txtenterleader.Text;
DataTable dt = new DataTable();
dt = clientproxy.GetLeadersInfo(ldr);
GridView1.DataSource = dt;
GridView1.DataBind();
Image1.ImageUrl = "http://localhost:53137/images/" + Convert.ToString(dt.Rows[0]["Pic"]);
}
protected void fillLeader()
{
ServiceReference1.IService1 clientproxy = new ServiceReference1.Service1Client();
ServiceReference1.Leaders ldr = new ServiceReference1.Leaders();
ldr.p_name = txtenterleader.Text;
DataTable dt = new DataTable();
dt = clientproxy.GetLeadersInfo(ldr);
GridView1.DataSource = dt;
GridView1.DataBind();
Image1.ImageUrl = "http://localhost:53137/images/" + Convert.ToString(dt.Rows[0]["Pic"]);
}
}
Continue...
Jump to: Part 1, Part 2, Part 3, Part 5
028511b8-5de2-49c0-b284-e54735419d9d|0|.0
Tags:
ASP.NET | WCF
Data Contract- is a formal agreement between a service and a client that abstractly describes the data to be exchanged.
Code for Service1.svc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace WcfServiceLeaders
{
// NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in Web.config and in the associated .svc file.
public class Service1 : IService1
{
Leaders ldr = new Leaders();
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
public DataTable GetLeadersInfo(Leaders ldr)
{
string constr = ConfigurationManager.ConnectionStrings["blogDevtechie"].ToString();
SqlConnection con = new SqlConnection();
con.ConnectionString = constr;
con.Open();
SqlCommand cmd = new SqlCommand("usp_selectLeader", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = ldr.p_name;// name;
//***************************************************************************
SqlParameter parm2 = new SqlParameter("@returnval", SqlDbType.Int);
parm2.Size = 50;
parm2.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(parm2);
//**************************************************************
SqlParameter parm1 = new SqlParameter("@msg", SqlDbType.VarChar);
parm1.Size = 50;
parm1.Direction = ParameterDirection.Output;
cmd.Parameters.Add(parm1);
//**************************************************************
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Leaders");
adpt.Fill(dt);
return dt;
}
public void AddLeader(Leaders ldr)
{
string constr = ConfigurationManager.ConnectionStrings["blogDevtechie"].ToString();
SqlConnection con = new SqlConnection();
con.ConnectionString = constr;
con.Open();
SqlCommand cmd = new SqlCommand("usp_InsertLeader", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = ldr.p_name;
cmd.Parameters.Add("@country", SqlDbType.VarChar).Value = ldr.p_country;
cmd.Parameters.Add("@pic", SqlDbType.VarChar).Value = ldr.p_pic;
//***************************************************************************
SqlParameter parm2 = new SqlParameter("@returnval", SqlDbType.Int);
parm2.Size = 50;
parm2.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(parm2);
//**************************************************************
SqlParameter parm1 = new SqlParameter("@msg", SqlDbType.VarChar);
parm1.Size = 50;
parm1.Direction = ParameterDirection.Output;
cmd.Parameters.Add(parm1);
//**************************************************************
int i=cmd.ExecuteNonQuery();
}
}
}
In the above code we are implementing our method defined in our interface.
Here, we are mainly concerned with two methods GetLeadersInfo and AddLeader
GetLeadersInfo- will fetch the leader from database and expose it to the client side.
AddLeader-will add the record to the database which is coming from client.
In both the methods I am passing parameter ldr which is object of type Leaders, so ldr will contain all the member variable and properties of class Leaders and through this ldr we will set and access the values of members defined in class Leaders.
Eg.
public void AddLeader(Leaders ldr)
public DataTable GetLeadersInfo(Leaders ldr)
Continue…
Jump to: Part 1, Part 2, Part 4, Part 5
11b4a5d1-348a-4115-b65c-a664f01fbad8|0|.0
Tags:
ASP.NET | WCF
Iservice.cs file is where we are going to define our interface and methods which they contain and Service.cs is where we are going to implement our methods which are in our interface.
We will also have to create image directory at the service application directory so that we can save the images to this location, in my case I have named the directory as images and in my system its location is:
F:\wcf programs\Leaders Info Insert Update DELETE\WcfServiceLeaders\WcfServiceLeaders\images
Service side code.
IService1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
namespace WcfServiceLeaders
{
// NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
[OperationContract]
DataTable GetLeadersInfo(Leaders ldr);
[OperationContract]
void AddLeader(Leaders ldr);
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
[DataContract]
public class Leaders
{
string name1;
[DataMember]
public string p_name
{
get{return name1;}
set{name1=value;}
}
string Country1;
[DataMember]
public string p_country
{
get{return Country1;}
set{Country1=value;}
}
string pic1;
[DataMember]
public string p_pic
{
get { return pic1; }
set { pic1 = value; }
}
string address;
[DataMember]
public string p_address
{
get { return address; }
set { address = value; }
}
}
}
Now in the above code we can see our interface IService1 is decorated with ServiceContract attribute. Service contract specifies what an endpoint communicates to the outside world (client).
Without Service Contract attribute, the interface is not visible to WCF clients. In simple words it is necessary to write service contract on an interface only then we would be able to invoke its methods on client side i.e. Expose it to exterior world.
We can also see that our methods are decorated with operation contract attribute. Operation contract defines which operations are to be exposed to the client (Exterior world). If we don't mention operation contract over method it will not get exposed to client side or in other words we won't be able to use it at client side.
We have also used class "Leaders" and decorated it with DataContract attribute which will expose it to the client and we will be using its member variables for inserting and displaying records. We have also decorated properties with Data Member attributes defined in class Leaders. Decorating member variables or properties with data member will expose them to the exterior world or client, without data member attribute the properties will not get exposed to the client side and therefore we won't be able to use them. When data member is applied to the member of a type it specifies that the member is part of a data contract and is serializable by the DataContractSerializer.
In the above example we have used explicit data contract (class, structure etc) as we are explicitly mentioning them. In my previous article we used implicit data contract (int, string etc…)
Continue ...
Jump to: Part 1, Part 3, Part 4, Part 5
40982369-bb4d-4399-bd09-b678f928afcc|0|.0
Tags:
ASP.NET | WCF
In this article, we will see how we can insert data and display records using WCF. We will be using data contract and data member attributes, we will also be using two completely different application domains for client and service respectively.
So first we will make a table in database.
Below is the code.
CREATE TABLE [dbo].[blog_Leaders](
[Name] [nvarchar](50) NOT NULL,
[Country] [nvarchar](50) NOT NULL,
[Pic] [nvarchar](max) NULL,
[ID] [int] IDENTITY(1,1) NOT NULL,
CONSTRAINT [PK_blog_Leaders] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Stored Procedure for Inserting Leaders:
CREATE PROCEDURE [dbo].[usp_InsertLeader]
(
@Name nvarchar(100),
@Id int=0,
@pic nvarchar(200),
@country nvarchar(50),
@msg varchar(100) output
)
-- Add the parameters for the stored procedure here
AS
BEGIN try
insert into blog_Leaders(Name,Country,Pic)
values(@Name,@country,@pic)
--select 'successfull'
return 0
END try
begin catch
select @msg='Error!!!Problem Occured During Process'
return 1
end catch
Stored Procedure for Displaying records
CREATE PROCEDURE [dbo].[usp_selectLeader]
(
@Name nvarchar(100),
@Id int=0,
@msg varchar(100) output
)
-- Add the parameters for the stored procedure here
AS
BEGIN try
select * from blog_Leaders where name like @Name+'%';
--select 'successfull'
return 0
END try
begin catch
select @msg='Error!!!Problem Occured During Process'
return 1
end catch:
Second, we need to select WCF service from templates which I have already shown in my previous articles which are here
Once we have selected WCF service from template you will be provided with two files in App_Code Directory
Continue …
Jump to: Part 2, Part 3, Part 4, Part 5
10d3db8f-9933-4262-a8b2-5d0707ce5074|0|.0
Tags:
ASP.NET | WCF
Today we will see how to build file upload functionality in MVC2 and then display uploaded files in a HTML table.
[More]