August 2009 - Posts
Using the HttpWebRequest Class
Last week I got a
requirement for a
direct interaction
with an HTTP
server. As a result I
needed to use the
HttpWebRequest class in
order to create the relevant requests.
This post will introduce the HttpWebRequest class.
The HttpWebRequest Class
The HttpWebRequest class is a wrapper class that wrap an HTTP
request for a resource. It provides many properties and methods that
enable us to configure an HTTP request and interact with HTTP servers.
You should initialize an HttpWebRequest only through the WebRequest’s
Create method like in the following example:
var request = (HttpWebRequest)WebRequest.Create("http://blogs.microsoft.co.il");
The most useful methods that you should know are the GetResponse,
which returns an HttpWebResponse, and BeginGetResponse and EndGetResponse
methods which enables the making of asynchronous request to the relevant
resource. The following example shows how get a response from a HttpWebRequest
object:
var response = (HttpWebResponse)request.GetResponse();
Example of Using the HttpWebRequest Class
The following code is an example of how to use the HttpWebRequest in
order to get the web page of http://blogs.microsoft.co.il (this site)
as a string:
try
{
var request = (HttpWebRequest)WebRequest.Create("http://blogs.microsoft.co.il");
request.Method = "GET";
request.ContentType = "text/html";
request.KeepAlive = false;
request.UseDefaultCredentials = true;
var response = (HttpWebResponse)request.GetResponse();
using (var stream = new StreamReader(response.GetResponseStream()))
{
var result = stream.ReadToEnd();
return result;
}
}
catch (WebException ex)
{
// do something
}
catch (Exception ex)
{
// do something
}
Summary
In this post we saw the HttpWebRequest class and how to use it
to get a resource like a web page to our application. The HttpWebRequest
enables us to communicate with HTTP servers by building the relevant
requests we want to perform and sending them. There are many
other details about this class that I encourage you to check out. Just
Google it/Bing it and you’ll find more details.
Building a Simple Cache Manager
As I wrote in a previous post,
I’ve started to work in a
new project. My role
there is a technical team
leader of a very big team
(10 developers).
Part of my role is helping the
team to create infrastructure for their applications. As part of the application’s
infrastructure, I recommended to start using caching for better performance.
In the post I’ll demonstrate the simple cache manager I’ve built for the team.
ICacheManager Interface
Before building the cache manager I created an interface for caching.
I’ve done that in order to create abstraction between the application
and the used cache manager since in the future we may want to change
the implementation for Velocity distributed cache for example. Another
reason was for the testability of the caching subsystem. The last reason is
because we are going to use a dependency injection container for our
infrastructure. The following code is the interface I’ve created:
public interface ICacheManager
{
/// <summary>
/// Add a new object into the cache
/// </summary>
/// <param name="key">The key of the object to add</param>
/// <param name="value">The value of the object to add</param>
void Add(string key, object value);
/// <summary>
/// Check whether the key is contained by the cache
/// </summary>
/// <param name="key">The key to check</param>
/// <returns>Returns true if the key is contained by the cache</returns>
bool Contains(string key);
/// <summary>
/// Returns the number of items in the cache
/// </summary>
/// <returns></returns>
int Count();
/// <summary>
/// Insert a new object into the cache
/// </summary>
/// <param name="key">The key of the object to insert</param>
/// <param name="value">The value of the object to insert</param>
void Insert(string key, object value);
/// <summary>
/// Get the object that its key is given
/// </summary>
/// <typeparam name="T">The object</typeparam>
/// <param name="key">The given key to check</param>
/// <returns>returns the object or null if it doesn't exists</returns>
T Get<T>(string key);
/// <summary>
/// Removes the object that is referenced by the given key
/// </summary>
/// <param name="key">The given key</param>
void Remove(string key);
/// <summary>
/// Get/Set the the given key and object
/// </summary>
/// <param name="key">The given key to the indexer</param>
/// <returns>Returns the object that the given key reference</returns>
object this[string key]
{
get;
set;
}
}
The CacheManager Implementation
The implementation of the cache manager is very straight forward.
I’ve used the ASP.NET caching in order to cache the data. The following code
is the simple implementation I’ve created:
public class CacheManager : ICacheManager
{
#region ICacheManager Members
public void Add(string key, object value)
{
HttpRuntime.Cache.Add(key, value, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
}
public bool Contains(string key)
{
return HttpRuntime.Cache.Get(key) != null;
}
public int Count()
{
return HttpRuntime.Cache.Count;
}
public void Insert(string key, object value)
{
HttpRuntime.Cache.Insert(key, value);
}
public T Get<T>(string key)
{
return (T)HttpRuntime.Cache.Get(key);
}
public void Remove(string key)
{
HttpRuntime.Cache.Remove(key);
}
public object this[string key]
{
get
{
return HttpRuntime.Cache[key];
}
set
{
HttpRuntime.Cache[key] = value;
}
}
#endregion
}
This isn’t going to be our caching manager in the future but for now
it is enough in order to start using cache in the application.
Summary
I’ve shown a very simple cache manager. I could have created other
solutions like having an in memory dictionary with cached data or other
implementation that I can think about but the ASP.NET caching is there
for using so why not use it. In the future this implementation will be
replaced with a more appropriate caching mechanism such as Velocity.
IDCC Session Voting
A lot was written about IDCC – Israeli Developers Community Conference 2009.
In this conference you, as part of the developers community, can vote for your
favorite sessions and then help to shape the conference’s agenda. I suggested
three topics:
- Entity Framework Tips & Tricks
Entity Framework is a very massive data access technology.
This session is filled with tips and tricks that can help you avoid pitfalls and increase
productivity with Entity Framework. See how to improve the performance of your
queries, how to avoid database queries if not needed, how to use caching and many
more. - Getting to know the ADO.NET Data Services framework
ADO.NET Data Services is a highly productive connection systems technology that
can enable RESTful services against a variaty of data sources. In this session we will
get to know with the ADO.NET Data Services framework and understand were to use it. - Dependency Injection the Unity way
This talk will introduce the concepts of DI and how to implement them in your
application using the Unity Application Block.
If you like these topics go and vote for them here.
The voting’s end is on this Monday so if you didn’t vote go ahead and do that.
There are some recommended topics from my colleagues like:
and more many very interesting sessions.
Since you can vote only for 4-8 sessions it was very hard for me to decide
which session will get my vote…
Strange Google Search Result
In two occasions this week I got the following Hebrew error page from
Google while I was searching development data:
To non Hebrew speakers the error page say that my query resembles a virus
or spyware requests and to protect other users Google can’t process my query.
The typed search in the first attempt was “ASP.NET server communication”…
This is the first time I get that response from Google…
Quick Tip – Convert VB.NET to C# or C# to VB.NET
There is a need sometimes to convert VB.NET files to C# or vice versa.
There are two tools that I use in this process:
There are also add-ins to Visual Studio that enables the convert between VB.NET
to C# like C-Sharpener For VB but since I don’t have full projects to convert
I prefer the above free tools.
Also, there is a great reference guide which highlight some differences
between VB.NET and C# which I found very useful when the convert tools fails.
Enjoy!
Where I’ve been in the Last Weeks
If you are reading my blog you could see that I haven’t written
posts for a while. In the last weeks I’ve been busy a lot with family
issues, I took a one week vacation and also I have started a new
project in a very big commercial company. In the future I’ll write more
about the things I do there and about other stuff.
See you around.
Disabled my Contact Form
Since yesterday my blog is under a spam attack!
I got more than 100 garbage mails through my contact form so I disabled it for a while.
I’ll enable it in the near future after I’ll see that the attack is over…
Populating a ModalPopupExtender Dynamically
In the following week
I was asked to dynamically
populate a popup that is
created by a ModalPopupExtender.
The answer is simple. There are
two ways to that and in this post
I’ll show them both.
Building the Script Service
The first thing I did was to create a ScriptService. The service will
create dynamically the controls I want to populate the popup of
the ModalPopupExtender with. The following ScriptService will
write a div and a bold text to its GetData method callers:
/// <summary>
/// Summary description for ExampleService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class ExampleService : WebService
{ [WebMethod]
public string GetData(string contextKey)
{ StringBuilder sb = new StringBuilder();
using (StringWriter underlineWriter = new StringWriter(sb))
{ using (HtmlTextWriter writer = new HtmlTextWriter(underlineWriter))
{ HtmlGenericControl div = new HtmlGenericControl
{ ID = "div",
InnerText = "Some Div",
TagName = "div"
};
div.RenderControl(writer);
writer.Write("<b>Data</b>"); }
}
return sb.ToString();
}
}
I deliberately used RenderControl option and also a hard coded string
to show that you can write any control any way you want.
Building the Page – First Attempt
One option to use when we want to populate a ModalPopupExtender
dynamically is to use the DynamicPopulateExtender. This extender
helps us to dynamically populate target controls. You need to supply to
the extender the trigger for the population in the PopulateTriggerControlID,
the service that will help you to populate the control (in my example – the
ExampleService) and the TargetControlID. The following code shows a
DynamicPopulateExtender with it’s relevant properties:
<cc1:DynamicPopulateExtender ID="dpe" runat="server" TargetControlID="panelInfo"
PopulateTriggerControlID="btnDummy" ServicePath="ExampleService.asmx"
ServiceMethod="GetData" />
The following is a web page example that uses the DynamicPopulateExtender
to dynamically populate data into a ModalPopupExtender’s shown modal:
%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="TestModalDialog.WebForm2" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!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>
<style type="text/css">
.modal
{ background-color: Gray;
filter: alpha(opacity=40);
opacity: 0.7;
}
.modalPopup
{ background-color: #ffffdd;
border-width: 3px;
border-style: solid;
border-color: Gray;
padding: 3px;
width: 250px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="ExampleService.asmx" />
</Services>
</asp:ScriptManager>
<div>
<input type="button" id="btnDummy" runat="server" value="Get Data" />
<asp:Panel ID="pnlPopup" runat="server" CssClass="modalPopup">
<div>
<asp:Panel ID="panelInfo" runat="server">
</asp:Panel>
</div>
<cc1:DynamicPopulateExtender ID="dpe" runat="server" TargetControlID="panelInfo"
PopulateTriggerControlID="btnDummy" ServicePath="ExampleService.asmx" ServiceMethod="GetData" />
<div>
<asp:Button ID="btnDlgOK" runat="server" Text="OK" /></div>
</asp:Panel>
<cc1:ModalPopupExtender ID="mpeData" runat="server" OkControlID="btnDlgOK" PopupControlID="pnlPopup"
TargetControlID="btnDummy" BackgroundCssClass="modal" DropShadow="true">
</cc1:ModalPopupExtender>
</div>
</form>
</body>
</html>
Building the Page – Second Attempt
In the first example I used the DynamicPopulateExtender to populate
my modal popup. In this example I use the ModalPopupExtender’s
properties in order to do the same thing. ModalPopupExtender exposes
three properties:
- DynamicControlID – the control that will be populated dynamically.
- DynamicServicePath – the path to the ScriptService which will be used
to dynamically populate the control.
- DynamicServiceMethod – the method to call in the ScriptService.
Using these properties enables us to populate dynamically a control when a
modal pops up. The following example is doing the same like in the
first attempt but using the ModalPopupExtender’s properties:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="TestModalDialog.WebForm2" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!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>
<style type="text/css">
.modal
{ background-color: Gray;
filter: alpha(opacity=40);
opacity: 0.7;
}
.modalPopup
{ background-color: #ffffdd;
border-width: 3px;
border-style: solid;
border-color: Gray;
padding: 3px;
width: 250px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="ExampleService.asmx" />
</Services>
</asp:ScriptManager>
<div>
<input type="button" id="btnDummy" runat="server" value="Get Data" />
<asp:Panel ID="pnlPopup" runat="server" CssClass="modalPopup">
<div>
<asp:Panel ID="panelInfo" runat="server">
</asp:Panel>
</div>
<div>
<asp:Button ID="btnDlgOK" runat="server" Text="OK" /></div>
</asp:Panel>
<cc1:ModalPopupExtender ID="mpeData" runat="server" OkControlID="btnDlgOK" PopupControlID="pnlPopup"
TargetControlID="btnDummy" BackgroundCssClass="modal" DropShadow="true" DynamicControlID="panelInfo"
DynamicServiceMethod="GetData" DynamicServicePath="ExampleService.asmx">
</cc1:ModalPopupExtender>
</div>
</form>
</body>
</html>
Summary
There are two ways to dynamically populate a ModalPopupExtender.
The first way is to use the DynamicPopulateExtender. The second
way is to use the ModalPopupExtender’s properties that enables
dynamic content to show up in the modal popup.
CodeProject