Friday, May 27, 2011

for loop vs foreach vs fordelegate vs LINQ vs Lambda loops

By seeing below report foreach is almost equal to lambda expression

Report - each Method 10 Iteration
Method Name : For :52
Method Name : ForEach :29
Method Name : ForEachDelegate :25
Method Name : Linq :37
Method Name : Lambda :33


Important - Run the code in Release Mode


static void Main(string[] args)
{
Test t = new Test();
t.AllTests();
}

class Avg
{
public int Time { get; set; }
public string MethodName { get; set; }
}

class Test
{
delegate void TestMethod();
List m_Source = new List();
List Average = new List();
System.Diagnostics.Stopwatch m_Watch
= new System.Diagnostics.Stopwatch();

public void AllTests()
{
for (int i = 0; i < 1000000; i++)
m_Source.Add(i);
TestMethod _TestFor = new TestMethod(TestFor);
TestMethod _TestForEach = new TestMethod(TestForEach);
TestMethod _TestForEachDelegate = new TestMethod(TestForEachDelegate);
TestMethod _TestLinq = new TestMethod(TestLinq);
TestMethod _TestLambda = new TestMethod(TestLambda);
//TestMethod _TestParallel = new TestMethod(TestParallel);

// how many time to repeat each test?

for (int i = 1; i < 10; i++)
{
TestThis(_TestFor);
TestThis(_TestForEach);
TestThis(_TestForEachDelegate);
TestThis(_TestLinq);
TestThis(_TestLambda);
//TestThis(_TestParallel);
Console.WriteLine(string.Empty);
}
var a1 = (from a in Average
group a by a.MethodName into g
select new { MethodName = g.Key, AvgTime = g.Sum(a2 => a2.Time) / g.Count() }).ToList();

foreach (var g in a1)
{
Console.WriteLine("Method Name : {0} :{1}", g.MethodName, g.AvgTime);
}

Console.Read();
}

void TestThis(TestMethod test)
{
m_Watch.Reset();
m_Watch.Start();
test.Invoke();
var _Time = (int)m_Watch.Elapsed.TotalMilliseconds;
var _Method = test.Method.Name.Replace("Test", string.Empty);
var _Result = string.Format("{1}\t{0}", _Method, _Time);
Average.Add(new Avg() { MethodName = _Method, Time = _Time });
Console.WriteLine(_Result);
}

void TestFor()
{
var _Target = new List();
for (int i = 0; i < m_Source.Count(); i++)
_Target.Add(m_Source[i] + 1);
_Target.ToArray().Count();
//Debug.Assert(m_Source.Count() == _Target.ToArray().Count());
}

void TestForEach()
{
var _Target = new List();
foreach (int i in m_Source)
_Target.Add(i + 1);

_Target.ToArray().Count();
//Debug.Assert(m_Source.Count() == _Target.ToArray().Count());
}

void TestForEachDelegate()
{
var _Target = new List();
m_Source.ForEach((int i) =>
{
_Target.Add(i + 1);
});
_Target.ToArray().Count();
//Debug.Assert(m_Source.Count() == _Target.ToArray().Count());
}

void TestLinq()
{
var _Target = from i in m_Source
select i + 1;
_Target.ToArray().Count();
//Debug.Assert(m_Source.Count() == _Target.ToArray().Count());
}

void TestLambda()
{
var _Target = m_Source.Select(i => i + 1);
_Target.ToArray().Count();
//Debug.Assert(m_Source.Count() == _Target.ToArray().Count());
}

void TestParallel()
{
// TODO
}
}

Friday, October 29, 2010

Reading WSDL from both webservice and WCF

HI,
i have changed little bit code in below url to read wsdl object from WCF also.

http://mikehadlow.blogspot.com/2006/06/simple-wsdl-object.html

Test Code


private void button1_Click(object sender, EventArgs e)
{
string url = txtUrl.Text;

WebServiceInfo webServiceInfo;

WebRequest.DefaultWebProxy = WebRequest.GetSystemWebProxy();
try
{
webServiceInfo = WebServiceInfo.OpenWsdl(new Uri(url));
}
catch
{
NetworkCredential credentials =
new NetworkCredential("userId", "password");
WebProxy proxy = new WebProxy("xx.xx.xx.xx:8080",
true, null, credentials);
WebRequest.DefaultWebProxy = proxy;
webServiceInfo = WebServiceInfo.OpenWsdl(new Uri(url));
}

StringBuilder sb = new StringBuilder();

int i = 1;
string strParameter = "";
foreach (WebMethodInfo method in webServiceInfo.WebMethods)
{
sb.Append(i.ToString() + ". " + string.Format("{0}",
method.Name));

foreach (Parameter parameter in method.InputParameters)
{
strInputParameter += string.Format("{0} {1},", parameter.Type,
parameter.Name);
}
if (strInputParameter != "")
{
strInputParameter = strInputParameter.Substring(0,
strInputParameter.Length - 1);
sb.Append("(" + strInputParameter + ")");
strInputParameter = "";
}
else
{
sb.Append("()");
}
sb.Append("\r\n");
i++;
//foreach (Parameter parameter in method.OutputParameters)
//{
// sb.Append(
// string.Format("\t\t\t{0} {1}", parameter.Name,
//parameter.Type));
//}
}


txtOperations.Text = "";
txtOperations.Text = sb.ToString();
}




wsdl class coding

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Web.Services.Description;
using System.Net;
using System.Xml.Schema;



///
/// A collection of WebMethodInfo objects
///

public class WebMethodInfoCollection : KeyedCollection
{
///
/// Constructor
///

public WebMethodInfoCollection() : base() { }

protected override string GetKeyForItem(WebMethodInfo webMethodInfo)
{
return webMethodInfo.Name;
}
}


///
/// represents a parameter (input or output) of a web method.
///

public struct Parameter
{
///
/// constructor
///

///
///
public Parameter(string name, string type)
{
this.Name = name;
this.Type = type;
}

///
/// Name
///

public string Name;
///
/// Type
///

public string Type;
}

///
/// Information about a web service operation
///

public class WebMethodInfo
{
string _name;
Parameter[] _inputParameters;
Parameter[] _outputParameters;

///
/// OperationInfo
///

public WebMethodInfo(string name, Parameter[] inputParameters,
Parameter[] outputParameters)
{
_name = name;
_inputParameters = inputParameters;
_outputParameters = outputParameters;
}

///
/// Name
///

public string Name
{
get { return _name; }
}

///
/// InputParameters
///

public Parameter[] InputParameters
{
get { return _inputParameters; }
}

///
/// OutputParameters
///

public Parameter[] OutputParameters
{
get { return _outputParameters; }
}
}

///
/// Information about a web service
///

public class WebServiceInfo
{
WebMethodInfoCollection _webMethods =
new WebMethodInfoCollection();
private XmlSchemaSet e = new XmlSchemaSet();
Uri _url;
string _serviceName = "";
static Dictionary _webServiceInfos =
new Dictionary();

///
/// Constructor creates the web service info from the given url.
///

///
private WebServiceInfo(Uri url)
{
if (url == null)
throw new ArgumentNullException("url");
_url = url;
_webMethods = GetWebServiceDescription(url);
}

///
/// Factory method for WebServiceInfo. Maintains a
/// hashtable WebServiceInfo objects
/// keyed by url in order to cache previously accessed wsdl files.
///

///
///
public static WebServiceInfo OpenWsdl(Uri url)
{

WebServiceInfo webServiceInfo;
if (!_webServiceInfos.TryGetValue(url.ToString(), out webServiceInfo))
{

webServiceInfo = new WebServiceInfo(url);
_webServiceInfos.Add(url.ToString(), webServiceInfo);
//_webServiceInfos.Add(url.ToString(), null);
}
return webServiceInfo;
}

///
/// Convenience overload that takes a string url
///

///
///
public static WebServiceInfo OpenWsdl(string url)
{
Uri uri = new Uri(url);
return OpenWsdl(uri);
}

///
/// Load the WSDL file from the given url.
/// Use the ServiceDescription class to walk the wsdl and
/// create the WebServiceInfo
/// instance.
///

///
private WebMethodInfoCollection GetWebServiceDescription(Uri url)
{
UriBuilder uriBuilder = new UriBuilder(url);
uriBuilder.Query = "WSDL";

WebMethodInfoCollection webMethodInfos = new WebMethodInfoCollection();

HttpWebRequest webRequest =
(HttpWebRequest)WebRequest.Create(uriBuilder.Uri);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Method = "GET";
webRequest.Accept = "text/xml";

ServiceDescription serviceDescription;

using (System.Net.WebResponse response = webRequest.GetResponse())
using (System.IO.Stream stream = response.GetResponseStream())
{
serviceDescription = ServiceDescription.Read(stream);
}
_serviceName = serviceDescription.Name;
desc(serviceDescription, url);

foreach (PortType portType in serviceDescription.PortTypes)
{
foreach (Operation operation in portType.Operations)
{
string operationName = operation.Name;
string inputMessageName = operation.Messages.Input.Message.Name;
string outputMessageName = operation.Messages.Output.Message.Name;

// get the message part
string inputMessagePartName =
serviceDescription.Messages[inputMessageName].Parts[0].Element.Name;
string outputMessagePartName =
serviceDescription.Messages[outputMessageName].Parts[0].Element.Name;

// get the parameter name and type
Parameter[] inputParameters = GetParameters(inputMessagePartName);
Parameter[] outputParameters = GetParameters(outputMessagePartName);

WebMethodInfo webMethodInfo = new WebMethodInfo(
operation.Name, inputParameters, outputParameters);
webMethodInfos.Add(webMethodInfo);
}
}

return webMethodInfos;
}

///
/// Walk the schema definition to find the parameters of the given message.
///

///
///
///
private Parameter[] GetParameters(string messagePartName)
{


List parameters = new List();

//Types types = serviceDescription.Types;
//System.Xml.Schema.XmlSchema xmlSchema = types.Schemas[0];

foreach (XmlSchemaElement schemaElement in e.GlobalElements.Values)
{

//}
//foreach (object item in xmlSchema.Items)
//{
// System.Xml.Schema.XmlSchemaElement schemaElement = item as System.Xml.Schema.XmlSchemaElement;
if (schemaElement != null)
{
if (schemaElement.Name == messagePartName)
{
System.Xml.Schema.XmlSchemaType schemaType = schemaElement.SchemaType;
System.Xml.Schema.XmlSchemaComplexType complexType =
schemaType as System.Xml.Schema.XmlSchemaComplexType;
if (complexType != null)
{
System.Xml.Schema.XmlSchemaParticle particle = complexType.Particle;
System.Xml.Schema.XmlSchemaSequence sequence = particle as System.Xml.Schema.XmlSchemaSequence;
if (sequence != null)
{
foreach (System.Xml.Schema.XmlSchemaElement childElement in sequence.Items)
{
string parameterName = childElement.Name;
string parameterType = childElement.SchemaTypeName.Name;
parameters.Add(new Parameter(parameterName, parameterType));
}
}
}
break;
}
}
}
return parameters.ToArray();
}


private void desc(ServiceDescription serviceDescription, Uri baseUri)
{
//Uri baseUri = new Uri(A_0);
foreach (XmlSchema schema in serviceDescription.Types.Schemas)
{
if (schema.Items.Count > 0)
{
e.Add(schema);
}
foreach (XmlSchemaObject obj2 in schema.Includes)
{
if (obj2 is XmlSchemaImport)
{
try
{
string schemaUri = new Uri(baseUri, ((XmlSchemaImport)obj2).SchemaLocation).AbsoluteUri;
e.Add(((XmlSchemaImport)obj2).Namespace, schemaUri);
continue;
}
catch (Exception)
{
continue;
}
}
}
}
e.CompilationSettings.EnableUpaCheck = false;
e.Compile();
}
///
/// WebMethodInfo
///

public WebMethodInfoCollection WebMethods
{
get { return _webMethods; }
}

///
/// Url
///

public Uri Url
{
get { return _url; }
set { _url = value; }
}
public string ServiceName
{
get { return _serviceName; }
set { _serviceName = value; }
}

}




Thursday, September 30, 2010

MSBuild Copy files and folders



Its working fine...

<PropertyGroup>
<OutputFolder>D:\TempASP\MsBuild\Deploy</OutputFolder>
<DeployPath1>D:\TempASP\MsBuild\1</DeployPath1>
</PropertyGroup>

<ItemGroup>
<MyWebService Include="$(OutputFolder)\**\*.*" />
</ItemGroup>

<!-- Copy using the metadata -->
<Copy SourceFiles="@(MyWebService)" DestinationFolder="$(DeployPath1)\%(MyWebService.RecursiveDir)" />