Monday, May 25, 2009

Visual Studio 2010 Beta 1

Visual Studio 2010 Beta 1 is ready to download since May 20
then it's ready to test (and also the .Net Framework 4) by public.

URL to download:
Visual Studio 2010 and .NET Framework 4 Beta 1
http://msdn.microsoft.com/en-us/vstudio/dd582936.aspx

Visual Studio 2010 Product Highlights
http://msdn.microsoft.com/en-us/library/dd547188(VS.100).aspx

Visual Studio 2010 and .NET Framework 4 Training Kit - May Preview
http://www.microsoft.com/downloads/details.aspx?FamilyID=752CB725-969B-4732-A383-ED5740F02E93&displaylang=en

Visual Studio 2010 Samples
http://msdn.microsoft.com/en-us/vstudio/dd238515.aspx

Visual Studio 2010 and .NET Framework 4 Beta 1 Walkthroughs
http://msdn.microsoft.com/en-us/vstudio/dd441784.aspx
Share/Bookmark

Tuesday, May 19, 2009

My 100th Blog Entry!

I made it to 100! and it's just starting to grow up, Thank all the readers, it's a try to share and there is a hope to help. I learned a lot from others,and I decided to share. Till now, it visited from 51 countries, this encourages me to try more, cheers.

Coming soon: Many more blog entries! it'll continue.


Share/Bookmark

Monday, May 18, 2009

C# - Generic dictionary Types - Dictionary


Dictionary Class
Represents a collection of keys and values.
Namespace: System.Collections.Generic

http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

Sample code:

...
public Dictionary seasonDic =
new Dictionary();
...


Some sample methods to work with Dictionary

// Fill the Dictionary
private void fillSeasonDic()
{
seasonDic.Add("Spring", Color.LightGreen);
seasonDic.Add("Summer", Color.Orange);
seasonDic.Add("Autumn", Color.LightYellow);
seasonDic.Add("Winter", Color.LightBlue);
}

// Using .TryGetType to find [value] corresponding to the [key]
private Color getSeasonColor(string seasonName)
{
Color retColor = Color.White;

if ( ! string.IsNullOrEmpty(seasonName))
if ( ! seasonDic.TryGetValue(seasonName, out retColor)
retColor = Color.White;

return retColor;
}

// Retrieve data from a Dictionary by Enumerator
private string getAllSeasons()
{
StringBuilder sbRetVal = new StringBuilder();

Dictionary.Enumerator sEnum =
seasonDic.GetEnumerator();

while (sEnum.MoveNext())
sbRetVal.AppendLine(sEnum.Current.Key +
": " +
sEnum.Current.Value.Name);

return sbRetVal.ToString();
}

// Use [KeyValuePair] structure in a [foreach] loop
private string getAllColorSeasons()
{
StringBuilder sbRetVal = new StringBuilder();

foreach( KeyValuePair kvp in seasonDic )
sbRetVal.AppendLine(kvp.Value.Name + ": " + kvp.Key);

return sbRetVal.ToString();
}

private void btnGetAllSeason_Click(object sender, EventArgs e)
{
MessageBox.Show( this.getAllSeasons() +
"\r\n" +
this.getAllColorSeasons() );
}

Share/Bookmark

Friday, May 15, 2009

C# - Application.StartupPath - How to get the path for the executable file that started the application?

If you want to have access to the path of running application, there is a property that can give you the path. As an example this path can contain other files or folders to keep related data files to youe application and in this way you can work with those files without pointing to static directory addresses.

Application.StartupPath Property
Namespace: System.Windows.Forms

Application.StartupPath property gets the path for the executable file that started the application, not including the executable name.

Directory.SetCurrentDirectory Method
Sets the application's current working directory to the specified directory.
http://msdn.microsoft.com/en-us/library/system.io.directory.setcurrentdirectory.aspx

System.IO.Directory.GetCurrentDirectory()
A string containing the path of the current working directory.
http://msdn.microsoft.com/en-us/library/system.io.directory.getcurrentdirectory.aspx

Assembly.GetExecutingAssembly Method
Gets the assembly that contains the code that is currently executing.
http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getexecutingassembly.aspx

System.Reflection.Assembly.GetExecutingAssembly().Location
It returns the file name of the current binary

The following simple sample can show the result of aboved mentioned methods:

string dfltDir = @"C:\TEMP";
if( Directory.Exists( dfltDir ) )
Directory.SetCurrentDirectory( dfltDir );

StringBuilder sb = new StringBuilder();
sb.AppendLine("GetCurrentDirectory(): ");
sb.AppendLine( Directory.GetCurrentDirectory() );
sb.AppendLine();
sb.AppendLine( "Application.StartupPath: " );
sb.AppendLine( Application.StartupPath );
sb.AppendLine();
sb.AppendLine("Assembly.GetExecutingAssembly().Location: ");
sb.AppendLine( System.Reflection.Assembly.GetExecutingAssembly().Location);
sb.AppendLine();

MessageBox.Show(sb.ToString());

Share/Bookmark

Wednesday, May 13, 2009

C# - GZipStream to Zip and UnZip with Base64 Encoding

First of all, you can find sample code about Encoding and Decoding based on Base64 in the following link:

C# - UTF8/Base64 Encoder/Decoder
http://iborn2code.blogspot.com/search?q=Base64

class fbBase64
{
public static string EncodeToBase64(string theString)
{
return Convert.ToBase64String(
System.Text.Encoding.UTF8.GetBytes(theString));
}

public static string DecodeBase64(string theString)
{
return System.Text.Encoding.UTF8.GetString(
Convert.FromBase64String(theString));
}
}



public static bool GetZipBase64( string str2Zip, out byte[] aryBase64Zip )
{
bool retVal = true;
aryBase64Zip = null;

try
{
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream gzs = new GZipStream(ms, CompressionMode.Compress))
{
using (StreamWriter sw = new StreamWriter(gzs))
{
sw.Write(fbBase64.EncodeToBase64(str2Zip));
}
}
aryBase64Zip = ms.ToArray();
}
}
catch (Exception ex)
{
retVal = false;
MessageBox.Show(ex.ToString());
}
return retVal;
}



public static bool GetUnZipUnBase64( byte[] zipData, out string strOrgnl)
{
bool retVal = true;
strOrgnl = null;

try
{
using (MemoryStream ms = new MemoryStream(zipData) )
{
using (GZipStream gzs = new GZipStream(ms, CompressionMode.Decompress))
{
using ( StreamReader sr = new StreamReader(gzs) )
{
strOrgnl = fbBase64.DecodeBase64( sr.ReadToEnd() );
}
}
}
}
catch (Exception ex)
{
retVal = false;
MessageBox.Show(ex.ToString());
}
return retVal;
}

Share/Bookmark

Monday, May 11, 2009

C# - How to read or modify value of a key in app.Config


using System;
using System.Text;
using System.Configuration;
using System.Collections.Generic;

namespace myApp
{
class theAppCnfg
{
public static string GetKey( string keyName )
{
string retVal = string.Empty;
AppSettingsReader appCnfgRdr = new AppSettingsReader();
retVal = (string) appCnfgRdr.GetValue(keyName,typeof(string));

return retVal;
}

public static void ModifyKey(string keyName, string keyValue)
{
Configuration cnfg =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None );
cnfg.AppSettings.Settings[keyName].Value = keyValue;
cnfg.Save(ConfigurationSaveMode.Modified);
}

}
}

Share/Bookmark

Sunday, May 10, 2009

C# - Graphics Object - Pie Chart


This one comes with a [Form] which contains a [PictureBox] who called [chart]

We have two classes:
- [piePart] that collects name, value, and color for each pie part in our pie chart
- [pieChart] contains a generic List collection based on [piePart] class and a method which draw the chart which called [public Image doPieChart(Size pieSize)] and returns a bitmap or generated pie chart.

Codes for pieChart and piePart classes:

using System;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections.Generic;

namespace PieChart
{
public class piePart
{
public string pieName;
public float pieVal;
public Color pieColor;

public piePart()
{
}

public piePart(string _pieName, float _pieVal, Color _pieColor)
{
pieName = _pieName;
pieVal = _pieVal;
pieColor = _pieColor;
}
}

public class pieChart
{
public List lstPiePart = new List();

public pieChart()
{
}

public Image doPieChart(Size pieSize)
{
if (lstPiePart.Count == 0) return null;

Bitmap pieBmp = new Bitmap(pieSize.Width, pieSize.Height);
Graphics grfx = Graphics.FromImage(pieBmp);
grfx.SmoothingMode = SmoothingMode.HighQuality;

float totalPieValues = 0;
foreach (piePart aPie in lstPiePart)
{
if (aPie.pieVal <= 0)
{
string errMag =
"A Pie must have a positive value";
throw new ArgumentException(errMag);
}
totalPieValues += aPie.pieVal;
}

if ( totalPieValues <= 0 )
{
string errMsg =
"At least one Pie must have a greater than Zero value";
throw new ArgumentException(errMsg);
}

Rectangle pieRect =
new Rectangle(1, 1, pieSize.Width - 2, pieSize.Height - 2);
Pen piePen = new Pen(Color.Black, 1);
float pieStartAngle = 0;

foreach (piePart aPie in lstPiePart)
{
Brush pieBrush =
new LinearGradientBrush(pieRect,
aPie.pieColor,
Color.White,
(float)45 );
float pieSweepAngle = (aPie.pieVal / totalPieValues) * 360;
grfx.FillPie(pieBrush, pieRect, pieStartAngle, pieSweepAngle);
grfx.DrawPie(piePen, pieRect, pieStartAngle, pieSweepAngle);
pieStartAngle += pieSweepAngle;
}
return pieBmp;
}

}

}


Codes for Form class:

using System;
using System.Text;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections.Generic;

namespace PieChart
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Draw(object sender, PaintEventArgs e)
{
Draw();
}

private void Draw()
{
pieChart myChart = new pieChart();
myChart.lstPiePart.Add(new piePart( "Spring",
(float) 118.79,
Color.Green ) );
myChart.lstPiePart.Add(new piePart( "Summer",
(float) 67.23,
Color.Red));
myChart.lstPiePart.Add(new piePart( "Autumn",
(float) 96.14,
Color.Yellow));
myChart.lstPiePart.Add(new piePart( "Winter",
(float) 121.92,
Color.Blue));

chart.Image = myChart.doPieChart( new Size(200, 200 ) );
}

}
}

Share/Bookmark

Friday, May 8, 2009

C# - System.Drawing namespace & Graphics Object

To have a graphic UI, .NET prepared many graphic classes to display graphical objects
on a form or other Windows Forms control.

The System.Drawing namespace is included in .NET Framework to deal with graphic stuff.
The System.Drawing namespace contains many classes and the most common ones are as following:
- [Graphics] is used to draw to display devices
- [Pen] is used to draw lines and curves
- [Brush] and other classes drived from it are used to fill shapes.
- ...

The System.Drawing namespace contains some structures too, and most important ones are as following:
- [Color] which represent a color
- [Point] that has x and y cordinates for a point in two dimensional plane.
- [Rectangle] it has four integer values that represent the location and size of
a rectangle.
- [Size] Stores width and height of a rectabgle by integer values.
- ...

How to draw a line or shape:
- Create a [Graphics] object, using System.Windows.Forms.Control.CreateGraphics method.
- Create a [Pen] object.
- Call a method from the Graphics object to draw a shape using the [Pen].

Some of the Graphics object methods:
- [Clear] Fills the entire drawing surface with a color.
- [DrawEllipse] Draws an ellipse or a circle by a pair of height and width.
- [DrawIcon] Draws image of an icon at specified coordinates.
- [DrawImage] Draws an image at specified coordinates.
- [DrawLine] Draws a line between two points.
- [DrawLines] Draws a series of lines by an array of Point structures.
- [DrawPath] Draws a series of connected lines and curves.
- [DrawPie] Draws a pie shape, it needs a upper-left coordinate pair, a width, a height, and two radial lines.
- [DrawPolygon] Draws a multi sides shape by an array of Point structures.
- [DrawRectangle] Draws a square shape by a coordinate pair, a width, and a height.
- [DrawRectangles] Draws multiple rectangles by Rectangle structures.
- [DrawString] Draws a text string at the specified location, and specified Brush and Font.
Share/Bookmark

Tuesday, May 5, 2009

C# - Sample code - System.Xml.Serialization and XML serialization attributes



[XmlRoot ("Produts")]
public class product2Sell
{
[XmlAttribute] public int prdId;
public string prdName;
public decimal prdPrice;
public int prdQty;
public DateTime prdLastOrderDate;
[XmlIgnore] public DateTime prdLastShipDate;

public product2Sell()
{
}
}



private void btnXmlSerialize_Click(object sender, EventArgs e)
{
List lstProduct = new List();
for (int i = 0; i < 3; i++)
{
product2Sell prdItem = new product2Sell();
prdItem.prdId = i;
prdItem.prdName = "Product" + i.ToString();
prdItem.prdPrice = i * 10.75m;
prdItem.prdQty = i * 3 + 5;
prdItem.prdLastOrderDate = DateTime.Now.AddDays(-i * 3);
prdItem.prdLastShipDate = DateTime.Now.AddDays(i * 2);

lstProduct.Add(prdItem);
}

string fName = @"C:\FB\Tst.data";
using (FileStream fs = new FileStream(fName, FileMode.Create))
{
XmlSerializer xs = new XmlSerializer( typeof(List) );
xs.Serialize(fs, lstProduct);
}
}

private void btnXmlDeserialize_Click(object sender, EventArgs e)
{
string fName = @"C:\FB\Tst.data";
using (FileStream fs = new FileStream(fName, FileMode.Open))
{
XmlSerializer xs =
new XmlSerializer(typeof(List) );
List lstPrdItem =
(List) xs.Deserialize(fs);

MessageBox.Show("# of products: " + lstPrdItem.Count.ToString());
}
}

Share/Bookmark

Sunday, May 3, 2009

C# - System.Xml.Serialization namespace

Let's review something about XML serialization first:
- It provides interoperability and communicability with different platform and also flexibility to conform to XML schema as a pattern.
- XML serialization can not be used to serialize private data.
- A class which wants to be serialized by XML serialization should be public and all members should be defined as public too, and you have to create a parameterless constructor for that class.
- Arrays, collections, Data sets, instances of XmlElement or XmlNote class can be serialized with XmlSerializer

XML Serialization Attributes
It's possible to use attributes to create XML documents that conform to specific standards.
Example:
- [XmlIgnore] in front of a public properties and fields will cuase to ignore it when the class is serialized, it's similar to [NonSerialized] attribute in standard serialization.
- [AmlAttribute] will cause to consider the serialized member as XML attribute.

For more details and to see the list of attributes, please look at the following URL:
XmlAttributes Members
Share/Bookmark

Saturday, May 2, 2009

C# - System.Runtime.Serialization namespace


Serialization is the process of converting data into a byte stream that can be stored or transferred. The rule is to use BinarryFormatter for the best efficiency and SoapFormatter when you require portability, SoapFormatter provides less efficient but more interoperable rather than BinaryFormatter. There are two classes for formatting serialized data in the System.Runtime.Serialization namespace:

* BinaryFormatter
It's the most efficient way to serialize objetcs that will be available to use just by .NET Frameworkbased applications. If you are sure that your client opens the serialized objects by a .NET Framework application, BinaryFormatter would be the best.

* SoapFormatter
it's located in System.Runtime.Serialization.Formatters.Soap, and is reliable way to serialize objects that will bbe transmitted across a network or read by a non .NET Framework based application. SoapFormatter can work instead of BinaryFormatter too but the serialized object consume considerabaly more space. SOAP WEB services were the primarily target for SoapFormatter and even though that it can format data using Xml, but the most flexible way to perform serialization is using XML serialization for such a kind of situations.

SoapFormatter is not included as default like BinaryFormatter and you need to add System.Runtime.Serialization.Formatters.Soap.dll as reference.
Share/Bookmark

Friday, May 1, 2009

C# - How to implement OnDeserialization for [Serializable] class with [NonSerialized] members



[Serializable]
class ProductItem : IDeserializationCallback
{
#region Fields
private int prdId;
private string prdName;
private decimal prdPrice;
[NonSerialized] private decimal prdTax;
#endregion

#region Properties
public int PrdId
{
get { return prdId; }
set { prdId = value; }
}
public string PrdName
{
get { return prdName; }
set { prdName = value; }
}
public decimal PrdPrice
{
get { return prdPrice; }
set { prdPrice = value; }
}
public decimal PrdTax
{
get { return prdTax; }
set { prdTax = value; }
}
#endregion

public ProductItem(int _prdId, string _prdName, decimal _prdPrice)
{
PrdId = _prdId;
PrdName = _prdName;
PrdPrice = _prdPrice;
PrdTax = _prdPrice * 0.12m;
}

void IDeserializationCallback.OnDeserialization(object sender)
{
// Calculate tax after deserialization completes
PrdTax = PrdPrice * 0.12m;
}
}



private void btnSerializeCallBack_Click(object sender, EventArgs e)
{
ProductItem prdItemObj = new ProductItem(1, "Cranker", 10);
string fName = @"C:\FB\Tst.data";
using (FileStream fs = new FileStream(fName, FileMode.Create))
{
SoapFormatter sf = new SoapFormatter();
sf.Serialize(fs, prdItemObj);
}
}

private void btnDeSerializeCallBack_Click(object sender, EventArgs e)
{
string fName = @"C:\FB\Tst.data";
using (FileStream fs = new FileStream(fName, FileMode.Open))
{
SoapFormatter sf = new SoapFormatter();
ProductItem prdItemObj = (ProductItem)sf.Deserialize(fs);
}
}

Share/Bookmark