smart developer’s blog

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

Google Chrome Extension: Google Weather

leave a comment »

I have just developed a nice Google Weather extension. You can find it here:ย Google Chrome Extensions: Google Weather.

I hope you will enjoy it!

I will make available soon the source code. Just stay tunned or leave a comment if interested!

Written by smartdev

January 14, 2010 at 9:19 pm

SQL queries running slow from web

leave a comment »

If you have a MSSQL query (stored procedure) that runs OK (fast) in the Query Analyzer or Management Studio but extremely slow when you run them from a web page, then the solution is one of the following (in this order):

– try to update statistics and recompile.
– try rebuilding indexes.
– try a query hint.

For me, recompiling (altering the procedure using WITH RECOMPILE option) always worked. Because SQL can optimize and compile a stored procedure, they run more quickly than the equivalent SQL statements executed from Query Analyzer (or perhaps passed in from a Web page or C# application). You can also run your procedure with the WITH RECOMPILE option:

EXEC procedure WITH RECOMPILE

But be careful when you use this option because sometimes the cost of recompilation can be big. If the procedure is long and have many queries, the recompilation itself could degrade performance.

Written by smartdev

July 23, 2009 at 11:11 am

Posted in SQL

Tagged with , ,

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!

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 ,