Thursday, March 7, 2013

Convert Datatable object into XElement object


public XElement ConvertDataTableIntoXElement(DataTable dtData)
        {
            XElement xElementConverted = null;
            try
            {
                xElementConverted = new XElement("container");
                using (XmlWriter xmlWriter = xElementConverted.CreateWriter())
                { dtData.WriteXml(xmlWriter, System.Data.XmlWriteMode.WriteSchema, true); }
            }
            catch (Exception ex)
            {  }
            return xElementConverted;
        }

Wednesday, March 6, 2013

Basic RESTful service in WCF

operation contract in the interface for the WCF service

[OperationContract]
        [WebInvoke(Method = "GET",
            BodyStyle = WebMessageBodyStyle.Bare,
            RequestFormat = WebMessageFormat.Xml,
            ResponseFormat = WebMessageFormat.Xml,
            UriTemplate = "/ValidateXMLData?inputData={inputData}")]
        string ValidateXMLData(string inputData);

In the .svc file do the implementation for the interface.

   public string ValidateXMLData(string inputData)
        {
            string validatedString=string.Empty;
            try
            {
                 XmlDocument xDoc = new XmlDocument();
                xDoc.LoadXml(inputData);
                validatedString = inputData;
            }
            catch (Exception ex)
            { }
            return validatedString;
        }

service configuration in your web.Config file

<system.serviceModel>
    <services>
      <service behaviorConfiguration="ServiceBehavior" name="MyService.Services.RestService">
        <endpoint address="XML"
                  behaviorConfiguration="restPoxBehavior"
                  binding="webHttpBinding"
                  contract="MyService.Contracts.IRestService" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="restPoxBehavior">
          <webHttp helpEnabled="true"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

Thursday, February 16, 2012

Write XML Data Dynamically

public void WriteDataToXML(string filePath, string[] fieldsList, string[] fieldsValue)
{
try
{
if (fieldsList.Length.Equals(fieldsValue.Length))
{
int arrayLength = fieldsList.Length;
if (File.Exists(filePath))
{
XDocument xDocument;
xDocument = XDocument.Load(filePath);
XElement rootElement = new XElement("Details");
XElement dataElement = new XElement("Data");
for (int count = 0; count < arrayLength; count++)
{
XElement element = new XElement(fieldsList[count], fieldsValue[count]);
dataElement.Add(element);
}
xDocument.Element("Details").Add(dataElement);
xDocument.Save(filePath);
}
else
{
XElement rootElement = new XElement("Details");
XElement dataElement = new XElement("Data");
for (int count = 0; count < arrayLength; count++)
{
XElement element = new XElement(fieldsList[count], fieldsValue[count]);
dataElement.Add(element);
}
rootElement.Add(dataElement);
rootElement.Save(filePath);
}
}
}
catch (Exception ex) { }
}

Wednesday, April 27, 2011

Create XML file using LINQ

public void AddProductCategory(string filePath, string productCategory)
{
XDocument oXDoc;
try
{
if (File.Exists(filePath))
{
oXDoc = XDocument.Load(filePath);
oXDoc.Element("DataContent").Add(
new XElement("Data",
new XElement("ID", Guid.NewGuid().ToString()),
new XElement("CategoryName", productCategory)
));
oXDoc.Save(filePath);
}
else
{
XElement oXElmnt = new XElement("DataContent",
new XElement("Data",
new XElement("ID", Guid.NewGuid().ToString()),
new XElement("CategoryName", productCategory)
));
oXElmnt.Save(filePath);
}
}
catch (Exception ex) { }
}

Wednesday, June 30, 2010

Create Excel file with save Dialog in ASP.Net

DataTable will have the data to write into Excel file
fileName will be Excel file name with extension(.xls/.xlsx)

public void SaveExcelFile(string fileName, DataTable dtData)
{
try
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName + "");
HttpContext.Current.Response.Flush();
for (int colCount = 0; colCount < dtData.Columns.Count; colCount++)
{
HttpContext.Current.Response.Write(dtData.Columns[colCount].ColumnName.ToString());
HttpContext.Current.Response.Write("\t");
}
for (int rowCount = 0; rowCount < dtData.Rows.Count; rowCount++)
{
HttpContext.Current.Response.Write("\n");
for (int colCount = 0; colCount < dtData.Columns.Count; colCount++)
{
HttpContext.Current.Response.Write(dtData.Rows[rowCount][colCount].ToString());
HttpContext.Current.Response.Write("\t");
}

}
HttpContext.Current.Response.End();
}
catch (Exception ex)
{ }
}

Friday, February 19, 2010

Some C# Coding Standards Should follow

Coding standards


  • Ø                          Naming Convention
1.       Use Pascal casing for Class name, Methods, Properties etc
                  Public void DisplayName()
                   {
                    }

2.       Use Camel casing for variables
string customerName
Int customerId

3.       Don’t use Hungerian notation
 string m_sName;
Int nCount;


  • Ø                      Always use meaningful names for variables, properties, Methods etc.
Like:- string customerName
Avoid :- string cust_Name


  • Ø                   Do not use underscore ( _ ) for local variables

  •                          Prefix Boolean variables, properties and methods with “is” or similar prefixes.

Private bool isFinished;


  • Ø          Namespace names should follow the standard pattern

...


  • Ø                   File name should match with class name.

For example, for the class HelloWorld, the file name should be helloworld.cs (or, helloworld.vb)


  • Ø               Always use Pascal casing in filename.


  • Ø             Don’t use variables like i,j in loop. Always use meaningful names

Wrong approach:
For(int i=0; i<10; i++)
{
}

Right approach:
For(int count=0; count<10; count++)
{
}

  • Ø                 Always put Comments for classes, functions, properties etc.

///Summary
/// description of class,methods
///created by : user
///created on : date
///last modified by : user
///last created on : date



Wednesday, February 17, 2010

Creating Excel Workbook using C#.net

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Exl = Microsoft.Office.Interop.Excel;

public class createExcel
{

//Excel Objects
        Exl.Application excel;
        Exl.Workbook workBook;
        Exl.Workbooks workBooks;
        Exl.Sheets sheets;
        Exl._Worksheet workSheet;
        Exl.Range range;
        Exl.Range rangeCells;



public createExcel()
{
InitializeExcelObjects();
}

public void InitializeExcelObjects()
        {
            excel = new Exl.Application();
            workBooks = excel.Workbooks;
            workBook = excel.Workbooks.Add(Type.Missing);

            //sheets = excel.Sheets;
            //wSheet = (Exl._Worksheet)(sheets[1]);
        }


private int ExcelTemplate(string fileName, DataTable dtData)
        {
            int nmReturn=0, nmSheetIndex=1, nmColumnCount=1;
            StringBuilder strBuild = new StringBuilder();
            string sheetName = string.Empty;
            try
            {
        
                sheetName = dtData.Rows[0][1].ToString();
                sheets = excel.Sheets;
                workSheet = ((Exl.Worksheet)sheets[nmSheetIndex]);
                workSheet.Name = sheetName;
                range = workSheet.Cells;
                rangeCells = workSheet.Cells;
                for (int rowCount = 0; rowCount < dtData.Rows.Count; rowCount++)
                {
                    if (!sheetName.Equals(dtData.Rows[rowCount][1].ToString()))
                    {
                        nmSheetIndex++;
                        sheetName = dtData.Rows[rowCount][1].ToString();
                        workSheet = ((Exl.Worksheet)sheets[nmSheetIndex]);
                        workSheet.Name = sheetName;
                        range = workSheet.Cells;
                        rangeCells = workSheet.Cells;
                        nmColumnCount = 1;
                    }
                        //workSheet.Columns.ColumnWidth = 50;
                        rangeCells.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlLeft;
                        rangeCells[1, nmColumnCount] = dtData.Rows[rowCount][0].ToString();
                        nmColumnCount++;
                                   }
                string filePath = Application.StartupPath.ToString() + fileName;
                workBook.SaveAs(filePath, Exl.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Exl.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                excel.Workbooks.Close();
                nmReturn++;
            }
            catch (Exception ex) { nmReturn = 0; }
            return nmReturn;
        }
}

Motivational qoutes

पूरे विश्वास के साथ अपने सपनों की तरफ बढ़ें। वही ज़िन्दगी जियें जिसकी कल्पना आपने की है।