Archives for category: C#

I created a folder in my solution named “UserControls”. That is where the following .ascx files are located:

StateFilter.ascx

<%@ Control Language=”C#” AutoEventWireup=”true” CodeBehind=”StateFilter.ascx.cs” Inherits=”Sandbox2010.UserControls.StateFilter” %>

<asp:DropDownList ID=”DdlState” runat=”server” DataSourceID=”DsState”
DataTextField=”Name” DataValueField=”StateProvinceID” AutoPostBack=”True”
onselectedindexchanged=”DdlState_SelectedIndexChanged”>
</asp:DropDownList>

<asp:SqlDataSource ID=”DsState” runat=”server”
ConnectionString=”<%$ ConnectionStrings:AdventureWorks2012_ConnectionString %>”
SelectCommand=”
select ” as StateProvinceID, ‘(Select a State)’ as Name
UNION ALL
SELECT DISTINCT StateProvinceID, Name
FROM Person.StateProvince
WHERE ISNULL(@CountryRegionCode, ”) = ” or CountryRegionCode = @CountryRegionCode ORDER BY Name”
onselecting=”DsState_Selecting”>
<SelectParameters>
<asp:Parameter Name=”CountryRegionCode” Type=”String” />
</SelectParameters>
</asp:SqlDataSource>

StateFilter.ascx.cs

using System;
using System.Web.UI.WebControls;
using System.ComponentModel;

namespace Sandbox2010.UserControls
{
public partial class StateFilter : System.Web.UI.UserControl
{
public event SelectedIndexChangedEventHandler SelectedIndexChanged;
public delegate void SelectedIndexChangedEventHandler(object sender, SelectedIndexChangedEventArgs args);

public string CountryRegionCode { get; set; }

public ListItem SelectedItem
{
get { return DdlState.SelectedItem; }
}

public string SelectedValue
{
get { return DdlState.SelectedValue; }
}

[Description(“CSS Class”), Category(“Configuration”)]
public string CssClass { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
DdlState.CssClass = CssClass;
}

protected void DdlState_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.SelectedIndexChanged != null)
{
this.SelectedIndexChanged(this, new SelectedIndexChangedEventArgs(DdlState.SelectedItem));
}
}

protected void DsState_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
e.Command.Parameters[“@CountryRegionCode”].Value = string.IsNullOrEmpty(CountryRegionCode) ? string.Empty : CountryRegionCode;
}
}
}

CountryFilter.ascx

<%@ Control Language=”C#” AutoEventWireup=”true” CodeBehind=”CountryFilter.ascx.cs” Inherits=”Sandbox2010.UserControls.CountryFilter” %>

<asp:DropDownList ID=”DdlCountry” runat=”server” DataSourceID=”DsCountry”
DataTextField=”Name” DataValueField=”CountryRegionCode” AutoPostBack=”True”
onselectedindexchanged=”DdlCountry_SelectedIndexChanged”>
</asp:DropDownList>

<asp:SqlDataSource ID=”DsCountry” runat=”server”
ConnectionString=”<%$ ConnectionStrings:AdventureWorks2012_ConnectionString %>”
SelectCommand=”
select ” as CountryRegionCode, ‘(Select a Country)’ as Name
UNION ALL
select distinct c.CountryRegionCode, c.Name
from
Person.CountryRegion as c
join Person.StateProvince as s
on c.CountryRegionCode = s.CountryRegionCode
order by Name
“>
</asp:SqlDataSource>

CountryFilter.ascx.cs

using System;
using System.Web.UI.WebControls;
using System.ComponentModel;

namespace Sandbox2010.UserControls
{
public partial class CountryFilter : System.Web.UI.UserControl
{
public event SelectedIndexChangedEventHandler SelectedIndexChanged;
public delegate void SelectedIndexChangedEventHandler(object sender, SelectedIndexChangedEventArgs args);

public string CountryRegionCode { get; set; }

public ListItem SelectedItem
{
get { return DdlCountry.SelectedItem; }
}

public string SelectedValue
{
get { return DdlCountry.SelectedValue; }
}

[Description(“CSS Class”), Category(“Configuration”)]
public string CssClass { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
DdlCountry.CssClass = CssClass;
}

protected void DdlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.SelectedIndexChanged != null)
{
this.SelectedIndexChanged(this, new SelectedIndexChangedEventArgs(DdlCountry.SelectedItem));
}
}
}
}

I created a web form that contains my user controls and a text box that displays the final selected drop down list option:

WebForm1.aspx

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”WebForm1.aspx.cs” Inherits=”Sandbox2010.WebForm1″ %>
<%@ Register Src=”UserControls/StateFilter.ascx” TagPrefix=”uc” TagName=”StateFilter”%>
<%@ Register Src=”UserControls/CountryFilter.ascx” TagPrefix=”uc” TagName=”CountryFilter”%>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title></title>
<link rel=”Stylesheet” href=”Styles/Rubrik.css” />
</head>
<body>
<form id=”form1″ runat=”server”>
<br /><br />
<uc:CountryFilter id=”CountryFilter1″ runat=”server” onselectedindexchanged=”CountryFilter1_SelectedIndexChanged” />
<br /><br />
<uc:StateFilter id=”StateFilter1″ runat=”server” onselectedindexchanged=”StateFilter1_SelectedIndexChanged” />
<br /><br />
You selected:<br />
<asp:TextBox ID=”MySelection” runat=”server”></asp:TextBox>
</form>
</body>
</html>

WebForm1.aspx.cs

using System;
using Sandbox2010.UserControls;

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

protected void CountryFilter1_SelectedIndexChanged(object sender, SelectedIndexChangedEventArgs e)
{
if (e.SelectedItem != null)
{
StateFilter1.CountryRegionCode = e.SelectedItem.Value;
StateFilter1.DataBind();
}
}

protected void StateFilter1_SelectedIndexChanged(object sender, SelectedIndexChangedEventArgs e)
{
if (e.SelectedItem != null)
{
MySelection.Text = e.SelectedItem.Text;
}
}
}
}

 

 

Advertisements

This example demonstrates how to get the current logged in windows user by using an ASP.NET Web Form named “MyWebForm.aspx” and a code behind page named “MyWebForm.aspx.cs”. The Web Form has a single text box control named “TextBox1”. “this” represents System.Web.UI.Page, which has a public instance variable named “Request” of type System.Web.HttpRequest.
using System;

namespace MyNamespace
{
public partial class MyWebForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = this.Request.LogonUserIdentity.Name;
}
}
}

Imagine you have a web service. The web service is configured to use the POST method and it’s configured to accept JSON requests and responses. The web service accepts a ‘Product’ object as the input parameter. The web service simply gets the ‘Name’ attribute of the ‘Product” and returns it as a string. I know that this web service is useless, but it works as a simple example.

Here is the definition for the ‘Product’ class. You need to create a ‘Product.cs’ class in the project where the ‘CallService<T>’ method is being called:

public class Product{

public int ID { get; set; }
public string Name { get; set; }

}

You need to add the following references to your project and add the following code at the top of the file where ‘CallService<T>’ is defined:

using System;
using System.Text;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;

Here is the definition of the ‘CallService<T>’ method:

// <T> needs to specify the return type of the web service
public T CallService<T>(string webServiceUrl, object param){

object result = new object(); //this is the object that will be returned by CallService<T>
string jsonString = new JavaScriptSerializer().Serialize(param); //get Json string representation of object
//Console.WriteLine(jsonString); //display the json encoded string (if you are using a console application)

byte[] postData = Encoding.UTF8.GetBytes(jsonString); //convert the Json string to an array of bytes
WebRequest request = WebRequest.Create(webServiceUrl); //create a request object
request.Method = “POST”; //we will use POST (as opposed to GET)
request.ContentLength = postData.Length; //set the length of the request
request.ContentType = “text/json”; //we will use Json data formatting
using (Stream reqStream = request.GetRequestStream()) {

reqStream.Write(postData, 0, postData.Length); //send the input data to the web service

}
using (WebResponse response = request.GetResponse()) {

string jsonResult = new StreamReader(response.GetResponseStream()).ReadToEnd(); //get the Json string from the web service response
result = new JavaScriptSerializer().Deserialize<T>(jsonResult); //convert the Json string to a c# object of type T, then cast it as an object

}
return (T)result;

}

Here is an example call. Please note that you need to change ‘<string>’ so that it matches the return type of your web service:

Product inputParameter = new Product();
inputParameter.ID = 123;
inputParameter.Name = “Laptop”;

string url = “http://localhost:49269/MyService.svc/GetProductName “;

string outputParameter = CallService<string>(url, inputParameter);

 

This is how I convert a C# object to a Json string, send it to a web service, get a Json string response from the web service, and convert the Json string back into a C# object. I’m new at this, so I may be performing unnecessary steps …but it works.

You can get detailed instructions for creating the WCF web service that I use in this example. CLICK HERE FOR DETAILS.

In Visual Studio, within the Solution Explorer area: right click “Solution ‘MyNamespace'” -> Add -> New Project… -> Visual C# -> Console Application. Then enter ‘ConsoleApplication1’ in the ‘Name:’ textbox and click the ‘OK’ button.

In the Solution Explorer area: right click ConsoleApplication1 -> Set as StartUp Project.

In the Solution Explorer area: right click ConsoleApplication1 -> Add -> New Item… -> Visual C# Items -> Class. Then enter ‘CompositeType.cs’ in the ‘Name:’ textbox and click the ‘OK’ button.

Open ‘CompositeType.cs’ and replace ‘class CompositeType{}’ with the following code:

public class CompositeType {

bool boolValue = true;
string stringValue = “Hello “;

public bool BoolValue{

get { return boolValue; }
set { boolValue = value; }

}

public string StringValue{

get { return stringValue; }
set { stringValue = value; }

}

}

Add this to the ‘IMyService.cs’ file in the ‘MyNamespace’ project, then save the changes:

[OperationContract]
[WebInvoke(Method = “POST”,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = “ReceiveJsonStringAndReturnIt”)]
CompositeType ReceiveJsonStringAndReturnIt(CompositeType param);

Add this to the ‘MyService.svc.cs’ file in the ‘MyNamespace’ project, then save the changes:

public CompositeType ReceiveJsonStringAndReturnIt(CompositeType param) {

//i am just returning the input parameter, unmodified.
//you should probably do something meaningful here.
return param;

}

In the Solution Explorer area: ConsoleApplicaiton1 -> right click ‘References’ -> Add Reference… -> find/select ‘System.Web.Extensions’ -> click ‘OK’ button

In the Solution Explorer, open ‘Program.cs’. Add the following code in the first line of the file:

using System.Web.Script.Serialization; //this comes from System.Web.Extensions
using System.Net;
using System.IO;

Then add the following code within the ‘static void Main’ method: (Be sure to replace ‘http://localhost:55761 ‘ with the correct value. CLICK HERE FOR DETAILS)

CompositeType myCompositeType = new CompositeType() { StringValue=”here is my string value”, BoolValue=true }; //create c# CompositeType object
var serializedObject = new JavaScriptSerializer().Serialize(myCompositeType); //get Json string representation of object
//Console.WriteLine(serializedObject); //uncomment this in order to see what the Json string looks like

byte[] byteArray = Encoding.UTF8.GetBytes(serializedObject); //create a byte array for the datastream
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(“http://localhost:55761/MyService.svc/ReceiveJsonStringAndReturnIt “); //create a request to send to the web service
request.Method = “POST”; //use the POST method (as opposed to GET)
request.ContentType = “application/json”; //set the content type to Json
Stream dataStream = request.GetRequestStream(); //establish a stream to the web service
dataStream.Write(byteArray, 0, byteArray.Length); //send the byte array
dataStream.Close(); //close the stream

WebResponse response = request.GetResponse(); //get the response from the web service
string result = new StreamReader(response.GetResponseStream()).ReadToEnd(); //get the Json string from the web service response
CompositeType resultCompositeType = new JavaScriptSerializer().Deserialize<CompositeType>(result); //convert the Json string to a c# object (Car)
Console.WriteLine(resultCompositeType.StringValue); //demonstrate that the object was successfully converted and contains data from the web service

Press Ctrl + F5 to run the program in Visual Studio. If the program is working correctly then a cmd.exe window should open and you should see the text returned from the web service: ‘here is my string value’.

This will require 4 main components: MyService.svc, MyService.svc.cs, IMyService.cs, Web.config. For me, the Web.config endpoint configuration is the only component that is not straight forward. If you want to view the markup of the MyService.svc file, then: Solution Explorer -> right click MyService.svc -> View Markup.

Lets get started creating the project.

In Visual Studio: FILE -> New -> Project -> WCF Service Application. I entered ‘MyNamespace’ in the ‘Name:’ textbox and clicked the ‘OK’ button.

In the Solution Explorer area, right click IService.cs and rename it ‘IMyService’. Choose ‘Yes’ if the Visual Studio message box promps you to change all references. If you are not prompted, then open IService.cs, right click the ‘IService’ in ‘public interface Iservice’ then: Refactor -> Rename. Then enter ‘IMyService’ in the ‘New name:’ textbox and click the ‘OK’ button.

In the Solution Explorer area, right click Service1.svc and rename it ‘MyService’. Choose ‘Yes’ if the Visual Studio message box promps you to change all references. If you are not prompted, then open Service1.cs, right click the ‘Service1’ in ‘public class service1 : IMyService’ then: Refactor -> Rename. Then enter ‘MyService’ in the ‘New name:’ textbox and click the ‘OK’ button.

Open Web.config. Add the following code directly below ‘<behaviors>’:

<endpointBehaviors>
<behavior name=”webHttp”>
<webHttp/>
</behavior>
</endpointBehaviors>

Add the following code directly below ‘<serviceBehaviors>’:

<behavior name=”myServiceBehavior”>
<serviceMetadata httpGetEnabled=”true”/>
<serviceDebug includeExceptionDetailInFaults=”false”/>
</behavior>

Add the following code directly below ‘<system.serviceModel>’:

<services>
<service name=”MyNamespace.MyService” behaviorConfiguration=”myServiceBehavior”>
<endpoint name=”webHttpBinding” address=”” binding=”webHttpBinding” contract=”MyNamespace.IMyService” behaviorConfiguration=”webHttp”>
</endpoint>
<endpoint name=”mexHttpBinding” address=”mex” binding=”mexHttpBinding” contract=”IMetadataExchange”></endpoint>
</service>
</services>

Open IMyService.cs, delete the existing [OperationContract] and ‘string GetData(int value);’ and the following code in it’s place:

[OperationContract]
[WebInvoke(Method = “GET”, UriTemplate = “GetData/{value}”)]
string GetData(string value);

[OperationContract]
[WebInvoke(Method = “GET”, ResponseFormat = WebMessageFormat.Json, UriTemplate = “GetJsonDataUsingDataContract”)]
CompositeType GetJsonDataUsingDataContract();

Open MyService.svc.cs, delete the existing GetData method and paste the following code in it’s place:

public string GetData(string value){

return string.Format(“You entered: {0}”, value);

}

public CompositeType GetJsonDataUsingDataContract(){

return new CompositeType();

}

We will be running the code next, so you need to know the project url that will be used. Go to Solution Explorer -> right click MyNamespace -> Properties -> Web -> Project Url. Copy the url.

Press Ctrl + F5 to run the web service. Paste the url you copied, followd by ‘MyService.svc/GetData/hello world’, into the a browser and you should see the result that gets returned by the web service. Paste the url you copied, followd by ‘MyService.svc/GetJsonDataUsingDataContract’, into the a browser and you should see the Json result that gets returned by the web service.