Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, March 5, 2014

How to avoid ContextSwitchDeadlock exception?

In some of the cases we face the problem regarding ContextSwitchDeadlock. Actually there are some causes for this exception.

You can check these causes by following this link-

http://msdn.microsoft.com/en-us/library/ms172233%28v=vs.110%29.aspx

In this article, I am explaining - "How can we avoid ContextSwitchDeadlock exception?"

To void the this exception, we need to set some setting in Visual Studio IDE, Check the below steps-

1. Click on "Debug" Menu.
2. After that Click on "Exceptions".
3. It will open one Exception window. Here expand the node- "Manage Debugging Assistants".
4. Here you will find "ContextSwitchDeadlock" CheckBox, just uncheck it.

Follow-

Debug-> Exceptions-> Manage Debugging Assistants -> ContextSwitchDeadlock

Check the below screen shot-


ContextSwitchDeadlock


Just uncheck it and again run the application, This exception will be skipped while run-time.


Friday, February 28, 2014

How to Compare the Objects in .Net (Real story of Equals() method)

Comparing objects is really a big story because we don’t have any direct method to compare the object (Except reference comparison).  If we want to compare the object reference then we can use Object .Equals () but it is not useful when we want to compare the object properties.

Equals () method compares the references not the properties or values of the object. So it will not any help when we have requirement to compare the object properties or values.

Let me take the small example for this. Check the below code-

private void btnEquals_Click(object sender, EventArgs e)
        {
            try
            {
                ClsEmployee objEmp1 = new ClsEmployee();
                ClsEmployee objEmp2 = new ClsEmployee();
                ClsEmployee objEmp3 = new ClsEmployee();

                //Assigning value to objEmp1
                objEmp1.intEmpId = 1;
                objEmp1.intEmpName = "Jitendra";

                //Assigning value to objEmp2
                objEmp2.intEmpId = 1;
                objEmp2.intEmpName = "Jitendra";

                //Assigning objEmp3 with objEmp1 (Reference)
                objEmp3 = objEmp1;

                //Comparing objEmp1 and objEmp2
                if (objEmp1.Equals(objEmp2))
                {
                    MessageBox.Show("Object objEmp1 and objEmp2 are same");
                }
                else
                {
                    MessageBox.Show("Object objEmp1 and objEmp2 are not same");
                }

                //Comparing objEmp1 and objEmp3
                if (objEmp1.Equals(objEmp3))
                {
                    MessageBox.Show("Object objEmp1 and objEmp3 are same");
                }
                else
                {
                    MessageBox.Show("Object objEmp1 and objEmp3 not are not same");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

In above code, I have assigned the same value to objEmp1 and objEmp2 but
objEmp1.Equals(objEmp2) will return False because objEmp1 and objEmp2 represents different references.

objEmp1.Equals(objEmp3) will return True because before comparing the object I have assigned objEmp3 = objEmp1, so here both will represent the same reference.

So here is the question- What if we want to compare the object properties?

Solution-

Here we have solution for this- We can make use of Reflection. Using reflection we can compare thee the properties of object with the help of PropertyInfo class. This class provides the information about the property.

You can find the difference based on following points-

1.    If the type of objects are not same
2.    If number of properties in objects are not same
3.    If any property is missing in second object
4.    If value of properties are not same
5.    If any object is null

For this add the below namespace-

using System.Reflection;

Check the below example-

    //Employee Class
    public class ClsEmployee
    {
        public Int32 intEmpId { get; set; }
        public string intEmpName { get; set; }
        public ClsDept objClsDept { get; set; }
    }

    //Dept Class
    public class ClsDept
    {
        public Int32 intDeptId { get; set; }
        public string intDeptName { get; set; }
    }

//Code to compare object using PropertyInfo Class
        private void btnCompareProInfo_Click(object sender, EventArgs e)
        {
            try
            {
                ClsEmployee objEmp1 = new ClsEmployee();
                ClsEmployee objEmp2 = new ClsEmployee();
                ClsEmployee objEmp3 = new ClsEmployee();

                //Assigning value to objEmp1
                objEmp1.intEmpId = 1;
                objEmp1.intEmpName = "Jitendra";
                objEmp1.objClsDept = new ClsDept();
                objEmp1.objClsDept.intDeptId = 1;
                objEmp1.objClsDept.intDeptName = "AC";
              
                //Assigning value to objEmp2
                objEmp2.intEmpId = 1;
                objEmp2.intEmpName = "Jitendra";
                objEmp2.objClsDept = new ClsDept();
                objEmp2.objClsDept.intDeptId = 1;
                objEmp2.objClsDept.intDeptName = "AC";

                //Assigning value to objEmp3
                objEmp3.intEmpId = 1;
                objEmp3.intEmpName = "Jitendra";
              
                //Comparing objEmp1 and objEmp2
                if (CompareObjects(objEmp1, objEmp2))
                {
                    MessageBox.Show("Object objEmp1 and objEmp2 are same");
                }
                else
                {
                    MessageBox.Show("Object objEmp1 and objEmp2 are not same");
                }

                //Comparing objEmp1 and objEmp3
                if (CompareObjects(objEmp1, objEmp3))
                {
                    MessageBox.Show("Object objEmp1 and objEmp3 are same");
                }
                else
                {
                    MessageBox.Show("Object objEmp1 and objEmp3 are not same");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //Method to compare Object
        private Boolean CompareObjects(object obj1, object obj2)
        {
            Boolean isEqual = true;
            try
            {
                //If any object is null then returning  false
                if (obj1 == null || obj2 == null)
                {
                    return false;
                }
                //If object types are different then returning false
                if (obj1.GetType() != obj2.GetType())
                {
                    return false;
                }

                //Getting list of properties
                PropertyInfo[] obj1PInfo = obj1.GetType().GetProperties();
                PropertyInfo[] obj2PInfo = obj2.GetType().GetProperties();

                //If number of properties are not same then return false
                if (obj1PInfo.Count() != obj2PInfo.Count())
                {
                    return false;
                }

                //Looping each child property
                for (int index = 0; index < obj1PInfo.Count(); index++)
                {
                    //Getting child property
                    PropertyInfo objChild1PInfo = obj1PInfo[index];
                    Object propValue1 = objChild1PInfo.GetValue(obj1, null);

                    Object propValue2 = null;

                    //Checking same property is not present in second object then return false
                    if (obj2PInfo.Contains(objChild1PInfo) == false)
                    {
                        return false;
                    }
                    else
                    {
                        PropertyInfo objChild2PInfo = obj2PInfo[index];
                        propValue2 = objChild2PInfo.GetValue(obj2, null);
                    }

                    //If object contains any child property (as class type) then compare child properties also
                    if (Enum.IsDefined(typeof(System.TypeCode), objChild1PInfo.PropertyType.Name) == false)
                    {
                        isEqual = CompareObjects(propValue1, propValue2);
                    }
                    else
                    {
                        if (Convert.ToString(propValue1) != Convert.ToString(propValue2))
                        {
                            return false;
                        }
                    }
                }
                return isEqual;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

In above code, I have written one method (CompareObjects()) to compare the object s.
Boolean CompareObjects(object obj1, object obj2)-  In this method I have used PropertyInfo class get the information about each property in objects. This method will compare the object based on points as I have given above.

So the result of (CompareObjects(objEmp1, objEmp2)) will be True because both object have same values And result of (CompareObjects(objEmp1, objEmp3)) will be False because both object have different values.

Note- This code will also work if you have any child  classes.

Monday, February 24, 2014

How to generate alphabet sequence A, B, C, ....., Z, AAA, AAB,....., ZZZ in C#

In some of the cases we use alphabet for sequence. If we have options less then 27 then   we can direct use A-Z alphabet but if the options are more then we have to generate sequence.

Check the below logic to generate the alphabet sequence like -     A, B, C, ....., Z, AAA, AAB,....., ZZZ  

 private void btnGenerate_Click(object sender, EventArgs e)
        {
            List<string> lstSquence = new List<string>();
           
            int i = 0;
            //Generating 1000 alphabet sequence
            while (i < 1000)
            {
                lstSquence.Add(GenerateSequence(i));
                i++;
            }
        }


        //Method to generate alphabet sequence
        static string GenerateSequence(int index)
        {
            string result = string.Empty;
            while (index > 0)
            {
                index = index - 1;
                result = char.ConvertFromUtf32(65+ index % 26) + result;
                index = index / 26;
            }
            return result;
        }

       

This logic will generate the alphabet sequence like -     A, B, C, ....., Z, AAA, AAB,....., ZZZ

Wednesday, January 8, 2014

How to insert bulk record into database using SQL Server,C# and XML

If we have list of records then we can not process each record to insert into database because it is time taking process and it will degrade the performance.In this case we can use bulk insert. Suppose if we have bulk record in xml then we can easily dump that xml record into database.

Check the below code sample to insert bulk record.

Suppose this is sample XML string -

XML Data String

<?xml version='1.0' encoding='utf-8'?>
<Employees>
  <Emp>
    <EmpID>101</EmpID>
    <EmpName>Jitendra</EmpName>
    <Age>27</Age>
  </Emp>
  <Emp>
    <EmpID>102</EmpID>
    <EmpName>Ramesh</EmpName>
    <Age>30</Age>
  </Emp>
  <Emp>
    <EmpID>103</EmpID>
    <EmpName>Raj</EmpName>
    <Age>24</Age>
  </Emp>
 </Employees>
 

 
Now check the below stored procedure –

Stored Procedure

This stored proceduer will take the XML string as input and it will process this XML to insert into table.

--Stored procedure to insert bulk record using XML

CREATE PROCEDURE [dbo].[SP_EmpBulkInsert]   
(    @XMLData text    )   
AS   
BEGIN   
 SET NOCOUNT ON   
 BEGIN TRANSACTION   
 Begin Try   

  DECLARE @XMLDocPointer INT   
  EXEC sp_xml_preparedocument @XMLDocPointer OUTPUT, @XMLData   

   INSERT INTO tab_Employees
   (EmpID, EmpName, Age)   
   SELECT EmpID,EmpName,Age  
   FROM OPENXML(@XMLDocPointer,'/Employees/Emp',2)   
   WITH  (EmpID INT,EmpName nvarchar(50),Age INT)    

   EXEC sp_xml_removedocument @XMLDocPointer   
   COMMIT TRANSACTION   
   Return 0;    
 End Try   
 Begin Catch   
   ROLLBACK TRANSACTION   
 End Catch   
END


In this stored procedure I am inserting data into tab_Employees table, based on column selection data will be inserted to this table. Now chek the below code to call this stored procedure from C# application.

C# Code-

//Code to insert bulk records
        private void btnBulkInsert_Click(object sender, EventArgs e)
        {
            try
            {
                //Code to insert bulk record using XML
                string strConnectionString = "Your connection string";
                //Getting XML string
                string strXML = GetXMLString();
               
                //Connecting to database
                using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection())
                {
                    conn.ConnectionString = Convert.ToString(strConnectionString);
                    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SP_EmpBulkInsert", conn);
                    cmd.Parameters.AddWithValue("@XMLData", strXML);
                    cmd.CommandType = CommandType.StoredProcedure;
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    conn.Close();
                    MessageBox.Show("Records inserted successfully.");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

         //XML string to insert bulk record
        private string GetXMLString()
        {
            return  @"<?xml version='1.0' encoding='utf-8'?>
<Employees>
  <Emp>
    <EmpID>101</EmpID>
    <EmpName>Jitendra</EmpName>
    <Age>27</Age>
  </Emp>
  <Emp>
    <EmpID>102</EmpID>
    <EmpName>Ramesh</EmpName>
    <Age>30</Age>
  </Emp>
  <Emp>
    <EmpID>103</EmpID>
    <EmpName>Raj</EmpName>
    <Age>24</Age>
  </Emp>
 </Employees>";
        }


In above code, I am getting XML string using GetXMLString() method. After getting the XML string I am passing this string as parameter for stored procedure. Finally when this code will be executed then you will find the new records in tab_Employees table.

Tuesday, October 29, 2013

The process cannot access the file because it is being used by another process


Problem-


The process cannot access the file because it is being used by another process

This is common problem, when we create file using File.Create() method.




Theprocesscannotaccess


Reason-


When we use File.Create() method to create file then the object of FileStream class is created and no other process can use or access the created file until the file is closed.

Solution -

This problem can be easily resolved by modifying your code like this-

File.Create (@"c:\Text.txt").Close();

Means use Close () with File.Create () method. It will create the file and after that it will close the related file.



Monday, July 22, 2013

How to get index of node based on node value using XSLT?


While working with XML in some of the cases, we want to get the index or position of particular value. This can be easily done by using XSLT.

In this article, I am explaining - How to get index of node based on node value using XSLT?

Example-

Suppose, I have this XML data-

<ResponseData>
    <value>C</value>
    <value>A</value>
    <value>B</value>
</Response>

Now if I want to get the position of ‘A’ then It should return '2' .

How to get it-

This is small XSLT code to get this position-

<!--Declaring Variable with value-->
<xsl:variable name="TempData" select="A"/>
 

<!--XSLT code to get position of 'A', output will be 2 -->
<xsl:value-of select="count(//abc:ResponseData/abc:value[text()=$TempData]/preceding-sibling::*)+1" />


In above line I have declared one variable - 'TempData'
and using select I have assigned value -'A'


Now to get the position of 'A', I have used count() method.

Here this expression -

count(//abc:ResponseData/abc:value[text()=$TempData]/preceding-sibling::*)+1

Will return the count of preceding sibling of A, which will be position of 'A'.

Like 'A', we can also get the position of other Values ('B' and 'C'), for this we need to assign this value to 'TempData' variable.



Thanks


Thursday, March 21, 2013

Using #Region in Dot Net


The #region directive allows organizing code files. Using #region directive we can separate the code. We can create separate region for each code block. Means to declare the variables, constants, functions etc we can use different code block by separating using #region directive.

Here is the example-

// region 1
#region Public Variables
Public int value1
Public int value2
#endregion

//region 2
#region Methods
public string  GetData()
{
--------
--------
}
#endregion


in above example we can see that I have created 2 region.

region1 for Public variables
region2 for methods


Like this we can create other regions also.


There are some benefits of using #region directive.

1. Separation of code
2. Readability
3. Easy to maintain
4. Easy to expand or collapse the code block
5. Easy to move entire code block


It is good to use #region directive while doing coding.



Thanks



Wednesday, February 27, 2013

How to download file using C#?


In some of the cases we need to download file from the Internet, In this article I am explaining-

How to download file using C#?

For this I have used WebResponse, WebRequest Classes so we need to include System.Net Namespace.To download the file from Internet we have to make request to particular object so that I have used webRequest class object. After getting the response from the server we need to handle that response so I have used webResponse class object.

For displaying downloading process I have used ProgressBar control.

Here is the code-

 private void btnDownLoadFile_Click(object sender, EventArgs e)
        {
           
            WebRequest requestObj ;
            WebResponse responseObj;
            Stream readerData ;
            Stream writerData ;
            byte[] data = new byte[1024];
            int count = 0;
            int total = 0;
            this.Text = "Downloading file .....";
           
            string DestinationFileName= "TargetLocation";
            string SourceLocation= "SourceLocation";

            Application.DoEvents();

            try
            {
                requestObj = WebRequest.Create(
SourceLocation);
                responseObj = requestObj.GetResponse();
                readerData = responseObj.GetResponseStream();
                progressBar1.Maximum = Convert.ToInt32(responseObj .ContentLength);
                progressBar1.Value = 0;
                total = 0;
                writerData = File.Create(DestinationFileName);
                while (true)
                {
                    count = readerData .Read(data, 0, 1024);
                    if (count <= 0)
                    {
                        break;
                    }
                    writerData.Write(data, 0, count);
                    total += 1024;
                    if (total < progressBar1.Maximum)
                        progressBar1.Value = total;
                    Application.DoEvents();
                }
                readerData .Close();
                writerData.Close();
                MessageBox.Show("Download completed...");
            }
            catch (Exception ex)
            {  
                MessageBox.Show("Error: " + ex.Message);
            }
        }



In above code, I am making request to download file using WebRequest Class object, for that I am passing source file url to download file.

 requestObj = WebRequest.Create(TargetLocation);

After making request we will get response, using this line of code-

  responseObj = requestObj.GetResponse();

Now using using Stream class object I am reading and writing data to the target file.

 count = readerData .Read(data, 0, 1024);

 writerData.Write(data, 0, count);


Meanwhile for displaying the download process, I am showing progressbar. Based on data read and write progressbar value will be increased which will show downloading process.


Output-


Downloading file



Thanks


Thursday, January 3, 2013

How to make Single Click and Double Click Events work together in windows form?


While working with Windows Application, This is common problem  that- Single Click and Double Click Events don't work together (If you have any processing code in Single Click Event like- Showing message using MessageBox), means if we have written some code in Single Click Event and some lines of code in Double Click Event then always Single Click Event code will be executed.

I also faced same problem and came with one workaround.

See this example-

  private void Form1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Single Click Event");
        }

  private void Form1_DoubleClick(object sender, EventArgs e)
        {
            MessageBox.Show("Double Click Event");
        }


In above lines of code always Single Click Event code will be executed and always output will be - Single Click only.

In this article, I am explaining - How to make Single Click and Double Click  Events work together?

Workaround-

To resolve this problem, I have taken one Timer Control, using Timer control I am handling the Single and Double Click Events functionalities.

Here is the code-

        private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Interval = SystemInformation.DoubleClickTime;
        }

        private void Form1_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
        }

        private void Form1_DoubleClick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            MessageBox.Show("Double Click Event");
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            MessageBox.Show("Single Click Event"); 
        }



In above code, first I am setting Timer Interval as System Double Click Time value. This can be different based on Operating System Settings.

  private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Interval = SystemInformation.DoubleClickTime;
        }


Now in Single Click Event, I am just enabling the Timer to execute the code which is written in Tick() Event of Timer.

  private void Form1_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;

        }


 In Tick() event write the code which you want to execute in Single Click Event.

    private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            MessageBox.Show("Single Click Event"); 
        }


Here I am disabling the Timer Control also because this code will be executed once.

Now this is Double Click Event code-

 private void Form1_DoubleClick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            MessageBox.Show("Double Click Event");
        }


Here I am just disabling the Timer Control; here you need to put actual Double Click Event code.

Here all the functionalities depend on Timer Control, Here making Timer control enable and disable is making trick for us.


Try this code.


Thanks



Friday, November 2, 2012

How to change NewDataSet xml root name while creating xml using WriteXml() method of Dataset?


This is default behavior of WriteXml() method when we create xml then it adds  <NewDataSet> node as root xml node and <Table> as child node. In this article, I am explaining- How to change <NewDataSet> xml root name while creating xml using WriteXml() method of Dataset?

Let first see the default case-

Suppose you we have one DataSet object ds and we are filling it will data source, like this-

Dataset ds= new DataSet();
ds= datasource;


After that we are using WriteXml() method to create XML, like this-

ds.WriteXml("FileName");

Then in this case output will be like this-

<NewDataSet>
  <Table>
    <Emp_ID>717</Emp_ID>
    <Emp_Name>Jitendra Faye</Emp_Name>
    <Salary>35000</Salary>
  </Table>
----------
----------
----------
</NewDataSet>


Here we can see that <NewDataSet> and   <Table> is default tag here.

Now to change these default tag follow this code, Here I am changing <NewDataSet> tag as <EmployeeRecords> tag and <Table> tag as <Employee> tag.

Here is code-

Dataset ds= new DataSet();
ds= datasource;


//Giving Name to DataSet, which will be displayed as root tag

ds.DataSetName="EmployeeRecords";

//Giving Name to DataTable, which will be displayed as child tag

ds.Tables[0].TableName = "Employee";

//Creating XML file
ds.WriteXml("FilePath");


Now after executing this above code generated XML file will be like this-

<EmployeeRecords>
  <Employee>
    <Emp_ID>717</Emp_ID>
    <Emp_Name>Jitendra Faye</Emp_Name>
    <Salary>35000</Salary>
  </Employee>
----------
----------
----------
</EmployeeRecords>



Here we can see that DataSet name is coming as root tag and DataTable name is coming as child tag.

Note-

Before giving name to DataTable (ds.Tables[0].TableName) first check that it should not be null otherwise it will cause an error.



Thanks


Thursday, November 1, 2012

How to edit word document using Asp.Net?


Problem -
 

Editing word document is not an easy task in ASP.Net, because we don't have any direct option to open server copy of word document. When we open any word document from server machine then first that document is downloaded to client machine's temp folder and then it is displayed. So if we will make any changes to that opened document then that changes will be saved in only client machine not in server machine.
 

Means the changes will not be reflected directly to server copy of word document.   
 

I have done some RND in this problem and came with one workaround. Hope this solution will help you.


Workaround-

There are some steps for this workaround.

Step 1: Store your document in any server folder.

Step 2: Read that document from server and convert to HTML Document.

Step 3: Now load converted HTML document to any HTML editor, for this you can use any free editor, there are lot of free editors are available in the market you can use anyone.

See this link for free HTML editors -

http://www.techsupportalert.com/best-free-html-editor.htm
Step4: Start editing document which is displayed in HTML editor using HTML editor ToolBox.

Step 5: After editing document get updated data from HTML editor and load to MemoryStream object.

Step 6: Finally again convert that MemoryStream object data to word file.

By following these steps you can edit word document online for this there is no need to use any paid third party controls.

Code Implementation-

For this implementation, I am using following tools-

1. Aspose DLL –   For converting Word document to HTML document and vice versa.
(I am using evaluation copy)

2. nicEditor HTML Editor - for showing and editing converted HTML document.
(It is free)

Now I have designed .aspx page like this-

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EditDocument.aspx.cs" Inherits="OnlineEdit.EditDocument"
    ValidateRequest="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="NicScript/nicEdit.js" type="text/javascript"></script>
    <script type="text/javascript">
        bkLib.onDomLoaded(function () {
            new nicEditor({ fullPanel: true, iconsPath: 'NicScript/nicEditorIcons.gif' }).panelInstance('docArea');
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table border="1">
            <tr>
                 <td>
                     <textarea cols="100" rows="20" id="docArea" runat="server"></textarea>
               </td>
            </tr>
            <tr>
                 <td align="center">
                   <asp:Button ID="btnLoad" runat="server" Text="Load Doc" Width="70px" OnClick="btnLoad_Click" />
                        
                   <asp:Button ID="btnSave" runat="server" Text="Save" Width="70px" OnClick="btnSave_Click" />
                 </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>



Note-   Set ValidateRequest="false"


Here I have taken one TextArea control by named – docArea. This will be used for showing and editing Word document. For this I have bounded nicEditor editor with TextArea. Using these lines of code-

    <script type="text/javascript">
        bkLib.onDomLoaded(function () {
            new nicEditor({ fullPanel: true, iconsPath: 'NicScript/nicEditorIcons.gif' }).panelInstance('docArea');
        });
    </script>


Pictorial representation will be like this-

Edit word document using ASP.Net


Now write following code in code behind-

protected void btnLoad_Click(object sender, EventArgs e)
        {
            string strFileName = Server.MapPath("docs\\" + "Eggheadcafe.doc");
            
             //Loading word document to HTML editor
            LoadDoc(strFileName);
        }

Here, I am reading Word document from docs directory (which is present in my solution structure) and passing to LoadDoc () function.

//Function to convert word document to HTML document after that loading into HTML editor
        private void LoadDoc(string strFileName)
        {
            //Loading  doc file using Document class of Aspose DLL
            Document doc = new Document(strFileName);

             //SaveOptions for image which is present in Word document
            HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
            string strImagePath = Server.MapPath("docs\\");

             //Location to save images which is included in word document
            options.ImagesFolder = strImagePath;
            options.ImagesFolderAlias = "docs\\";

           //Setting SaveFormat to save as HTML document
            options.SaveFormat = SaveFormat.Html;

           //Saving  file as HTML document
            doc.Save(strFileName + ".html", options);

             //Reading converted HTML file in Editor
            StreamReader sr = new StreamReader(strFileName + ".html");
            string strValue = sr.ReadToEnd();
            docArea.Value = strValue;
             sr.Close();
            sr.Dispose();
        }



In above function I have used Document class of Aspose dll to load Word document.
            Document doc = new Document(strFileName);

After loading document, we need to set the path for saving images which is included in Word document, for this I have used HtmlSaveOptions class.
       
            HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
            string strImagePath = Server.MapPath("docs\\");

//Location to save images which is included in word document
            options.ImagesFolder = strImagePath;
            options.ImagesFolderAlias = "docs\\";


Finally to save Word document as HTML document we need to set SaveFormat

            options.SaveFormat = SaveFormat.Html;
            doc.Save(strFileName + ".html", options);


Once these lines of code will be executed Word document will be converted to HTML document. Now we can load this HTML document to HTML editor.

             //Reading converted HTML file in Editor
            StreamReader sr = new StreamReader(strFileName + ".html");
            string strValue = sr.ReadToEnd();
            docArea.Value = strValue;
             sr.Close();
            sr.Dispose();


Output will be like this, when we will click on Load() button-

Edit word document using ASP.Net


Now to save edited document use the following code-

    protected void btnSave_Click(object sender, EventArgs e)
         {
             //Getting Text of HTML editor and writing into memorystream class object
            MemoryStream storeStream = new MemoryStream();
            StreamWriter sw = new StreamWriter(storeStream);
             sw.Write(docArea.Value);
             sw.Flush();

             //Again saving edited document with same name
            string strFileName = Server.MapPath("docs\\" + "Eggheadcafe.doc");
            Document doc = new Document(storeStream);
             doc.Save(strFileName, SaveFormat.Doc);
            storeStream.Close();
            storeStream.Dispose();
            sw.Close();
            sw.Dispose();
        }



In above code, first I am getting all the text of TextArea and writing to MemoryStream class object.

//Getting Text of HTML editor and writing into memorystream class object    
           MemoryStream storeStream = new MemoryStream();
            StreamWriter sw = new StreamWriter(storeStream);
            sw.Write(docArea.Value);
            sw.Flush();


After storing data into MemoryStream class object, I am using Document class of Aspose dll to write that data into same word file.

             //Again saving edited document with same name
            string strFileName = Server.MapPath("docs\\" + "Eggheadcafe.doc");
            Document doc = new Document(storeStream);
             doc.Save(strFileName, SaveFormat.Doc);
            storeStream.Close();
            storeStream.Dispose();
            sw.Close();
            sw.Dispose();


Now you are done.  We can test edited word document by going to same location where we have stored Word document.

Limitations-

1. One Extra HTML document will be created

2. You need to explicitly delete that HTML document after editing.

3. Time taking process because first you need to convert word doc to HTML doc and after editing again you have to create word doc.

4. Formatting can be lost, it depends on HTML editor.


Thanks


Monday, October 15, 2012

How to add custom action to Windows Installer using C# ?


Visual Studio Package and Development wizard provides facility to create setup of your .Net Application. But in some cases we want to control the installation steps using custom action, means we want to add some custom functionality while installing the application.

Using custom action we can handle functionalities like-

-    Setting registry value while installation
-    Reading registry value while installation
-    Serial key implementation

Etc.

In this article, I am explaining - How to add custom action to Windows Installer in C#?

Here I am giving complete steps with pictorial representation. Follow these steps -

Step1: First, develop your application with required functionality.

Step2: For performing your custom action while installing application, we need to add "Installer Class" in application.  Add one "Installer Class" using "Add New Item" to the project like this-



Installer


Step 3: After adding Installer Class to the project , add your custom functionality , Here I am adding some code in "MyInstaller.cs" file-


//Code to perform at the time of installing application
public override void Install(System.Collections.IDictionary stateSaver)
        {
            System.Windows.Forms.MessageBox.Show("Installing Application...");
        }

//Code to perform at the time of uninstalling application
        public override void Uninstall(System.Collections.IDictionary savedState)
        {
            System.Windows.Forms.MessageBox.Show("Uninstalling Application...");
        }



Here I have added to events, this is for custom functionality, you can write your own code which you want to perform at the time of Installing and uninstalling application.

Step 4: Now set your application in "Release Mode" and build it.

Step 5: Now we have to add setup project for developed application, so right click on "Solution Explorer" and click on "Add -> New Project option".

Here you will get Project Templates dialog, Select "Visual Studio Installer" from "Other Project Types" option.

See this Image-


Setup


Step 6: After adding Setup project to solution, set project output for Setup project. For this right click on setup project and click on "Add -> Project Output"

you will get "Add project Output Group Dialog”, Here you need to set some setting like this-



Add Project Group


After setting click on "OK" button.

Step 7: Now to add custom action, again right click on "Setup project" and click on "View -> Custom Actions".


Custom Action



Now to set Custom action for installation right  click on "Install" click on "Add Custom Action",

Here double click on "Application folder" and select Primary output from Myproject and click on "OK" button.


Primary Output



Step 8: Repeat same for UN-installation process also.

Step 9: Finally your solution structure will be like this-


Solution Explorer

 

Step 10: Now build setup project and finally build the solution. Now you are done.

To test the complete process just try to install your application now, while installing application you will get message like this-



Installing Application



This is the same message which we have given in Install () event. Means whatever the action or code we will write in this event that will be perform at the time of installing application.

//Code to perform at the time of installing applicationpublic override void Install(System.Collections.IDictionary stateSaver)
        {
            System.Windows.Forms.MessageBox.Show("Installing Application...");
        }

And when you will uninstall application you will get message like this-


Uninstalling Application

 Here also we can see that the code which we have written in Uninstall () event that is executing.
Like Install () event we can handle Uninstall () event also.


//Code to perform at the time of uninstalling application
        public override void Uninstall(System.Collections.IDictionary savedState)
        {
            System.Windows.Forms.MessageBox.Show("Uninstalling Application...");
        }



These complete helps you to handle custom action while installation or uninstallation, Using these step we can implement serial key for application, means while installing application we can set expiration time for application and while uninstallation we can delete application related registry settings.



Thanks



Monday, October 8, 2012

How to compare DataTables?


Data Tables can be easily compared. This comparison can be done using Merge () and GetChanges() methods of DataTable class object.

In this article, I am taking 3 DataTable class object- dataTable1, dataTable2 and dataTable3
Here dataTable3 will hold the comparison result of dataTable1 and dataTable2.

Here is simple code-

//Merging datatable2 to data table 
dataTable1.Merge(dataTable2);

//Getting changes in dataTable3

 DataTable dataTable3= dataTable2.GetChanges();


In above lines of code, first I am merging datatTable1 and dataTable2 and combined result will be stored in dataTable1. Finally to get changes I am using GetChanges() method of dataTable1 object.

DataTable dataTable3= dataTable2.GetChanges();

Here GetChanges() method will return one DataTable class object and  returned result will be stored in dataTable3 object.



Thanks

Tuesday, September 4, 2012

How to change sort order of crystal report by using code?



Crystal report -

Crystal report is a tool which provides facility to display data in reporting format. It also support functionality like sorting of data based on sort field. This sorting can be done in design time and run-time also.


Sorting data using sort field is easy while design time but if we want to sort data in run-time then some time it can generate error. The most common error for run-time sorting is-


"The sorting already exists"


In this article, I will explain -
How to change sort order of crystal report by using code?

First I will tell what the reason for this error is and how we can solve this error.


Reason-


This error comes when we are trying for setting sort field for crystal report using code and that particular sort-field is already added as sort order field for crystal report in design time.


Example-


Suppose we want set "Name" as sort order field and this field ("Name") is already present as sort order in design time then it will generate error.


Workaround-


Simple workaround for this problem is that swapping of sort order fields.

Suppose you have added two fields (firstName and lastName) as sort fields for report in design time
And present sort field is firstName now if you want to changes sort field to lastName then will generate error. So here we have a trick – Take any column from table which is not present in sort field which you have added in design time.

Design time –

Sort field (0) - firstName
Sort field (1)-lastName

In code set like this-

Sort field (0) - firstName
Sort field (1) - address (any field of table which is not in sort field)

Now again swap between firstName and lastName. This time it will successful because now currently we don’t have lastName as sort field in report. 

Here I am going to explain how we can solve this problem? Here is sample code to solve this problem-

String SortField="yourSortField";

bool fieldPresent = false;

 //CHECKING SORT FIELD PRESENT IN THE REPORT IF YES THEN SWAP THE POSITION //TO ZERO

    for (int i = 0; i <= Report100.DataDefinition.SortFields.Count - 1; i++)
  {
       if (Report100.DataDefinition.SortFields[i].Field.FormulaName == SortField)
        {
            fieldPresent = true;
            FieldDefinition tempDef = New FieldDefinition;
            FieldDefinition currentDef =New FieldDefinition;

            //HOLDING CURRENT [0'TH] SORT FIELD

            currentDef = Report100.DataDefinition.SortFields[0].Field;

            //HOLDING FOUND SORT FIELD

            tempDef = Report100.DataDefinition.SortFields[i].Field;

            //REPLACING FOUND FIELD  DEFINITION WITH OTHER FIELD DEFINITION EXCEPT (Already Present SortField in design time) BECAUSE THESE SORT FIELDS ARE ALREADY IN REPORT SO GENERATE ERROR


            Report100.DataDefinition.SortFields[i].Field = Report100.Database.Tables[0].Fields[5];


            //SWAPPING THE CURRENT SORT FIELD WITH FOUND SORT FIELD

            Report100.DataDefinition.SortFields[0].Field = tempDef;
            Report100.DataDefinition.SortFields[i].Field = currentDef;

            break;

        }
    }

    //IF SORT FIELD IS NOT PRESENT THEN REPLACE THE CURRENT FIELD DEFINITION


    if (fieldPresent == false)

    {
        FieldDefinition FieldDef = New FieldDefinition;
        FieldDef = Report100.Database.Tables[0].Fields[SortField];
        Report100.DataDefinition.SortFields[0].Field = FieldDef;
    }

Report100.DataDefinition.SortFields[0].SortDirection = CrystalDecisions.Shared.SortDirection.AscendingOrder;



In above code, I am setting sort order field, Here this I am swapping sort field orders but we can’t swap sort field directly because if field is present as sort field then it will generate error, for this I have written code to identify that sort field is present or not.


If sort field is not present then I am directly setting given field ("SortField") as sort field. Otherwise to set sort order field I am implementing swapping concept.


For this I have take two objects of  FieldDefinition class.


FieldDefinition tempDef = New FieldDefinition;
FieldDefinition currentDef =New FieldDefinition;


Using this first, I am replacing present sort order field  with different (which is not present in sort order field ) sort order field . Finally I am changing the sort order like this-

 //SWAPPING THE CURRENT SORT FIELD WITH FOUND SORT FIELD


Report100.DataDefinition.SortFields[0].Field = tempDef;

Report100.DataDefinition.SortFields[i].Field = currentDef;


Now done, try this code, I have successfully implemented this code.



Thanks