This blog is subject the DISCLAIMER below.
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, September 13, 2010

Do people in non-English-speaking countries code in English?

I was reading a question with the same name on Stack-Exchange Beta site for Non-programmer-related questions (aka Programmers) when I came across this answer posted by a (probably Ukrainian) developer named Igor.

Accompanied by an earlier attempt by a colleague at work to write an enum in Arabic, I tried to write this piece of code:

Strangely enough it compiled and even ran showing the expected output (10)!! Note, the order above of the 2nd & 3rd line is mingled due to RTL issues in Gist. Visual Studio will show it in the right order (or at least, a more readable order for me, copy it & past it in your IDE to know how it looks).

Off course, I’m pretty convinced that this isn’t the best practice you should follow, (check my answer to the same question). Yet, I find this really hilarious! As a matter of fact, I took the claim that it’s bad practice too much for granted to the extent that I’ve never even tired to write such a strange piece of code :D

.. more.

Friday, July 09, 2010

Changing regional settings for System accounts (including ASPNET) in Windows 7

One of the small issues I faced while switching my development machine to windows 7 was a bug/exception in an application I was working on in parsing date format.

After switching my regional settings to the “expected” format, I still got the same exception. After playing a little with the regional settings, I realized that I was switching only my account date format, not the whole machine's date format. To push those settings to other system accounts (like ASPNET, etc), I did the following steps:

After setting your your account regional settings, switch to “Administrative” tab:

Click to Enlarge

From “Welcome screen and new user accounts”, click “Copy setting”:

Click to EnlargeMake sure “Welcome screen and system accounts”  check box is checked, press ok, and Voila!

.. more.

Tuesday, May 25, 2010

How to consume REST based-services?

Q. How to consume REST based-services?
Assume we have REST based-service contains method Add which takes two operands op1 and op2 and return the summation.

A. Create any project type (Console, Windows or even Web-based application)
Add using System.Net; using System.IO;
Write some code to consum the service
string parameters;
string response;
// Create the request obj
WebRequest request = WebRequest.Create("serviceURL/Add");
// Set values for the request back
request.Method = "POST"; //REST based-services using Post method
request.ContentType = "application/json"; //tells request the content typs is JSON
parameters = "{\"op1\":2,\"op2\":\"1\"}";
request.ContentLength = parameters.Length;
// Write the request
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
requestWriter.Write(parameters);
requestWriter.Close();
// Do the request to get the response
StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
response = responseReader.ReadToEnd();
responseReader.Close();
//response value should be 3 if you implement Add method correctly :))

.. more.

Saturday, December 05, 2009

How to create a C# Class from XML file (via xsd.exe)

A friend asked me a couple of times about how to I created the class I used in “twitter common friends” to handle xml as objects (includes reading & writing back). Actually the tool (xsd.exe) is pretty simple & takes no more than a couple of commands to create the class for me.

It’s just that I usually forget the keywords/parameters & their order (you can create a dataset or class that can be C# or VB, & there’s a couple of other option I never used before). I usually refer to its MSDN page when asked..

So I thought a post would be easier to remember. First you should create the xsd file out of the xml, using the VS command prompt:

xsd myFile.xml

That will create “myFile.xsd”, now to create “myFile.cs”, write the below line:

xsd myFile.xsd /c

Now you can add the cs file to your project & use it as illustrated in my previous post.

.. more.

Saturday, September 12, 2009

Reading POP3 (secure) SSL like Gmail via C#

Friend of mine asked me about reading messages by pop3 protocol using C#code. After I did some search in Google I got a lot of pop agents that working fine but not with Gmail as it uses secure connection (SSL) so I did new search in google and sourceforge but most of them have exceptions or not working fine and this is the main reason for this post to continue work from the point I have stoped.

After a hard search in alot of pages I got two good result :
1- it is a good project (from this blog) have good description that implements the standard POP3 commands like authenticating, receiving stats, retrieving and deleting messages .

2-There are open source project called OpenPOP in sourefourge but have bugs and fixed (here) in this blog by Kiran banda,unfortantualy it have build errors but i fix it (here) but it needs some work to go live.

Related post :
Reading Atom feed of Gmail inbox via C#




.. more.

Friday, September 11, 2009

Reading Atom feed of Gmail inbox via C#



Today I am coming with Gmail feature that may be useful although many people don't know and how to access it via simple C# code.
Gmail Atom feed is xml format file to know the unread messages .

http://mail.google.com/mail/feed/atom/ shows the most recent unread items from your inbox. Gmail also offers feeds for your labels:http://mail.google.com/mail/feed/atom/labelname/ .
To know the feature in detials go to this link @ (the unofficial news and tips about Google).

As a developer you can download the C# example here.
All what you need is create instance a simple class called GmailHandler and drop this lines in your project.


//just 2 steps to get your Gmail Atom
//1- Create the object from GmailHandler class
GmailHandler gmailFeed = new GmailHandler("WriteHereYourGmailUserName(ex: fci-h)", "WriteHereYourGmailPassword(ex: XXX)");
//2-get the feed :) ,Congratulations
XmlDocument myXml = gmailFeed.GetGmailAtom();


Just happy code :)

.. more.

Saturday, August 15, 2009

Integrating SSIS with C# to deliver very scalable Data-Driven Solution

نوضح في هذه المقاله استخدام ال SSIS لبناء C# application to get very scalable data-driven solution و كيفيه ارتباط ال C# بالـ SSIS

ما هم ال SSIS ؟؟ كيفيه الحصول عليه ؟؟ وماهي مميزاته؟؟ وفيما يستخدم اكثر؟؟

اولا SSIS تعني SQL Server Integration Services وهى احدى منتجات ميكروسوفت ويأتي مع جميع نسخ ال SQL Server ما عدا ال Express كان يسمى فيما سبق DTS لكن SSIS يعتبر منتج جديد وليس تحديثا من ال DTS

هي اداه قامت ميكروسوفت بتطويره و اخراجه للسوق عام 2007 وتهدف الى نقل البيانات من اكثر من Data Repository الى Data Repository اخر مثلا نقل البيانات من ملف نصي، ملف Excel او قاعاده بيانات SQL or Access الى جدول في قاعده بيانات في ال SQL Server دون الحاجه لوجود SQL Server ولا يجب مصدر البيانات او وصول البيانات SQL Server بأختصار يكمن استخدمها لنقل البيانات من ملف نصي الى قاعده بيانات Oracle تعتبر ال SSIS اداه ETL (Extract, Transform, and Load) اي انها تقوم بأخد البيانات من المصادر تحسين البيانات بشكل وتنظيمه وبعد هذا نقلها الى نقطه الوصول.

.. more.

Monday, June 01, 2009

.NET Framework Posters (4 and 3.5)

While I am google for .NET Framework 3.5 Poster to see some new namespaces , I got .NET Framework 4 Poster so I want to share the both with you here.

.NET Framework 3.5 :

DotNet_poster_xps_large.xps 1.5 MB

DotNt_poster_xps_split.xps 1.8 MB

NET_35_Namespaces_Poster_JAN08.pdf 849 KB

NET35_Namespaces_Poster_Tiled_JAN08.pdf 25MB

All of them are available in this link

.NET Framework 4:
You can find in the next link two version for framework 4, the first is silverlight with deep zoom and the second is PDF high resolution version.
They are available in this link

.. more.

Tuesday, April 28, 2009

How to create SQL Server Login programmatically?

Q. How to create SQL Server Login programmatically?

I got this question from Daniweb C# forum, and of course when I need to do something against SQL Server object from .net I go to SMO (SQL Server Management Objects) which provides a great functionalities to do anything with SQL Server instead of going on SSMS and create some scripts then embedding them into stored procedure then call it…. off…

Anyway to avoid showing how much I’m talkative…

Create any C# project type (Windows, Class Library or even Console one), add reference to Microsoft.SqlServer.Smo, Microsoft.SqlServer.ConnectionInfo
and Microsoft.SqlServer.SqlEnum

Server sqlServerInstance = new Server(                 new Microsoft.SqlServer.Management.Common.ServerConnection(                 new System.Data.SqlClient.SqlConnection("Data Source=.;Initial Catalog=Master;Integrated Security=True")));// your connection string I place mine for illustration..             Login loginObj = new Login(sqlServerInstance, @"DomainName\UserName");             loginObj.DefaultDatabase = "Master";             loginObj.LoginType = LoginType.WindowsUser;             loginObj.Enable();             loginObj.Create("password"); //set the password             //there're many properties to do some tasks related to Login object...

If you used LoginType.WindowsUser, be sure to provide valid windows username and if you aren’t on Domain use the machine name instead.



If you need to create SQL login use LoginType.SqlLogin…



You can explore Login class more on http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.login.create.aspx

.. more.

Sunday, April 12, 2009

Twitter Common Friends

For the past couple of months, A lot of people (who I don't know) have been following my twitter.. Mostly they don't look like anybody I know, not even Egyptians, & I'm not that popular anyway.. I'm ok with people following me anyway.. My twitter is public, & I'm not planning to change that.. But sometimes I need to know if these are real people who are in my twitter "social network" or just some sort of zombies or bots..

I've just created a small app to act like "common friends" in Facebook so I can find out whether I really know them or not.. Actually a couple of these followers are really interesting people & I'm following them now.. The app finds common people you're follwoing.. not common followers, the followers all is almost the same it just need authentacation..



The application depend on a single twitter API which takes the user name as a parameter & returns an xml (or JSON) file of their freinds for eg these are my friends xml file:

http://twitter.com/statuses/friends/mshady.xml



I used the "XML schema definition" tool (Xsd.exe) to generate the class to use the xml nodes directly as nodes rather than querying the XML document.. I'm such a lazy coder.. I know :D..

Once the xml is deserialised into the users datatype like this:


XmlSerializer oXmlSerializer = new XmlSerializer(typeof(users));
users oUsers1 = (users)oXmlSerializer.Deserialize(
                     XmlReader.Create(@"http://twitter.com/statuses/friends/"+textBox1.Text+".xml"
                        ));

All you need to do is to find the intersection set between the two list/sets.. & display them
 
The source code & binaries are available here: http://cid-570d40f05cc0dc13.skydrive.live.com/self.aspx/Sample%20Code/TwitterTest.rar

.. more.

Monday, July 21, 2008

C# 4.0 is not a dream, it is comming :)

I Have Nothing to say, just Check this Link

------ Welcome C# 4.0 ------

.. more.

Thursday, July 10, 2008

Code Snippet :Oracle via C#

Select statement :

OracleCommand myOracleCommand = new OracleCommand();

OracleConnection myOracleConn = new OracleConnection();

myOracleConn.ConnectionString = "user id=userid ; data source=ERPDEV ; password=xxxxx";

myOracleConn.Open();

myOracleCommand.Connection = myOracleConn;

try

{

string strSQLFields = "select QUESTIONANSWER from FCIH where QUESTIONTEXT ='any text' ROWNUM <= 2)";

myOracleCommand.CommandText = strSQLFields;

myOracleCommand.CommandType = CommandType.Text;

OracleDataReader OracleDataReader1 = myOracleCommand.ExecuteReader();

if (OracleDataReader1.Read())

{

if (!(OracleDataReader1.IsDBNull(0)))

{

answer = OracleDataReader1.GetString(0);

}

}

if (!OracleDataReader1.IsClosed)

OracleDataReader1.Close();

if (myOracleConn.State == ConnectionState.Open)

myOracleConn.Close();

}

catch (Exception ex)

{

throw new ArgumentException(ex.Message.ToString());

}


Insert statment :

//new record

OracleCommand myOracleCommand4Insert = new OracleCommand();

OracleConnection myOracleConn4Insert = new OracleConnection();

myOracleConn4Insert.ConnectionString = "user id=ultimus ; data source=ERPDEV ; password=kmbpm263";

myOracleConn4Insert.Open();

myOracleCommand4Insert.Connection = myOracleConn4Insert;

try

{

string strSQLFields4Insert = "INSERT INTO FCIHTABLE( TENDERNAME, TENDERNO )";

string strSQLValues4Insert = ":TENDERNAME,TENDERNO.NEXTVAL";

string strSQL4Insert = strSQLFields4Insert + " VALUES (" + strSQLValues4Insert + ")";

myOracleCommand4Insert.CommandText = strSQL4Insert;

myOracleCommand4Insert.CommandType = CommandType.Text;

myOracleCommand4Insert.Parameters.Add("TENDERNAME", "any tender name");

myOracleCommand4Insert.ExecuteNonQuery();

}

catch (Exception ex)

{

throw new ArgumentException("Error In Insert You Suggestions to DataBase: " + ex.Message.ToString());

}

.. more.

Tuesday, June 17, 2008

IComparable Interface.

From The name, this Interface used for comparison. This is the implementation of this interface:

C#:

public interface IComparable
{
int CompareTo(object o);
}

 

vb.net:

Public Interface IComparable
    Function CompareTo(ByVal o As Object) As Integer
End Interface

 

The result of this function is Integer; it returns 0 in similarity, -1 when the first one is smaller and 1 when larger .

Now we don't need to know who is larger, let’s assume that we have car class, something like that:

C#:

class Car
{

string Name;
int year;
}

vb.net:

Class Car
    Private Name As String
    Private year As Integer
End Class

 

Now we need to sort the cars depends on the creation year, our first step it to implement IComparable interface.

C#:

class Car:IComparable
{

string Name;
int year;
}


vb.net:

class Car:IComparable
{

string Name;
int year;
}

 

Next, we should write an implementation to CompareTo function, something like that:

c#:

int IComparable.CompareTo(object obj)
{
Car temp = (Car)obj;
if(this.year > temp.year)
return 1;
if(this.year < temp.year)
return -1;
else
return 0;
}

 

vb.net:

Private Function CompareTo(ByVal obj As Object) As
Integer Implements IComparable.CompareTo
    Dim temp As Car = DirectCast(obj, Car)
    If Me.year > temp.year Then
        Return 1
    End If
    If Me.year < temp.year Then
        Return -1
    Else
        Return 0
    End If
End Function

 

Anyway, -1 is equals to -100 in return value, this function work with any negative number referring to smaller, any positive number also is accepted instead of 1.

Sort Function:

Assume we have array of numbers, in this case some code like that is applicable.

c#:

Array.Sort(myNumbers);

 

vb.net:

Array.Sort(myNumbers)

 

But if we have array of cars, this will cause error, except if we implementing IComparable interface. in this case the array.sort() will use CompareTo function to sort all array elements. This is better solution than using another function for check and sorting. It is also more readable for people who work with you or read your code.

.. more.

Friday, May 16, 2008

How to make your controls moveable?

Q: How to make your controls moveable?


A: Some people need to add style to their controls to be moveable that's users can drag and drop them anywhere on the form.So, when user presses on a control and moves the mouse; control location should equal mouse axis.

Some variables used in our code.


/// <summary>
/// Indicates whether control is pressed by mouse or not
/// </summary>
bool IsDraged = false;

/// <summary>
/// Holds the X-coordinate of the control
/// </summary>
int Control_X = 0;

/// <summary>
/// Holds the Y-coordinate of the control
/// </summary>
int Control_Y = 0;


This is the mouse down event handler, we just checked the left button is pressed then set boolean variable IsDraged to true and assigned control location to mouse location.


private void Control_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
IsDraged = true;
Control_X = e.X;
Control_Y = e.Y;
}
}


Just when mouse left button released we set IsDraged to false.


private void Control_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
IsDraged = false;
}
}


Here's when mouse moves while mouse left button not released yet, the computation used helps controls to move smoothly with the mouse movement.


private void Control_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Control active = (Control)sender;
if (IsDraged)
{
active.Left += e.X - Control_X / 12;
active.Top += e.Y - Control_Y / 12;
Control_X = e.X;
Control_Y = e.Y;
}
}
}

.. more.

Sunday, April 27, 2008

How to save image in SQL Server database?

Q: How to save image in SQL Server database?

A: It's the most common question asked in technical forums, the answer is so simply is to convert your image to binary and save the equivalent binary data to the database.

I am expecting you know how to Insert\get data to\from SQL Server.

To convert image to binary you need to write this piece of code

   1: System.IO.FileStream fs = new System.IO.FileStream(@"ImagePath", System.IO.FileMode.Open);
   2:             byte[] imageAsBytes = new byte[fs.Length];
   3:             fs.Read(imageAsBytes, 0, imageAsBytes.Length);
   4:             fs.Close();


You need a table with column of binary\image datatype to be able to insert the equivalent binary data of image.

And what about retrieving binary data to be converted to image

You just need to initiate new Image from MemoryStream object which takes array of bytes as an argument -Array of bytes comes from SQL Server-



1: Image img = Image.FromStream(new System.IO.MemoryStream(imageAsBytes));


.. more.

Friday, April 25, 2008

How to bind ComboBox to an array of object?

Q: How to bind ComboBox to an array of object?

A:

Assume we have class like Student class

   1: public class Student
   2:     {
   3:         int id;
   4:  
   5:         public int ID
   6:         {
   7:             get { return id; }
   8:             set { id = value; }
   9:         }
  10:         string firstName;
  11:  
  12:         public string FirstName
  13:         {
  14:             get { return firstName; }
  15:             set { firstName = value; }
  16:         }
  17:         string lastName;
  18:  
  19:         public string LastName
  20:         {
  21:             get { return lastName; }
  22:             set { lastName = value; }
  23:         }
  24:  
  25:         public string FullName
  26:         {
  27:             get { return firstName + " " + lastName; }
  28:         }
  29:  
  30:         public Student(int id, string firstName, string lastName)
  31:         {
  32:             this.id = id;
  33:             this.firstName = firstName;
  34:             this.lastName = lastName;
  35:         }
  36:     }



what we need is to bind an array of Student to ComboBox and let the ComboBox shows the student FullName and bind their IDs to be used later.



So, what we need is to use some ComboBox properties like DisplayMember and ValueMember




   1: Student[] students = new Student[3];
   2:  
   3:             students[0] = new Student(1, "Ramy", "Mahrous");
   4:             students[1] = new Student(2, "FCI", "Helwan");
   5:             students[2] = new Student(3, "X", "Y");
   6:  
   7:             comboBox1.Items.AddRange(students);
   8:             
   9:             comboBox1.DataSource = students;
  10:             comboBox1.ValueMember = "ID";
  11:             comboBox1.DisplayMember = "FullName";




And now, ComboBox shows the FullName without overriding ToString method which is not the solution if we need to bind some properties.



Untitled

.. more.

Thursday, March 27, 2008

Amazon S3 via C#

Amazon Simple Storage Service (Amazon S3) via C#

Amazon S3 is storage for the Internet. It is designed to make web-scale computing easier for developers. It’s provides a simple web services interface that can be used to store and retrieve any amount of data, at any time, from anywhere on the web.

It uses standards-based REST and SOAP interfaces so it is platform independent and language independent.

It `s commercial but highly scalable, reliable, fast and inexpensive data storage infrastructure.

To know more about its advantage and the cost click here:

http://www.amazon.com/gp/browse.html?node=16427261

I am writing here to give you my experiences and tricks which I faced it when I started in develop the service using Dot Net (C#) and soap.

First trick:

When you work using .Net, you must use WSE 2.0 NOT WSE 3.0 as Amazon support DIME (WSE 2.0) NOT MTOM (WSE 3.0).

Second trick:

You can only using the class System.Web.Services.Protocols.SoapHttpClientProtocol, if you want upload files to AWS (Amazon Web Service) that are less than one Megabytes.

Here is an excellent example that server the required (files less than megabyte) with complete demo code for view and upload files.

http://developer.amazonwebservices.com/connect/entry.jspa?externalID=774&categoryID=55

Third trick:

If your files are bigger than one Megabytes (ten, twenty or may be 50 megabytes), you must to change the class System.Web.Services.Protocols.SoapHttpClientProtocol to Microsoft.Web.Services2.WebServicesClientProtocol . (As mentioned in this link)

http://developer.amazonwebservices.com/connect/entry!default.jspa?categoryID=103&externalID=689&fromSearchPage=true

Then follow the last trick...

Last trick:

You must raise the Timeout property that inherits the Microsoft.Web.Services2.WebServicesClientProtocol (the AmazonS3class if you opened the following example) more time out (this property measures in milliseconds) .

Here it an excellent example that server the required (more than one megabyte) with complete code.

http://developer.amazonwebservices.com/connect/entry!default.jspa?categoryID=47&externalID=690&fromSearchPage=true

The Amazon S3 Developer Guide :

http://docs.amazonwebservices.com/AmazonS3/2006-03-01/

.. more.

Friday, March 14, 2008

The Singularity Research Development Kit

At Tuesday, February 13, 2007 Shereef Saker has posted article on FCI-H about Singularity: A research OS written in C# while going through Microsoft Student Partners forum I found a post sent by Matthieu Suiche an MSP from France informing about Singularity first release...

Microsoft research page: http://research.microsoft.com/os/singularity/
The Singularity Research Development Kit (RDK) 1.1 is now available for academic non-commercial use. You can download it from CodePlex, Microsoft's open source project hosting website, here. http://www.codeplex.com/singularity

Overview:
Singularity is a research project focused on the construction of dependable systems through innovation in the areas of systems, languages, and tools. We are building a research operating system prototype (called Singularity), extending programming languages, and developing new techniques and tools for specifying and verifying program behavior.
Advances in languages, compilers, and tools open the possibility of significantly improving software. For example, Singularity uses type-safe languages and an abstract instruction set to enable what we call Software Isolated Processes (SIPs). SIPs provide the strong isolation guarantees of OS processes (isolated object space, separate GCs, separate runtimes) without the overhead of hardware-enforced protection domains. In the current Singularity prototype SIPs are extremely cheap; they run in ring 0 in the kernel’s address space.
Singularity uses these advances to build more reliable systems and applications. For example, because SIPs are so cheap to create and enforce, Singularity runs each program, device driver, or system extension in its own SIP. SIPs are not allowed to share memory or modify their own code. As a result, we can make strong reliability guarantees about the code running in a SIP. We can verify much broader properties about a SIP at compile or install time than can be done for code running in traditional OS processes. Broader application of static verification is critical to predicting system behavior and providing users with strong guarantees about reliability.

.. more.

Thursday, March 06, 2008

Save As PDF using C#

Welcome guys , this day we will display an esay way to convert files from any format that Microsoft Office open to PDF file format using simple C# code.

Frist of all you should to install 2007 Microsoft Office Add-in: Microsoft Save as PDF (very small about 934 KB) .

Click here to download it from Microsoft site

After you have finished your setup , you should to have new save as option like the picture .

saveasPDF


Secondly : add this two reference to your DotNet project as you see in this picture .

refrences

Then insert the required namespaces in the project ..

Like here :

using System;

using System.Data;

using System.Text;

using System.IO;

using Microsoft.Office.Interop.Word;

finally : here is the class called Doc2PDFAtServerClass , this class have only one static function word2PdfFcih which have two paramters .

this is a example :

object SourceFileName = “Fci-H.doc” ;

object newFileName = “Fci-H.pdf” ;

static public class Doc2PDFAtServerClass

{

static public void word2PdfFcih(object SourceFileName, object newFileName)

{

//Pid++;

Microsoft.Office.Interop.Word.ApplicationClass MSdoc = null;

//object Source = "d:\\Document" + Pid.ToString(System.Globalization.CultureInfo.CurrentCulture) + ".doc";

object Source = SourceFileName;

object readOnly = false;

object Unknown = System.Reflection.Missing.Value; //Type.Missing;

object missing = Type.Missing;

try

{

//Creating the instance of Word Application

if (MSdoc == null)

MSdoc = new Microsoft.Office.Interop.Word.ApplicationClass();

MSdoc.Visible = false;

MSdoc.Documents.Open(ref Source, ref Unknown,

ref readOnly, ref Unknown, ref Unknown,

ref Unknown, ref Unknown, ref Unknown,

ref Unknown, ref Unknown, ref Unknown,

ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown);

MSdoc.Application.Visible = false;

MSdoc.WindowState = Microsoft.Office.Interop.Word.WdWindowState.wdWindowStateMinimize;

object FileName = newFileName;

object FileFormat = WdSaveFormat.wdFormatPDF;

object LockComments = false;

object AddToRecentFiles = false;

object ReadOnlyRecommended = false;

object EmbedTrueTypeFonts = true;

object SaveNativePictureFormat = false;

object SaveFormsData = false;

object SaveAsAOCELetter = false;

//object Encoding = MsoEncoding.msoEncodingUSASCII;

object InsertLineBreaks = false;

object AllowSubstitutions = false;

object LineEnding = WdLineEndingType.wdCRLF;

object AddBiDiMarks = false;

/*

to get more details about SaveAs(...) function and it's parameter ,read this microsoft's link

http://msdn2.microsoft.com/en-us/library/aa662158(office.10).aspx

*/

MSdoc.ActiveDocument.SaveAs(ref FileName, ref FileFormat, ref LockComments,

ref missing, ref AddToRecentFiles, ref missing,

ref ReadOnlyRecommended, ref EmbedTrueTypeFonts,

ref SaveNativePictureFormat, ref SaveFormsData,

ref SaveAsAOCELetter, ref /*Encoding*/missing, ref InsertLineBreaks,

ref AllowSubstitutions, ref LineEnding, ref AddBiDiMarks);

}

catch (FileLoadException e)

{

Console.WriteLine(e.Message + "Error" );

}

catch (FileNotFoundException e)

{

Console.WriteLine(e.Message + "Error");

}

catch (FormatException e)

{

Console.WriteLine(e.Message + "Error");

}

finally

{

if (MSdoc != null)

{

MSdoc.Documents.Close(ref Unknown, ref Unknown, ref Unknown);

//WordDoc.Application.Quit(ref Unknown, ref Unknown, ref Unknown);

}

// for closing the application

// WordDoc.Quit(ref Unknown, ref Unknown, ref Unknown);

MSdoc.Quit(ref Unknown, ref Unknown, ref Unknown);

MSdoc = null;

}

}

}

Have fun ;) ..

.. more.