Monday, February 23, 2009

run a standalone web test application

Introduction

Hello, VS.Net 2008 has a utility tool for Performance Testing. Simply it listens for web requests and response and generate code according to these requests. But what could we do if we want to execute these requests in another application. it is required to make some enhancement on existing code. As code generator dependes on HttpWebTestRequest, we need to wrap it to HttpWebRequest.



Solution





ASsume code generated is GetRequestEnumerator, which returns all requests recorded from visual studio testing tool.


public override IEnumerator GetRequestEnumerator()
{
WebTestRequest request1 = new WebTestRequest("http://www.masrawy.com/");
request1.Encoding = System.Text.Encoding.GetEncoding("utf-8");
request1.ThinkTime = 300;
yield return request1;
request1 = null;
WebTestRequest request2 = new WebTestRequest("http://www.masrawy.com/");
request2.Encoding = System.Text.Encoding.GetEncoding("utf-8");
request2.QueryStringParameters.Add("hl", "en", false, false);
request2.QueryStringParameters.Add("q", "gmail", false, false);
request2.QueryStringParameters.Add("meta", "", false, false);
request2.QueryStringParameters.Add("aq", "0", false, false);
request2.QueryStringParameters.Add("oq", "Gma", false, false);
yield return request2;
request2 = null;
}





we will make our cusomized execution function


void execute()
{
IEnumerator requests = GetRequestEnumerator();
int count = 0;
while (requests.MoveNext())
{
try
{
#region wrapping from WebTestRequest to WebRequest
Console.WriteLine("In request NUM " + count++);
WebTestRequest currentRequest = requests.Current;
HttpWebRequest httpRequest;
string URL = currentRequest.Url;
if (currentRequest.QueryStringParameters.Count > 0)
{
for (int i = 0; i < i ="="" httprequest =" (HttpWebRequest)HttpWebRequest.Create(URL);" method =" currentRequest.Method;" credentials =" CredentialCache.DefaultNetworkCredentials;" impersonationlevel =" System.Security.Principal.TokenImpersonationLevel.None;" timeout =" 10000;" keepalive =" true;" encoding =" new" posteddata =" currentRequest.Body.ToString();" contentlength =" PostedData.Length;" stream =" httpRequest.GetRequestStream();" data =" encoding.GetBytes(PostedData);"> 0)
{
Console.WriteLine("Thinkin in " + currentRequest.ThinkTime);
Thread.Sleep(currentRequest.ThinkTime);
}
#endregion
# region get response
WebResponse response = httpRequest.GetResponse();
Console.WriteLine("Succeed Response");
Console.WriteLine("**************\n");
#endregion
}
catch (Exception ex)
{
Console.WriteLine("Failed Response"+ex.Message);
}
}
Console.WriteLine("All Requests are Finished");
}





We can take that function and call it through main function, like that


public static void Main()
{
Console.WriteLine("welcome, Press a key to begin sending requests");
Console.Read();
try { new WebTest1Coded().execute(); }
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.Read();
Console.Read();
}


Result
we can get that application and measure its execution performance through any measurement too.

Thanks and waiting for ur comment

Tuesday, February 17, 2009

.Net Remoting, Object Activation Types

Introduction

This articles assumes that you have initial background about .Net Remoting, Just We descripe Object Activation Concept.

What Is Object Activation?
object activation referes to the way which the remote object can be instantiated. There are two types of activation:

- Server Activation Object(SAO)
It means that object instantiating is occured on server, and client can access that object via a proxy.
There are two types of activation: Single Ton, and Single Call

Single Call: Means that every request from client to server, a new object is created.
Single Ton: an object is created first time only.

Let's Type a code
// Server Side

// Create an instance of a channel
TcpChannel channel = new TcpChannel(8080);
ChannelServices.RegisterChannel(channel, true);
Console.WriteLine("Channel Registered");

//Register Service as single call
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(ClientHandler),
"HelloWorld",WellKnownObjectMode.SingleCall);

//But if u want to register service as a signle ton
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(ClientHandler),
"HelloWorld",WellKnownObjectMode.SingleTon);


Example
Assume we have class ClientHandler that represents remote object

public class ClientHandler : MarshalByRefObject
{
int x = 0;

public void add(int y)
{
x+= y;
Console.WriteLine("after add, x=" + x);
}
}


Build your server program as above, according u activation type.

then Build client program

// Create a channel for communicating w/ the remote object
// Notice no port is specified on the client
TcpChannel chan = new TcpChannel();
ChannelServices.RegisterChannel(chan, true);

object obj = Activator.GetObject(
typeof(Test.NetRemoting.ClientHandler),
"tcp://habdelmawgood:8080/HelloWorld");


ClientHandler cHandler = (ClientHandler)obj;
if (obj.Equals(null))
{
System.Console.WriteLine("Error: unable to locate server");
}
else
{
cHandler.add(10);
cHandler.add(20);
}


- what result appears in server if we execute as single call
after add, x=10
after add, x=20

that means that object is initialized every time a method is called


- what result appears in server if we execute as single Ton
after add, x=10
after add, x=30

It assumes that it works fine, but problem appears when we make a new object again, result appears

after add, x=40
after add, x=60

that means that object is created once for specific client only once at a time. it has a life time specfied by configuration.

- Client Activation Object(CAO)
It means that object instantiating is occured on client

- Build Server Program


// Create an instance of a channel
TcpChannel channel = new TcpChannel(8080);
ChannelServices.RegisterChannel(channel, true);
Console.WriteLine("Channel Registered");

RemotingConfiguration.ApplicationName = "HelloWorld";
RemotingConfiguration.RegisterActivatedServiceType(typeof(ClientHandler));

- Build Client Program

// Create a channel for communicating w/ the remote object
// Notice no port is specified on the client
TcpChannel chan = new TcpChannel();
ChannelServices.RegisterChannel(chan, true);


RemotingConfiguration.RegisterActivatedClientType(typeof(ClientHandler), "tcp://habdelmawgood:8080/HelloWorld");
ClientHandler obj = new ClientHandler();
ClientHandler cHandler = (ClientHandler)obj;
if (obj.Equals(null))
{
System.Console.WriteLine("Error: unable to locate server");
}
else
{
cHandler.add(10);
cHandler.add(20);
}

Result: If we execute server and client

after add, x=10
after add, x=30

create object again
after add, x=10
after add, x=30

that means object is is instantiated every time a client need.

Thanks Alot for reading my articles, and waiting for your comments.

Monday, February 16, 2009

Helper Class For Event Logging, C#


public class LoggingHelper
{
public enum LoggingType
{
File, EventLog
}

public enum EventType
{
Error, Information, Warning
}

private string strLoggingFilePath, strEventLogCategoryName;


LoggingType objLogType;
///


/// Logging class constructor to initialize the logging process
///

/// Logging can be in File or in the EventLog
/// If the selected type is File then Name will be the File Path,
/// if the selected type is the Event log then Name will be the Event Category Name

public LoggingHelper(LoggingType LogType, string Name)
{
objLogType = LogType;
switch (LogType)
{
case (LoggingType.EventLog):
strEventLogCategoryName = Name;
if (!System.Diagnostics.EventLog.SourceExists(Name))
{
System.Diagnostics.EventLog.CreateEventSource(Name, Name);
}

break;
case (LoggingType.File):
strLoggingFilePath = Name;
if (!Directory.Exists(Path.GetDirectoryName(strLoggingFilePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(strLoggingFilePath));
}
break;
}
}
public void LogEvent(string Event, EventType Type)
{
StreamWriter EventWriter;
if (objLogType == LoggingType.EventLog)
{
EventLog.WriteEntry(strEventLogCategoryName, Event, Type == EventType.Error ? EventLogEntryType.Error : Type == EventType.Information ? EventLogEntryType.Information : Type == EventType.Warning ? EventLogEntryType.Warning : EventLogEntryType.SuccessAudit);
}
else if (objLogType == LoggingType.File)
{
if (!File.Exists(strLoggingFilePath))
{
EventWriter = new StreamWriter(strLoggingFilePath, false);
}
else
{
EventWriter = new StreamWriter(strLoggingFilePath, true);
}
EventWriter.WriteLine(DateTime.Now.ToString() + "/t" +
Event, Type == EventType.Error ? "Error" : Type == EventType.Information ? "Information" : Type == EventType.Warning ? "Warning" : ""
+ "/t" + Event);
}
}

Wednesday, February 11, 2009

Helper Class For XML Seriazliation- C#

using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Inputter
{
class Helber
{
///
/// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
///

/// Unicode Byte Array to be converted to String
/// String converted from Unicode Byte Array
private String UTF8ByteArrayToString(Byte[] characters)
{
UTF8Encoding encoding = new UTF8Encoding();
String constructedString = encoding.GetString(characters);
return (constructedString);
}


///
/// Converts the String to UTF8 Byte array and is used in De serialization
///

///
///
private Byte[] StringToUTF8ByteArray(String pXmlString)
{
UTF8Encoding encoding = new UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(pXmlString);
return byteArray;
}
///
/// Method to convert a custom Object to XML string
///

/// Object that is to be serialized to XML
/// XML string
public String SerializeObject(Object pObject)
{
try
{
String XmlizedString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(Info));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);


xs.Serialize(xmlTextWriter, pObject);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
return XmlizedString;
}
catch (Exception e)
{
System.Console.WriteLine(e);
return null;
}
}
///
/// Method to reconstruct an Object from XML string
///

///
///
public Object DeserializeObject(String pXmlizedString)
{
XmlSerializer xs = new XmlSerializer(typeof(Info));
MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);


return xs.Deserialize(memoryStream);
}
}

[Serializable]
public class Info
{
public int id;
public string name;
}

}

Note 1: This code is extracted from that link http://www.dotnetjohn.com/articles.aspx?articleid=173