smart developer’s blog

This is a C# resource library! Free how to’s and best practices…

Archive for the ‘.Net’ Category

Improve WebClient by adding UserAgent and Cookies to your requests

leave a comment »

Suppose you need to make a lot of web requests and you need to set/change your user agent or to add cookies. You cannot do this by using the default WebClient in ASP.net but you can do it by extending this class:


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Net;
using System.Collections.Generic;

public class CGWebClient : WebClient
{
	private System.Net.CookieContainer cookieContainer;
	private string userAgent;
	private int timeout;

	public System.Net.CookieContainer CookieContainer
	{
		get { return cookieContainer; }
		set { cookieContainer = value; }
	}

	public string UserAgent
	{
		get { return userAgent; }
		set { userAgent = value; }
	}

	public int Timeout
	{
		get { return timeout; }
		set { timeout = value; }
	}

	public CGWebClient()
	{
		timeout = -1;
		userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727)";
		cookieContainer = new CookieContainer();
		cookieContainer.Add(new Cookie("example", "example_value"));
	}

	protected override WebRequest GetWebRequest(Uri address)
	{
		WebRequest request = base.GetWebRequest(address);
		RefreshUserAgent();

		if (request.GetType() == typeof(HttpWebRequest))
		{
			((HttpWebRequest)request).CookieContainer = cookieContainer;
			((HttpWebRequest)request).UserAgent = userAgent;
			((HttpWebRequest)request).Timeout = timeout;
		}

		return request;
	}

	private void RefreshUserAgent()
	{
		List<string> UserAgents = new List<string>();
		UserAgents.Add("Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727)");
		UserAgents.Add("Mozilla/4.0 (compatible; MSIE 8.0; AOL 9.5; AOLBuild 4337.43; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618)");
		UserAgents.Add("Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.34; Windows NT 6.0; WOW64; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30618)");
		UserAgents.Add("Mozilla/5.0 (X11; U; Linux i686; pl-PL; rv:1.9.0.2) Gecko/20121223 Ubuntu/9.25 (jaunty) Firefox/3.8");
		UserAgents.Add("Mozilla/5.0 (Windows; U; Windows NT 5.1; ja; rv:1.9.2a1pre) Gecko/20090402 Firefox/3.6a1pre (.NET CLR 3.5.30729)");
		UserAgents.Add("Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1b4) Gecko/20090423 Firefox/3.5b4 GTB5 (.NET CLR 3.5.30729)");
		UserAgents.Add("Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Avant Browser; .NET CLR 2.0.50727; MAXTHON 2.0)");
		UserAgents.Add("Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; Media Center PC 6.0; InfoPath.2; MS-RTC LM 8)");
		UserAgents.Add("Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; InfoPath.2; .NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618)");
		UserAgents.Add("Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)");
		UserAgents.Add("Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; Media Center PC 3.0; .NET CLR 1.0.3705; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.1)");
		UserAgents.Add("Opera/9.70 (Linux i686 ; U; zh-cn) Presto/2.2.0");
		UserAgents.Add("Opera 9.7 (Windows NT 5.2; U; en)");
		UserAgents.Add("Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.8pre) Gecko/20070928 Firefox/2.0.0.7 Navigator/9.0RC1");
		UserAgents.Add("Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.7pre) Gecko/20070815 Firefox/2.0.0.6 Navigator/9.0b3");
		UserAgents.Add("Mozilla/5.0 (Windows; U; Windows NT 5.1; en) AppleWebKit/526.9 (KHTML, like Gecko) Version/4.0dp1 Safari/526.8");
		UserAgents.Add("Mozilla/5.0 (Windows; U; Windows NT 6.0; ru-RU) AppleWebKit/528.16 (KHTML, like Gecko) Version/4.0 Safari/528.16");
		UserAgents.Add("Opera/9.64 (X11; Linux x86_64; U; en) Presto/2.1.1");

		Random r = new Random();
		this.UserAgent  = UserAgents[r.Next(0, UserAgents.Count)];

		UserAgents = null;
	}


}

Enjoy!

Advertisements

Written by smartdev

May 8, 2009 at 9:42 am

Linq in DataSet

with 2 comments

I recently had to filter and order some datasets. I used Linq and I found it to be very nice.
Here are a few examples:

1. If you have a dataset with a table containing products and you want to search for all products having “test” in their name, and order the list by creation date, you can use something like:


DataTable dt = ds.Tables[0]
			.AsEnumerable()
			.Where(o => o.Field<string>("Name").Contains("test"))
			.OrderBy(o => o.Field<DateTime>("CreationDate"))
			.CopyToDataTable();

2. Alternatively, if you have to order a report each time a column name is pressed, you can write you own method that orders a table by a given column:


private DataTable OrderDataTable<T>(DataTable dt, string orderby, string orderdir)
	{
	if(orderdir == "ASC")
		return dt.AsEnumerable().OrderBy(o => o.Field<T>(orderby)).CopyToDataTable();
	else
		return dt.AsEnumerable().OrderByDescending(o => o.Field<T>(orderby)).CopyToDataTable();
	}

and you can use it like this:


switch (orderby1)
	{
	case "Keyphrase":
		repMain.DataSource = OrderDataTable<String>(ds.Tables[0], orderby1, orderdir1);
		break;
	case "KEI":
		repMain.DataSource = OrderDataTable<Double>(ds.Tables[0], orderby1, orderdir1);
		break;
	default:
		repMain.DataSource = OrderDataTable<Int32>(ds.Tables[0], orderby1, orderdir1);	
		break;
	}

Have fun!

Written by smartdev

May 8, 2009 at 9:36 am

Posted in .Net, Programming

Tagged with , , ,

XPath vs Linq to XML

leave a comment »

Considering you have an xml file:


<Categories>
	<Category id="543" parentid="193" name="Bridal Jewellery & Accessories" treeactive="True">
		<Products>
		<Product id="6843" name="Pearl & Diamante Set">
			<Description><!&#91;CDATA&#91;Necklace and earrings with pearl style stones and diamante.</br>
Available in a choice of colours.</br>
Lifetime plating guarantee.&#93;&#93;></Description>
			<Stock>0</Stock>
			<Manufacturer>89</Manufacturer>
			<Supplier>A90/75043</Supplier>
			<Price>0.0000</Price>
			<RRP>0.0000</RRP>
			<CreationDate>01/01/0001 00:00:00</CreationDate>
			<Promo>False</Promo>
		</Product>
		<Product id="6844" name="Pearl & Diamante Set 2">
			<Description><!&#91;CDATA&#91;Necklace and earring set with diamante and pearl style stones.</br>
Lifetime plating guarantee.&#93;&#93;></Description>
			<Stock>0</Stock>
			<Manufacturer>89</Manufacturer>
			<Supplier>A90-75002</Supplier>
			<Price>0.0000</Price>
			<RRP>0.0000</RRP>
			<CreationDate>01/01/0001 00:00:00</CreationDate>
			<Promo>False</Promo>
		</Product>
	</Products>
	 </Category>
</Categories>

Basically there are two ways of querying XML files form C#:

1. The first one would be to use a XPath expresion. There are a few methods in System.Xml.XPath namespace (XPathEvaluate() which returns an object type, XPathSelectElement() which returns an XElement type and XPathSelectElemens() wich returns IEnumerable) that you can use.

For instance, in order to get all products containing “Pearl” in the product name, we will use something like this:


XmlReader reader = XmlReader.Create(filename);
XElement root = XElement.Load(reader);
reader.Close();
IEnumerable<XElement> children = root
				.XPathSelectElements("/Category/Products/Product[contains(@name,'Pearl')]");

2. Another way would be to use Linq to XML. The query is more complicated and not so compact as the XPath expression:


XmlReader reader = XmlReader.Create(filename);
XElement root = XElement.Load(reader);
reader.Close();
IEnumerable<XElement> children = root.Descendants("Category")
				.Descendants("Products")
				.Descendants("Product")
				.Where(o => o.Attribute("name").Value.Contains("Pearl"));

or


from xElem in root.Descendants("Category").Descendants("Products").Descendants("Product")
where xElem.Element("name").Value.Contains("Pearl")
select xElem;

I personally prefer to use XPath because it is more clearer. And sometimes there are queries that I couldn’t translate in Linq.

Lately, I was preocupied by the performance of each method and I was curios to find out which one is faster (for different sizes of xml files). So, I generated three xml files (small, medium and big) and tested 14 instructions on each file using both XPath and XML to Linq.

Unfortunatelly, we don’t have a clear result. Basically all times are the same no matter what we use – Linq or XPath. So, for now I guess I will stick to XPath only because it is more clearer :).

You can run the application here: http://seven.webme.ro/xpath/

xml_xpath

Written by smartdev

April 15, 2009 at 4:11 pm

Posted in .Net, Programming

Tagged with , ,

Crop image in ASP.Net (C#)

with one comment

You can use the custom method below:

public static void CropImageFile(string ImageFrom, string ImageTo, int targetW, int targetH)
{
Image imgPhoto = Image.FromFile(ImageFrom);
int targetX = (imgPhoto.Width – targetW) / 2;
int targetY = (imgPhoto.Height – targetH) / 2;

Bitmap bmPhoto = new Bitmap(targetW, targetH, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(72, 72);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
grPhoto.DrawImage
(
imgPhoto,
new Rectangle(0, 0, targetW, targetH),
targetX,
targetY,
targetW,
targetH,
GraphicsUnit.Pixel
);
// Save out to memory and then to a file. We dispose of all objects to make sure the files don’t stay locked.
EncoderParameters ep = new EncoderParameters(1);
ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)100);

ImageCodecInfo ici = GetEncoderInfo(“image/jpeg”);

imgPhoto.Dispose();
grPhoto.Dispose();

bmPhoto.Save(ImageTo, ici, ep);
bmPhoto.Dispose();
}

private static ImageCodecInfo GetEncoderInfo(String mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for(j = 0; j < encoders.Length; ++j) { if(encoders[j].MimeType == mimeType) return encoders[j]; } return null; } [/sourcecode] If you combine this with the thumbnail auto-generation you can get a nice method that can generate a cropped thumbnail. ๐Ÿ™‚

Written by smartdev

April 9, 2009 at 4:50 pm

Posted in .Net

Tagged with ,

Generate image thumbnails using ASP.NET(C#)

with 7 comments

You can use the GetThumbnailImage built-in method to generate a thumbnail using this method I created:

public static void CreateThumbnail(string ImageFrom, string ImageTo, int ImageHeight)
{
System.Drawing.Image i = System.Drawing.Image.FromFile(ImageFrom);

i.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
i.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

System.Drawing.Image th = i.GetThumbnailImage
(
ImageHeight * i.Width / i.Height,
ImageHeight,
new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback),
IntPtr.Zero
);
i.Dispose();

EncoderParameters ep = new EncoderParameters(1);
ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)80);
ImageCodecInfo ici = GetEncoderInfo(“image/jpeg”);

th.Save(ImageTo, ici, ep);
th.Dispose();
return;
}

private static ImageCodecInfo GetEncoderInfo(String mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for(j = 0; j < encoders.Length; ++j) { if(encoders[j].MimeType == mimeType) return encoders[j]; } return null; } public static bool ThumbnailCallback() { return true; } [/sourcecode] If the Image contains an embedded thumbnail image (all digital cameras attach a thumbnail to the big image), this method retrieves the embedded thumbnail and scales it to the requested size. But the problem is that in most of the cases we do not want this because we want to generate thumbnails bigger than 150-200 pixels as embwdded thumbnails have and this will lead in poor quality images for 400-500 pizels or more thumbnail sizes. The workaround is to use this piece of code: [sourcecode language="csharp"] i.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); i.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); [/sourcecode] By fliping the image twice we get a new image identical with the original one but without the embedded thumbnail. Now the resulted thumbnail is in a very good quality. If you combine this with the cropped image auto-generation you can get a nice method that can generate a cropped thumbnail. ๐Ÿ™‚

Written by smartdev

April 9, 2009 at 3:41 pm

Posted in .Net, Programming

Tagged with ,

How to generate a vCard file

with 6 comments

Ever needed to dinamically generate a vCard file?ย The syntax is very simple. Just generate a .vcf text file and open it!

You can find many link resources here. Also, you can find a nice generator here:ย http://www.vicintl.com/vcf/.

I managed to create a simple C# script that generates this file. The result was as expected:


BEGIN:VCARD
FN:Mr. John P. Smith, Jr.
TITLE:General Manager
ORG:XYZ Corp.;North American Division;Manufacturing
ADR;POSTAL;WORK:;;P.O. Box 10010;AnyCity;AnyState;00000;U.S.A.
LABEL;POSTAL;WORK;ENCODING=QUOTED-PRINTABLE:P.O. Box 10010=0D=0A=
Anywhere, TN  37849=0D=0A=U.S.A.
ADR;PARCEL;WORK:;133 Anywhere St.;Suite 360;AnyCity;AnyState;00000;U.S.A.
LABEL;POSTAL;WORK;ENCODING=QUOTED-PRINTABLE:133 Anywhere St.=0D=0A=
Anywhere, TN  37849=0D=0A=U.S.A.
TEL;Work;VOICE;MESG;PREF:+1-234-456-7891 x56473
TEL;Home:+1-234-456-7891
TEL;Pager:+1-234-456-7891
TEL;Cell:+1-234-456-7891
TEL;Modem;FAX:+1-234-456-7891,,*3
EMAIL;Internet:webmaster@anywhere.com
URL:http://www.anywhere.com/mrh.vcf
UID:http://www.anywhere.com/mrh.vcf
TZ:-0500
BDAY:1997-11-29
REV:20090401T065518
VERSION:2.1
END:VCARD

generated this:

vcard_noimage

The real challenge camed when I treid to add a image to my vCard file. I couldn’t fint it on the Internet to a quick Export using the Outlook 2007 revealed the secret: all you have to do is to add a new line to your .vcf file:


PHOTO;TYPE=JPEG;ENCODING=BASE64:
YOUR BASE64 ENCODED IMAGE HERE

In order to generate the “YOUR BASE64 ENCODED IMAGE HERE” string in C# you can use the following method:


private string EncodeWithString(string ImagePath)
	{
		System.IO.FileStream inFile;
		byte[] binaryData;

		try
		{
			inFile = new System.IO.FileStream(ImagePath,
											  System.IO.FileMode.Open,
											  System.IO.FileAccess.Read);
			binaryData = new Byte[inFile.Length];
			long bytesRead = inFile.Read(binaryData, 0,
										(int)inFile.Length);
			inFile.Close();
		}
		catch (System.Exception exp)
		{
			// Error creating stream or reading from it.
			//System.Console.WriteLine("{0}", exp.Message);
			//return;
			return exp.Message;
		}

		// Convert the binary input into Base64 UUEncoded output.
		string base64String;
		try
		{
			base64String =
			   System.Convert.ToBase64String(binaryData,
											 0,
											 binaryData.Length);
		}
		catch (System.ArgumentNullException)
		{
			//System.Console.WriteLine("Binary data array is null.");
			//return;
			return "Binary data array is null.";
		}

		// Write the UUEncoded version to the output file.

		return base64String;
	}

Now, the new result is real magic:

vcard_image

Written by smartdev

April 6, 2009 at 3:20 pm

Posted in .Net, Programming

Tagged with ,

How to make a CheckBox fire the ItemCommand Event of a Repeater

leave a comment »

Today I needed to add a check box control to a repeater’s item template and have it fire the ItemCommand event on the repeater.ย ย I could’t do that, because this control (Checkbox) does not trigger this event. So, I searched the Internet and I found this cool new control:


using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace smartdev.web.Controls
{
    public class CheckBoxRepeaterAware : CheckBox
    {
        #region Properties

        #region CommandName

        public string CommandName
        {
            get
            {
                if (this.ViewState["CommandName"] == null)
                {
                    return string.Empty;
                }
                else
                {
                    return this.ViewState["CommandName"] as string;
                }
            }
            set
            {
                this.ViewState["CommandName"] = value;
            }
        }

        #endregion

        #region CommandArgument

        public string CommandArgument
        {
            get
            {
                if (this.ViewState["CommandArgument"] == null)
                {
                    return string.Empty;
                }
                else
                {
                    return this.ViewState["CommandArgument"] as string;
                }
            }
            set
            {
                this.ViewState["CommandArgument"] = value;
            }
        }

        #endregion

        #endregion

        #region Procedures

        #region On Checked Changed

        protected override void OnCheckedChanged(EventArgs e)
        {
            //create a new event args of type command event args
            CommandEventArgs ce = new CommandEventArgs(this.CommandName, this.CommandArgument);

            //allow the base checkbox to handle the event as normal
            base.OnCheckedChanged(e);

            //raise the contorls method RaiseBubbleEvent
            base.RaiseBubbleEvent(this, ce);
        }
        #endregion

        #endregion
    }
}

I hope you will find this usefull.

Written by smartdev

April 4, 2009 at 1:17 pm