Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Archive for October, 2010

FTP Commands to upload file

Posted by JP on October 30, 2010

Sometimes you might end up with a machine where the ftp tools are not accessible.  Here we can use the ftp.exe command line tool along with Windows Operating system.

Step1:

Type ftp in the windows run command box.

image

Step2:

In the appearing command line window type open www.yoursite.com. (I am typing my site named www.fortuneanalyst.com)

It will be prompting for the user name and password.

image

Step3:

Type your username and press enter.  Wait for 2 seconds and you will be prompted for the password.  Type the correct password and press enter.  Wait for 2 seconds and if the password is valid you will be getting the message”User * logged in”.

Note: The password typed won’t be displayed on the screen.

image

If you can see the above message Congratulations!!! You have successfully logged in.

Now we can move to the next step

Step 4:

Type the command dir in the above screen.  Wait for 2 seconds.  You will be listed with the directories and files in the root folder.

Step 5:

Create a new directory named “fxlogics”.  For creating a new directory use command

mkdir fxlogics

Step 6:

Copy files to the new directory.

First we have to change the directory to fxlogics.  For this type the command

cd fxlogics

Step 7:

You can ensure you are in the correct directory by entering the dir command again.

Step 8: Upload File

Here you are uploading a file from the local computer to the ftp site’s current directory.

Use command put filepath

Alternatively you can type put and drag and drop the file from explorer to the command window.  So the exact path will be shown correctly.

Eg: put c:\readme.txt

Step 9:

Ensure the file is copied correctly by typing the dir command again.

If you can see the file in the command screen you have uploaded the file successfully.

Step 10:

Close the command window by typing the quit command.

More Commands

Command Description Example
help Shows the commands list help
quit Closes the ftp window quit
dir Displays the directory contents dir
cd Change directory cd mydir
mkdir Make Directory mkdir newdirname
put Uploads a file from the local file system. put “c:\program files\a.txt”
delete Deletes the file from the directory delete “the file name.exe”

 

Tips

You can use the up and down arrow while in the command window, to traverse between the commands typed.  It will save the time and effort to type the command again.

Hope you enjoyed the article 🙂

Advertisements

Posted in C# | Tagged: , , , | 2 Comments »

WinForms: How to create a control from another thread?

Posted by JP on October 28, 2010

Control.CheckForIllegalCrossThreadCalls = false; is needed for refreshing controsl from other threads.

But for creating controls and setting parent to other control which was created in another thread the following code is needed.

Pre-requisites

Create a new windows forms application and place a button with click event handler on it.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Threading;

 

namespace WindowsFormsApplication1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        public delegate void DelegateDefinition();

 

        private void button1_Click(object sender, EventArgs e)

        { 

            DelegateDefinition delgate = new DelegateDefinition(CreateButton);

            ThreadStart threadStart = new ThreadStart(delegate { this.BeginInvoke(delgate); });

            Thread thread = new Thread(threadStart);

            thread.Start();

        }

 

        public void CreateButton()

        {

            Button button = new Button();

            button.Parent = this;

            button.Location = new Point(10, 10);

            button.Size = new Size(200, 25);

            button.Text = "Hi! I am the new button";

        }

    }

}

 

Posted in WinForms | Tagged: , , | Leave a Comment »

The system tables in Sql Server

Posted by JP on October 28, 2010

We can use the sys.tables and sys.objects to find metadata of tables and columns.

Display all User Tables

select * from sys.tables – displays all user tables

Display all Columns in a Table

select * from sys.columns where object_id in
(select object_id from sys.tables where name=’MyTable)

Posted in C# | Tagged: , | Leave a Comment »

Delegates, Anonymous Methods, Lambda Expressions and Advantage, Built-in Delegates (Func, Action, Predicate), Examples

Posted by JP on October 19, 2010

The world have started moving from object oriented programming to functional programming.  The Lambda Expressions in C# is definitely providing many advantages like reduced code and speed above the traditional programming.  Learning Lambda Expressions and the built-in methods in C# is not too hard, but requires sincere efforts. 

Power of Lambda

It is for sure that Lambda will reduce the code and execution time.

For example consider the case where a list contains numbers from 1 to 10, You wanted to print the numbers divisible by 2.

The code will be:

List<int> list = new List<int>(new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } );

           

foreach(int number in list)

if ((number %2)== 0)

            Console.WriteLine(number.ToString());

 

The same code for iterating, checking and displaying is combined using Lambda Expressions in one line as following:

list.Where(x => x > 0).ToList().ForEach(x => Console.WriteLine(x.ToString()));

Here we have reduced the code from 3 lines to 1 and the coding efforts too.  Above that, it is very interesting to use Lambda expressions.  Believe me!!

So I would like to start from the first step towards Lambda Expressions – that is delegates.  Learning one concept per day would be more easier and give more confidence in using it.

Delegates

Delegate is a type that references a method.  Same like a class variable can refer to an object instance, we can assign methods to the delegate variable.  It was a feature introduced in C# 2.0.

Example:

  public delegate void SimpleDelegate();

 

        static void Main(string[] args)

        {

            SimpleDelegate simpleDelegate = SimpleMethod;

            simpleDelegate();

 

            Console.ReadKey();

        }

 

        public static void SimpleMethod()

        {

            Console.WriteLine("Hi!");

        }

How it can be helpful? 

We can use delegates to create a skeleton of a method that would be used by multiple classes.  Event handlers can be created using delegates.

More Info: http://msdn.microsoft.com/en-us/library/ms173171(VS.80).aspx

Anonymous Methods

Anonymous methods were also introduced in C# 2.0 version.  Sometimes we run into cases like we have to create a method for assigning to events.  In this case, instead of creating a method, we can create inline methods – those are methods without a name.

Eg: In an ASP.NET application, we are setting the event handler of a button. The code will look like:

        protected void Page_Load(object sender, EventArgs e)

        {

            Button button = new Button();

            button.Click += new EventHandler(button_Click);

        }

 

        void button_Click(object sender, EventArgs e)

        {

           

        }

Here button_Click() is the method for the event handler.  The same code can be replaced as following using anonymous methods.

        protected void Page_Load(object sender, EventArgs e)

        {

            button1.Click += delegate(object s1, EventArgs e1)

            {

            };

        }

Please note that the delegate keyword is used to place the anonymous method.

In the above code we have saved one method and used inline coding for event handler.  This is a step towards our real aim – Lambda Expressions.

Delegates – Custom Delegate

Let us take another advanced example of Anonymous methods.  Here we are creating a custom delegate.  The WriteMessageDelegate delegate takes a string as argument and returns void.  It can be used as a callback mechanism to write messages globally in an application.

 

    public class Operation

    {

        public delegate void WriteMessageDelegate(string write);

 

        public void Do(WriteMessageDelegate write)

        {

            write("From Do() method.");

        }

    }

Test code is following: Here we are declaring a method named WriteMessage with same signature of the previous WriteMessageDelgate and then passing it to the Do method. 

    class Program

    {

        static void Main(string[] args)

        {

            Operation operation = new Operation();

            operation.Do(WriteMessage); // See the method pointer we are passing

 

            Console.ReadKey();

        }

 

        public static void WriteMessage(string message)

        {

            Console.WriteLine(message);

        }

    }

Please note that the Do method will be invoking the WriteMessage.

(One may get confused that statement operation.Do(WriteMessage); would be calling the WriteMessage. No!  This is just passing the method reference only)

If you can understand the above code, Congratulations!!!  You have just learned how to use delegates as arguments.

 

Lambda Expressions

A lambda expression is an anonymous function that can contain expressions and statements.

All lambda expressions uses the operator =>, which means “goes to”.

Eg: ForEach(argument => Console.WriteLine(argument));

The left hand side of => represents function arguments.

and the right hand side is the statement using argument.

Here the “argument” denotes the method argument and the operation on the right hand side.

This could be equivalent to the following lines:

        public void Write(string argument)

        {

            Console.WriteLine(argument);

        }

invoked as: list.ForEach(Write);

Example on Lambda

Consider we are having a list of string items.  We need to sort them using descending order.  So we have to implement the Compare() delegate.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            List<string> names = new List<string>();

            names.Add("Haq");

            names.Add("Jean");

            names.Add("Swami");

            names.Add("Gokila");

            names.Add("Meg");

 

            names.Sort((s1, s2) => s2.CompareTo(s1)); // Sorting

 

            names.ForEach(s => Console.WriteLine(s));

            Console.ReadLine();

        }

    }

}

Note: All the examples are intended to have System.Linq in the namespace section.

Sorting Example

Lambda Expression Without
names.Sort((s1, s2) => s2.CompareTo(s1));

names.Sort(

                delegate (string s1, string s2)

                {

                     return s2.CompareTo(s1);

 

                }

             );

 

Integer OrderBy Example

Lambda Expression Without
names.OrderBy(s => int.Parse(s));

names.Sort(

                delegate (string s1, string s2)

                {

                     return

int.Parse(s2).CompareTo(int.Parse(s1));

 

                }

             );

Note: The Sort() method actually changes the list, but OrderBy() gives an ordered view only without actually changing the list.

Integer OrderBy With Console Print

using System.Linq;

Namespace to include

List<string> list = new List<string>();

list.Add("1");

list.Add("10");

list.Add("2"); 

Code to Arrange

list.OrderBy(s => int.Parse(s)).ToList().ForEach(s => Console.WriteLine(s));

Lambda Code

list.Sort(delegate(string s1, string s2)

{

    return int.Parse(s1).CompareTo(int.Parse(s2));

}

);

 

foreach (string s in list)

    Console.WriteLine(s);

Regular Code

 

Selecting distinct Items With Console Print

using System.Linq;

Namespace to include

List<string> list = new List<string>();

list.Add("1");

list.Add("1");

list.Add("2"); 

list.Add("2"); 

Code to Arrange

list.Distinct(s => s).ToList().ForEach(s => Console.WriteLine(s));

Lambda Code

IList<string> unique = new List<string>();

            foreach (string s in list)

                if (!unique.Contains(s))

                    unique.Add(s);

foreach (string s in unique)

    Console.WriteLine(s);

Regular Code

 

Posted in Lambda Expressions | Tagged: , , | Leave a Comment »

Using xml column in sql server with XSD enabled

Posted by JP on October 18, 2010

For a long time I was wondering about why the xml type is needed in sql server.  Following are a few number of advantages on using xml column types which I found implemented in industry.

  • We can store entire xml content in the column and later query on the xml tags
  • We can store application properties like Company Name, Address etc. as xml tags and with the advantage of extensibility
  • We can reduce the number of relational tables with the power of extensibility on adding new xml elements

In this article I am trying to show how xml data types can be used in sql server along with xsd (xml schema definition)

Scenario

We need to create a Customer table having Id and Name of the customer and the order created by him.  An order contains multiple items and at a time the customer is having only one order.

The default implementation would look like:

Customer OrderHeader OrderDetail
Id Id Id
Name OrderDate Item
  CustomerId Quantity

 

We can implement the same using xml type as:

Customer
Id
Name
Orders (XML data type)

 

Step1: Creating the table

You can create the table using Sql Server Management Studio.  The Sql Server version which I am using is 2005.

image

Once created the table like above, you can try inserting data into it.

INSERT INTO Customer(Id, Name, Orders)

 

VALUES (

1,

‘Joe C’,

N‘<Orders></Orders>’

);

If you are able to execute the query successfully.  Congratulations!  That seems to be a valid the table creation.

Step2: Create the XSD

The above table design is good to proceed but not the best!  The user can store any xml in the column that would be difficult for us to parse back.  So we need to ensure that only the right format of xml can be stored in the column.  We can achieve the above using XSD enabling.

The XSD is an xml format definition which says what should be the xml data stored in.  If an attempt to save an invalid format the database will throw exception.

For creating an xsd the following sql can be used. (Please remember to delete the previous records from the table)

CREATE XML SCHEMA COLLECTION OrdersSchema AS

<schema xmlns="http://www.w3.org/2001/XMLSchema"&gt;

  <element name="Orders">

    <complexType>

      <sequence>

        <element name="Order" minOccurs="0">

                  <complexType>

                        <attribute name="Id" type="int" use="required" />

                        <attribute name="Item" type="int" use="required" />

                        <attribute name="Quantity" type="float" use="required" />

                  </complexType>

        </element>

      </sequence>

    </complexType>

  </element>

</schema>’

GO

After running the query successfully, you can ensure the schema was created in sql server by expanding the Programmability tree.

image

Step3: Set the XSD to our xml column

Open the Customer table in modify mode and select the ‘Orders’ column and se the ‘OrdersSchema’ to the Schema Collection property of it.

image

Save the table so that now onwards the XSD validation is enabled.

Testing the Table

You can test the above table by using following query:

DELETE FROM customer

 

INSERT INTO Customer(Id, Name, Orders) VALUES (1, ‘Joe C’,N‘<Orders><Order Id="1" Item="Laptop" Quantity="10"></Order></Orders>’);

INSERT INTO Customer(Id, Name, Orders) VALUES (2, ‘Dane K’,N‘<Orders><Order Id="2" Item="Pen Drive" Quantity="500"></Order></Orders>’);

INSERT INTO Customer(Id, Name, Orders) VALUES (3, ‘Mark V’,N‘<Orders><Order Id="3" Item="Mobile Phone" Quantity="30"></Order></Orders>’);

 

If you get the following results, then You are good.

(3 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

You can see the existing records by the query:

SELECT * FROM Customer;

image

Testing with a wrong Xml

You can check whether the xml schema validation is working by trying the following query which contains an “InvalidAttribute”

INSERT INTO Customer(Id, Name, Orders) VALUES (100, ‘Joe C’,N‘<Orders><Order InvalidAttribute="Value" Id="1" Item="Laptop" Quantity="10"></Order></Orders>’) 

Posted in C# | Tagged: , , , | Leave a Comment »

Command Pattern – Undo Example

Posted by JP on October 18, 2010

Friends, here I am trying to show the usage of Command Design Pattern, one among 23 design patterns.

Personally I like this pattern very much, it is making use of good object oriented constructs and simplifies the logic of enabling Undo. 

Scenario

You are working on a painting application.  For each brush stroke you need to provide the Undo feature.

The brushes presently available are square and rectangle. In future more and more brushes will be available.  Our challenge is to provide the user with Undo feature. Clearly, on clicking the undo button, the last stroke should be cleared from the canvas.

CommandPattern.png

Command Pattern applied to the scenario

The definition of Command Pattern says “Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations”

Command Pattern Explained

The pattern says that all the operations should be converted into objects, so that we log the objects.  In future we can call Do() or Undo() operations on the object.   The object should be smart enough to store the request parameters inside it to support the Do and Undo operations.

Command Pattern for our Scenario

Applied to our scenario, we have got two brushes:

  • Square Brush
  • Rectangle Brush

The other parameters would be Canvas which is the PictureBox control on which we draw and the X, Y location on mouse pointer on the canvas.   Formulating this we can create 2 classes:

SquareCommand class for square drawing operation and Rectangle class for rectangle drawing operation.

The Do() operation would be drawing a square for the square class and drawing a rectangle for the rectangle class.

We can formulate an interface called ICommand having the Do() and Undo() methods.

public interface ICommand

{

void Do();

void Undo();

}

The classes would be SquareCommand and RectangleCommand which implement s the above interface.

Architecture – Class Diagram

2.gif

Implementation

When the application is executed, the user will be having a blank white screen, with a set of colors to choose from.  The default brush selected will be Square and on clicking the canvas a new square will be drawn on the canvas.  The default color selected is Blue and is stored in the variable _activeColor.

The form level variables declared are:

private ShapeEnum _activeShape = ShapeEnum.Square;

private Color _activeColor = Color.Blue;

private Bitmap _bitmap;

private Graphics _graphics;

For each mouse down operation a new square class will be created.  That means if 10 clicks are made 10 square classes will be created and the Do() operation is called   An enumeration variable called _activeShape is used to keep track of the current shape selected by the user.  The mouse down event would look like the following.

private void Canvas_MouseDown(object sender, MouseEventArgs e)

{

// Each mouse down creates a new command class instance

ICommand command = null;

if (_activeShape == ShapeEnum.Square)

command = new SquareCommand(_bitmap, _activeColor, e.X, e.Y);

else if (_activeShape == ShapeEnum.Rectangle)

command = new RectangleCommand(_bitmap, _activeColor, e.X, e.Y);

command.Do();

_commandStack.Push(command);

RefreshUI();

}

Let us take an example: assume the user clicked the mouse at Point X=100 and Y=200.  As the _activeShape is Square,  a new SquareCommand class instance is created with arguments e.X and e.Y.  The remaining arguments are bitmap and the active color.  Then the command instance would be pushed to a stack and the Do() operation is called.

The stack provides a storage for usage of the command instance later.  The declaration of stack is:

private Stack<ICommand> _commandStack = new Stack<ICommand>();

Inside the SquareCommand Class

We can have a look on the Square class.  Both the SquareCommand and RectangleCommand class will be having same implementations except in the Do() operation of drawing the respective shape.

public class SquareCommand : ICommand

{

private Point _point;

private Bitmap _bitmap;

private Graphics _graphics;

private Color _color;

public SquareCommand(Bitmap bitmap, Color color, int x, int y)

{

_bitmap = bitmap;

_graphics = Graphics.FromImage(_bitmap);

_color = color;

_point = new Point(x, y);

}

public void Do()

{

// Save the current pixel colors for a future UNDO perform

SaveCurrentPixels();

// Do the drawing

_graphics.FillRectangle(new SolidBrush(_color),

new Rectangle(_point.X, _point.Y, Width, Height));

}

private const int Width = 50;

private const int Height = 50;

private IList<Color> _colors = new List<Color>();

private void SaveCurrentPixels()

{

for (int i = _point.X; i < _point.X + Width; i++)

for (int j = _point.Y; j < _point.Y + Height; j++)

_colors.Add(_bitmap.GetPixel(i, j));

}

/// <summary>

/// Perform Undo by restoring back the pixels to previous colors

/// </summary>

public void Undo()

{

int ix = 0;

for (int i = _point.X; i < _point.X + Width; i++)

for (int j = _point.Y; j < _point.Y + Height; j++)

_bitmap.SetPixel(i, j, _colors[ix++]);

}

}

The constructor is called with the bitmap and the x, y positions which are then stored into class fields.  When the Do() method is called the current pixel colors are saved into the _colors list.  This would enable us to perform the Undo() method later.  After that the graphics.FillRectangle() method is called to draw the square.  The width and height of the square would be set to 50 pixels using the constants Width and Height respectively.

The Undo() method just restores the previous pixel values using the bitmap.SetPixel method() by iterating through each pixel starting from x, y position.

Performing the Undo() on clicking Undo button

As we encapsulated each operation to a class with parameters and logged them into the command stack, it is now easier to call the Undo() method.  Please remind that on clicking the Undo button we have to get the last operation instance and call the Undo() method of it, and removing it from the stack.

The code for it is:

private void UndoButton_Click(object sender, EventArgs e)

{

// Check command stack contains items

if (_commandStack.Count > 0)

{

// Remove the last command

ICommand lastCommand = _commandStack.Pop();

// Call the Undo method

lastCommand.Undo();

}

RefreshUI();

}

First, the command stack count is checked to ensure there are commands inside it.  Then the last command is popped out using the Pop() method.  It will give us the last instance in the stack as well as removes it.  Then, the Undo() operation is invoked. After, the RefreshUI() method is called to update the UI with the changes.

Note

The command pattern provides an object oriented manner to provide Undo feature to our application in a flexible manner.

But the creation of lot of object instances is one of the draw back of this method which usually people say about.  I would say that in the other hand, the command pattern is giving us the advantage of keeping the code more manageable.

Source Code

I am happy to let you know that the source code for the article is available at c-sharpcorner.com

Link: http://www.c-sharpcorner.com/uploadfile/40e97e/3862/default.aspx

Posted in C#, Design Patterns | Tagged: , , , , | Leave a Comment »

HttpHandler – A Certificate example

Posted by JP on October 13, 2010

Scenario

You are a developer at Grade Nineteen University. One of the recent requirments the management had is to create an online certificate.
So that the students that pass out should be able to view their Certificates online. This will definitely add some technological edge to the university.

The student will be given his own certification url as following: http://www.cert19.edu/certificates/100.cert

On accessing the url, the following Certifcate image will be displayed for the student id: 100

(100.cert should be interpreted as “Show Certificate for Student Id as 100)

clip_image002

Easy Way of Implementation – But not the Best

The first thought of implementation would be to create jpg files for all the students and copy them into the cert folder of the website. This approach is feasible but following overheads are there:

· For 1000 students passed out each year it requires 50 MB disk space.

· While backing up database of site, we have to do backup of jpg files too which is tedious.

If we have to take a backup of the site, we have to copy the files separately and do the database backup separately.

Http Handlers for the Rescue – A better Approach

We can achieve the same behavior with little overheads – by avoiding files creation for certificates.

We can use the database records to dynamically create certificate based on the student url.

By default the ISAPI handlers, handle the .aspx url extensions. We have to create a new handler for .jpg file handling that would be redirected to our certificate creation code.

Steps

1. Create a new web application project

Create a new web application project and name it as Grade19University

2. Create a new class and implement the IHttpHandler interface

Create a new class named “CertHandler” and implement the IHttpHandler interface

Add the following code.

public class CertHandler : IHttpHandler

{

public bool IsReusable

{

get { return false; }

}

/// <summary>

/// Core Method

/// </summary>

/// <param name="context"></param>

public void ProcessRequest(HttpContext context)

{

StudentLibrary studentLibrary = new StudentLibrary();

Bitmap image = studentLibrary.GetCertificate

(context.Request.Url.ToString());

if (image != null)

{

context.Response.ContentType = "image/bmp";

image.Save(context.Response.OutputStream, ImageFormat.Bmp);

}

else

context.Response.Write("Invalid Student Id!");

}

}

// The StudentLibrary class contains all student id lookup and image generating code

// A Certificate template is stored in application resource file

3. Modify the config file

Open the web.config file and in the httpHandlers section add the new verb

<httpHandlers>

<add verb="*" path="*.cert" validate="false" type="Grade19University.CertHandler, Grade19University"/>

</httpHandlers>

4. Run the application and test the url

You can execute the application and see the certificates. The library contains 3 students information.

http://localhost:32971/certificates/101.cert

http://localhost:32971/certificates/102.cert

http://localhost:32971/certificates/103.cert

Note

We can add more optimizations to the code like verifying the raw url, customizing the error messages etc.

The source code can be found in c-sharpcorner.com

http://www.c-sharpcorner.com/uploadfile/40e97e/3806/default.aspx

Posted in ASP.NET | Tagged: , , | Leave a Comment »

How to Serialize a non-serializable class in .Net?

Posted by JP on October 13, 2010

Although we can use BinarySerializer to serialize objects, the constraint is that we have to mark the class as [Serializable].

This could not be feasible as we have to deal with different kinds of objects which contains other types.

The Solution

Use XmlSerializer for the purpose.

  private void Button_Click(object sender, EventArgs e)

        {

            Book book = new Book();

            book.Title = "Rich Dad Poor Dad";

            book.ReleaseDate = new DateTime(2000, 1, 1);

            book.Author = new Author() { Name = "Robert Kiyosaki", Email = "rkiyosaki@richdad.com" };

 

            book.AuthorList = new List<Author>();

            book.AuthorList.Add(book.Author);

            book.AuthorList.Add(book.Author);

 

            book.Price = 6.9f;

 

            List<Book> books = new List<Book>() { book, book };

 

            // Serialize

            SerializeToXML(books);

 

            // Deserialize

            books = DeserializeFromXML();

        }

 

        public void SerializeToXML(List<Book> movies)

        {

            XmlSerializer serializer = new XmlSerializer(typeof(List<Book>));

            TextWriter textWriter = new StreamWriter(@"C:\movie.xml");

            serializer.Serialize(textWriter, movies);

            textWriter.Close();

        }

 

        public List<Book> DeserializeFromXML()

        {

            XmlSerializer deserializer = new XmlSerializer(typeof(List<Book>));

            TextReader textReader = new StreamReader(@"C:\movie.xml");

            List<Book> movies;

            movies = (List<Book>)deserializer.Deserialize(textReader);

            textReader.Close();

 

            return movies;

        } 

 

        // Classes

 

        public class Book

        {

            public string Title

            { get; set; }

 

            public float Price

            { get; set; }

 

            public DateTime ReleaseDate

            { get; set; }

 

            public Author Author { get; set; }

 

            public List<Author> AuthorList { get; set; }

        }

 

        public class Author

        {

            public string Name { get; set; }

            public string Email { get; set; }

        }

Posted in C# | Tagged: , | Leave a Comment »

How to generate a bitmap dynamically in ASP.NET?

Posted by JP on October 12, 2010

There are two steps in this process

Step1: Create the bitmap dynamically

private Bitmap GetDynamicBitmap()

{

Bitmap bitmap = new Bitmap(100, 100);

      Graphics graphics = Graphics.FromImage(bitmap);

      graphics.DrawString("Dynamic Bitmap", new Font("Calibri", 14, FontStyle.Bold), Brushes.Black,

      new PointF(10, 10));

 

      return bitmap;

}            

Step2: Set the http response to bitmap

Bitmap bitmap = GetDynamicBitmap();

context.Response.ContentType = "image/bmp";

bitmap.Save(context.Response.OutputStream, ImageFormat.Bmp);

Posted in C# | Tagged: , , | Leave a Comment »

Global Exception Handler in WinForms

Posted by JP on October 12, 2010

This is a small code snippet to set the global exception handler in Windows Forms application.

Setting a global exception handler can help us in logging the exceptions to a common file, show them to the user in a friendly way or email to the moderator.

// Place the code inside Program.cs, before Application.Run

Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

 

public static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
    // Process the e.Exception
    MessageBox.Show("I got the exception!");
}

Posted in WinForms | Tagged: , , | Leave a Comment »