Thursday 21 November 2013

Obrivations


here is the obrivations:

Web Services Description Language (WSDL)
Windows Communication Foundation (WCF)
Customer Relationship Management (CRM)
Uniform Resource Identifier (URI).
REST represents Representational State Transfer.
SOAP stands for Simple Object Access Protocol

getting the selected radgrid values in c#



DataKeyNames="accumulatorname"

getting the selected radgrid values in c#

first we need to set the properities:


     
                                                            <telerik:RadGrid ID="radGridPromotionStatus" runat="server" class="inputfields"
                                                                GridLines="None" AutoGenerateColumns="False" CssClass="Grid" width="800"
                                                                 meta:resourcekey="radGridResource1"
                                                                CellSpacing="0" OnSelectedIndexChanged="Page_PreRender" DataKeyNames="column11" >
                                                                <ClientSettings AllowColumnsReorder="False" EnablePostBackOnRowClick="true"  >
                                                                   <Selecting AllowRowSelect="true"  />
                                                                    <%--<ClientEvents runat="server" OnRowSelected="Page_PreRender" />--%>
                                                                    <Resizing AllowColumnResize="True" />
                                                                </ClientSettings>
                                                                <MasterTableView NoDetailRecordsText="&nbsp;" DataKeyNames="accumulatorname" >

    <CommandItemSettings ExportToPdfText="Export to PDF"></CommandItemSettings>

    <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column"></RowIndicatorColumn>

    <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column"></ExpandCollapseColumn>
                                                                     <Columns>
                                                                        <telerik:GridBoundColumn DataField="accumulatorname" HeaderText="Accumulator Name"
                                                                            UniqueName="column11" meta:resourcekey="GridBoundColumnResource11" HeaderStyle-Width="125px">
                                                                        </telerik:GridBoundColumn>
                                                                        <telerik:GridBoundColumn DataField="accumulationamount" HeaderText="Accumulation Amount"
                                                                            UniqueName="column12" meta:resourcekey="GridBoundColumnResource12" HeaderStyle-Width="125px">
                                                                        </telerik:GridBoundColumn>
                                                                        <telerik:GridBoundColumn DataField="nextthresholdnumber" HeaderText="NextThreshold Number"
                                                                            UniqueName="column13" meta:resourcekey="GridBoundColumnResource13" HeaderStyle-Width="150px">
                                                                        </telerik:GridBoundColumn>
                                                                        <telerik:GridBoundColumn DataField="nextthresholdid" HeaderText="NextThreshold ID"
                                                                            UniqueName="column14" meta:resourcekey="GridBoundColumnResource14" HeaderStyle-Width="125px">
                                                                        </telerik:GridBoundColumn>
                                                                        <telerik:GridBoundColumn DataField="reachedthresholdnumber" HeaderText="Reachedthreshold Number"
                                                                            UniqueName="column15" meta:resourcekey="GridBoundColumnResource14" HeaderStyle-Width="150px">
                                                                        </telerik:GridBoundColumn>
                                                                        <telerik:GridBoundColumn DataField="reachedthresholdid" HeaderText="Reachedthreshold ID"
                                                                            UniqueName="column16" meta:resourcekey="GridBoundColumnResource14" HeaderStyle-Width="125px" >
                                                                        </telerik:GridBoundColumn>
                                                                    </Columns>
                                                                    <NoRecordsTemplate>
                                                                        <div style="text-align: center; padding-top: 50px; height: 100px; font-size: 12pt;">
<asp:Label ID="lblNoRecords"  meta:resourcekey="lblNoRecordsResource1" runat="server" Text="There are no records to display"></asp:Label>
</div>
                                                                    </NoRecordsTemplate>

    <EditFormSettings>
    <EditColumn FilterControlAltText="Filter EditCommandColumn column"></EditColumn>
    </EditFormSettings>
                                                                </MasterTableView>
                                                                <FooterStyle CssClass="GridFooter"></FooterStyle>
                                                                <HeaderStyle CssClass="GridHeader"></HeaderStyle>
                                                                <ItemStyle CssClass="GridRow"></ItemStyle>

    <FilterMenu EnableImageSprites="False"></FilterMenu>

    <HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Default"></HeaderContextMenu>
                                                            </telerik:RadGrid>

in coding:
 protected void Page_PreRender(object sender, EventArgs e)
        {
           // string selectedItemname = string.Empty;// ;
            object SelectedValue=null;
            if (radGridPromotionStatus.SelectedItems.Count > 0)
            {
                SelectedValue = radGridPromotionStatus.SelectedValue;
                //var name = radGridPromotionStatus.SelectedValues["column11"].ToString();

                //foreach (GridDataItem item in radGridPromotionStatus.SelectedItems)
                //{
                //    selectedItemname = item["column11"].Text;

                //}

            }

            if (SelectedValue != null)
            {
                divcontext.Visible = true;
            }

            //if (selectedItemname != "")
            //{
            //   // divcontext.Visible = true;
            //}
            else
            {
            }
        }

Monday 23 September 2013

get organization language information in sql server for crm 2011


getting the sql server information:

SELECT * FROM information_schema.tables
WHERE TABLE_NAME like  '%lang%'
select * from OrganizationLanguagePack

UPDATE OrganizationLanguagePack set isenabled=1 where languageid=3082


Thursday 25 April 2013

Tuesday 26 February 2013

Null Values in SSRS Parameters


we have option to give parameter as blank or null
by enabling the features


CRMAF in ssrs



select filteredsalesorder.ordernumber,filteredsalesorder.name,filteredsalesorder.createdon,filteredsalesorder.quoteid,filteredsalesorder.totalamount,
filteredaccount.address1_line1,filteredaccount.address1_line2,filteredaccount.address1_line3,filteredaccount.name,filteredaccount.address1_city,filteredaccount.address1_country,
filteredaccount.address1_stateorprovince,filteredaccount.address1_postalcode,
filteredbusinessunit.address2_line1,filteredbusinessunit.address2_line2,filteredbusinessunit.address2_line3,filteredbusinessunit.address2_city,
filteredbusinessunit.address2_stateorprovince,filteredbusinessunit.address2_postalcode,filteredbusinessunit.address2_country
 from filteredsalesorder,filteredbusinessunit,filteredaccount
where (filteredsalesorder.customerid = filteredaccount.accountid) and (filteredsalesorder.jmh_store=filteredbusinessunit.businessunitid)

select * from filteredsalesorder as CRMAF_filteredsalesorder,filteredbusinessunit,filteredaccount
where (CRMAF_filteredsalesorder.customerid = filteredaccount.accountid) and (CRMAF_filteredsalesorder.jmh_store=filteredbusinessunit.businessunitid)

select CRMAF_filteredsalesorder.ordernumber,CRMAF_filteredsalesorder.name,CRMAF_filteredsalesorder.createdon,CRMAF_filteredsalesorder.quoteid,CRMAF_filteredsalesorder.totalamount,
filteredaccount.address1_line1,filteredaccount.address1_line2,filteredaccount.address1_line3,filteredaccount.name,filteredaccount.address1_city,filteredaccount.address1_country,
filteredaccount.address1_stateorprovince,filteredaccount.address1_postalcode,
filteredbusinessunit.address2_line1,filteredbusinessunit.address2_line2,filteredbusinessunit.address2_line3,filteredbusinessunit.address2_city,
filteredbusinessunit.address2_stateorprovince,filteredbusinessunit.address2_postalcode,filteredbusinessunit.address2_country
 from filteredsalesorder as CRMAF_filteredsalesorder ,filteredbusinessunit,filteredaccount
where (CRMAF_filteredsalesorder.customerid = filteredaccount.accountid) and (CRMAF_filteredsalesorder.jmh_store=filteredbusinessunit.businessunitid)


Monday 25 February 2013

Filter dataset records based on another dataset data in ssrs


Senario:
we have two datasets.
dataset1 and dataset2.
based on dataset1 values we need to filter dataset2 data.

Doing thourgh FetchXml.

First create the Dataset1 with enableprefiltering="1".
Ex:


<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
  <entity name="salesorder" enableprefiltering="1">
    <attribute name="name" />
    <attribute name="customerid" />
    <attribute name="statuscode" />
    <attribute name="totalamount" />
    <attribute name="createdon" />
    <attribute name="ordernumber" />
    <attribute name="quoteid" />
    <attribute name="salesorderid" />
    <order attribute="name" descending="false" />
    <filter type="and">
      <condition attribute="name" operator="not-null" />
    </filter>
    <link-entity name="account" from="accountid" to="customerid" alias="aa">
      <attribute name="name" />
      <attribute name="address1_name" />
      <attribute name="address1_line1" />
      <attribute name="address1_line2" />
      <attribute name="address1_line3" />
      <attribute name="address1_city" />
      <attribute name="address1_stateorprovince" />
      <attribute name="address1_postalcode" />
      <attribute name="address1_country" />
      <filter type="and">
        <condition attribute="name" operator="not-null" />
      </filter>
    </link-entity>
    <link-entity name="businessunit" from="businessunitid" to="jmh_store" alias="ab">
      <attribute name="address2_name" />
      <attribute name="address2_line1" />
      <attribute name="address2_line2" />
      <attribute name="address2_line3" />
      <attribute name="address2_city" />
      <attribute name="address2_stateorprovince" />
      <attribute name="address2_postalcode" />
      <attribute name="address2_country" />
      <filter type="and">
        <condition attribute="name" operator="not-null" />
      </filter>
    </link-entity>
  </entity>
</fetch>

the about code will join "order", "Account","businessunit" tables.

next :
dataset2:


<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
  <entity name="salesorderdetail">
    <attribute name="productid" />
    <attribute name="productdescription" />
    <attribute name="priceperunit" />
    <attribute name="quantity" />
    <attribute name="extendedamount" />   
    <attribute name="baseamount" />
    <attribute name="jmh_orderamount" />    
    <attribute name="salesorderid" />
    <attribute name="salesorderdetailid" />
    <order attribute="productid" descending="false" />
    <filter type="and">
      <condition attribute="quantity" operator="not-null" />
    </filter>
  </entity>
</fetch>

now you need to get the data in dataset2 relating of dataset1;

create parameters 










Give the values as default values.
Use this filter and create another dataset3 for the Salesorder.
after that create another parameter



so using 3 parameter
create filter on dataset2.






u will get the correct details.

Wednesday 20 February 2013

Date Validation in crm 2011 using javascript


Validate two date fields using javascript.


function ValidateDates()
{

var startdate = Xrm.Page.getAttribute("jmh_invoicedate").getValue();
var dueby = Xrm.Page.getAttribute("jmh_daterecieved").getValue();

if(startdate != null && dueby != null)
{
if(dueby.setHours(0,0,0,0) < startdate.setHours(0,0,0,0))
{
alert("Recieved Date must be greater than or equal to Invoice Date");
var pass = Xrm.Page.data.entity.attributes.get("jmh_daterecieved");
pass.setValue(null);
//event.returnValue = false;
//return false;
}
}
}


Tuesday 5 February 2013

xrmtoolkit

Open a Email Form in crm 2011 with selected records details

Senario :

select a record in crm 2011 grid view and click a ribbon button.
open the E-mail form with the selected record details as body(description).

for this first create on custom field in E-mail activity with "new_body"

create a javascript like this:


function emailopen(ids) {

    // var selectedid = ids;
    var entityname = 'new_cooldrink';
 
    resultXml = RetrieveEntityById(entityname,ids, 'new_name');
    var parameters = {};
    parameters["subject"] = 'This is Subject';
    parameters["new_body"] = resultXml.toString();
    Xrm.Utility.openEntityForm("email", null, parameters);

}
//dont change any thing (for reference)
function RetrieveEntityById(prmEntityName, prmEntityId, prmEntityColumns) {
    var resultXml, errorCount, msg, xmlHttpRequest, arrayEntityColumns, xmlEntityColumns;
    arrayEntityColumns = prmEntityColumns.split(",");
    for (var i = 0; i < arrayEntityColumns.length; i++) {
        xmlEntityColumns += "<q1:Attribute>" + arrayEntityColumns[i] + "</q1:Attribute>";
    }
    var authenticationHeader = Xrm.Page.context.getAuthenticationHeader();
    //Prepare the SOAP message.
    var xml = "<?xml version='1.0' encoding='utf-8'?>" +
    "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'" +
    " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" +
    " xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
    authenticationHeader +
    "<soap:Body>" +
    "<Retrieve xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
    "<entityName>" + prmEntityName + "</entityName>" +
    "<id>" + prmEntityId + "</id>" +
    "<columnSet xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' xsi:type='q1:ColumnSet'>" +
    "<q1:Attributes>" +
    xmlEntityColumns +
   "</q1:Attributes>" +
    "</columnSet>" +
    "</Retrieve></soap:Body></soap:Envelope>";
    //call function to create Soap Request to ms crm webservice
    xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
    xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
    xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
    xmlHttpRequest.send(xml);
    resultXml = xmlHttpRequest.responseXML;
    var errorCount = resultXml.selectNodes('//error').length;
    if (errorCount != 0) {
        var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
        alert("Error Message : " + msg);
    }
    else {
        return resultXml;
    }
}

create a web resource and paste this code:

after that create ribbon button:


then write a javascript code in E-mail onload event:


function emailonload()
{

 if (Xrm.Page.data.entity.attributes.get('test_body').getValue()!= null)
     {

    var selectedid = Xrm.Page.data.entity.attributes.get('new_body').getValue();
    var entityname = 'new_cooldrink';
    //var columns = 'new_name','new_productcount';
    var x = null;
    var y = null;
    var resultXml = RetrieveEntityById(entityname, selectedid, 'new_name,new_productcount');
    if (resultXml != null && resultXml.selectSingleNode('//q1:new_name') != null) {
        x = resultXml.selectSingleNode('//q1:new_name').nodeTypedValue; //.getAttribute("name");    
    }
    if (resultXml != null && resultXml.selectSingleNode('//q1:new_productcount') != null) {
        y = resultXml.selectSingleNode('//q1:new_productcount').nodeTypedValue; //.getAttribute("name");      
    }
    //var table = "<table border='1' bgcolor='#00FF00'><tr><td> Name </td> <td> Test </td> </tr><tr><td>" + x + "</td><td>" + y + "</td></tr></table>";
    var z = x + y;
    Xrm.Page.data.entity.attributes.get('new_body').setValue(z);
}
}

function xmlToString(resultXml) {
    if ($(resultXml).find('q1\\:Attributes').length != 0) {
        response = $(resultXml).find('q1\\:Attributes').eq(0);
    } else {
        response = $(resultXml).find('Attributes').eq(0); ; //Chrome 24.0.1312.52 could not find node by the previous code
    }
    var result = ((typeof window.CrmEncodeDecode != 'undefined') ? window.CrmEncodeDecode.CrmXmlDecode(response.text()) : crmXmlDecode(response.text()));

    return result;
}


function RetrieveEntityById(prmEntityName, prmEntityId, prmEntityColumns) {
    var resultXml, errorCount, msg, xmlHttpRequest, arrayEntityColumns, xmlEntityColumns;
    arrayEntityColumns = prmEntityColumns.split(",");
    for (var i = 0; i < arrayEntityColumns.length; i++) {
        xmlEntityColumns += "<q1:Attribute>" + arrayEntityColumns[i] + "</q1:Attribute>";
    }
    var authenticationHeader = Xrm.Page.context.getAuthenticationHeader();
    //Prepare the SOAP message.
    var xml = "<?xml version='1.0' encoding='utf-8'?>" +
    "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'" +
    " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" +
    " xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
    authenticationHeader +
    "<soap:Body>" +
    "<Retrieve xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
    "<entityName>" + prmEntityName + "</entityName>" +
    "<id>" + prmEntityId + "</id>" +
    "<columnSet xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' xsi:type='q1:ColumnSet'>" +
    "<q1:Attributes>" +
    xmlEntityColumns +
   "</q1:Attributes>" +
    "</columnSet>" +
    "</Retrieve></soap:Body></soap:Envelope>";
    //call function to create Soap Request to ms crm webservice
    xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
    xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
    xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
    xmlHttpRequest.send(xml);
    resultXml = xmlHttpRequest.responseXML;
    var errorCount = resultXml.selectNodes('//error').length;
    if (errorCount != 0) {
        var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
        alert("Error Message : " + msg);
    }
    else {
        return resultXml;
    }
}

for this code execution we need to add the
Jquery.js
Json2.js
XrmServiceToolkit.js in E-mail form.



launch a report in Ribbon button click crm 2011

Launch a Report in Ribbon Button click

First create a Report in ssrs or report area in crm 2011

if you created in SSRS. deploy in crm.
Get the GUID of the report

how to get guid:
open the report and press F11.

then write the below code in javascript:


// JScript source code
function openreport(id) {
   
    var errorMessage = "Context is not available.";
    var context;
    if (typeof GetGlobalContext != "undefined") {
        context = GetGlobalContext();
    }
    else {
        if (typeof Xrm != "undefined") {

            context = Xrm.Page.context;
        }
        else {
            alert(errorMessage);
            return;
        }
    }
    var str = id;
//    alert(id);
//     var strId = str.replace("{", "");
//alert("hi");
var orgUrl = context.getServerUrl();
var currEntityObjTypeCode= Xrm.Page.context.getQueryStringParameters().etc
//alert(currEntityObjTypeCode);
//alert(orgUrl);
var reportUrl = orgUrl + "/crmreports/viewer/viewer.aspx?action=run&context=records&helpID=OrderAcknowledgement.rdl&id=%7b20a4c6e9-8f6f-e211-957a-

00155d000b45%7d&records=" + encodeURIComponent(  id ) +"&recordstype="+currEntityObjTypeCode;
//alert(reportUrl);
window.open(reportUrl);//, "_blank", "width=900px,height=600px,resizable=1");
   //return reportUrl;
  }



Change in code :

chage the id parameter with your Report guid.

create a web resource and put this code as jscript.









Sunday 3 February 2013

Connect CRM 2011 Online with SSRS

Connecting CRM 2011 online with SSRS.

in online service we have 2 choices.
1. CRM 2011 Online
2. CRM 2011 Office 365 (includes Free Trail Version)

CRM 2011 Online connection.

http://garethtuckercrm.com/2011/03/24/fetch-xml-reports-for-crm-2011-online/

based on the above link we will get.
in credentials we need to give the Online account and password.

CRM 2011 Office 365.

first we need to create a report in crm 2011 and
click on edit,
Actions-->Download.

in SSRS, take add existing item and add it.
do the manipulation again import into crm 2011.

if you want to use fetchxml for On primse version.
give the connection string like:
http://crmserver/organization

in credential take the window authentication.

Wednesday 30 January 2013

SSRS Some Tips


For getting Month and Year :

=Monthname(Datepart("m",Fields!duedateValue.Value)) & " " & Datepart("yyyy", Fields!duedateValue.Value)

Result: May 2013.

Difference Between two Dates:

=DateDiff("d",Fields!tvsi_approveddateValue.Value,Fields!actualclosedateValue.Value)

it will give the
result : 2.


For Month only :

=MonthName(Month(Fields!datedeliveredValue.Value))

Wednesday 16 January 2013

Runing Report on Selected Record


http://social.microsoft.com/Forums/en-CA/crmdevelopment/thread/34f44b87-8ef7-4b3c-8a3e-df22599277c5

first create a datasource.

creating dataset:

select * from filterednew_cool as CRMAF_filterednew_cool

then run and deploy the report.

we will get the option for selected records in running the report.

Wednesday 9 January 2013

retrieve data of lookup field in crm 2011

for this we need to download the xrmservicetoolkit.

http://xrmservicetoolkit.codeplex.com/releases

after download we will get 3 .js files.
1. jquery.js
2.json2.js
3.xrmservicetoolkit.js

just add these three as webresource.

write on javascript function;


function AlertGUID() {

    var primaryContactGUID = Xrm.Page.data.entity.attributes.get("parentcustomerid").getValue()[0].id;
var cols=["lastname"];
var retrievedaccount = XrmServiceToolkit.Soap.Retrieve("account", primaryContactGUID, cols);
var name = retrievedaccount.attributes['lastname'].value;

   alert(name);

}

add these function as webresource.

add 
downloaded webresorce add to the form in onload.
and custom function will give on the onchage of lookup filed.

then run.
for debug. press F12 in the form and 
select your code on : Formscript 
click on debugg. put pointer.

Monday 7 January 2013

Excel Upload/Download- update crm 2011 form

For this
aspx code:


<body>
    <form id="form1" runat="server">
   <asp:FileUpload ID="fu_ImportCSV" runat="server" />
&nbsp;&nbsp;&nbsp;&nbsp;
    <asp:Button ID="Button2" runat="server" Text="NowUpload"
        onclick="Button2_Click" />
<br/>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="upload" />
    <asp:Button ID="btnimport" runat="server" onclick="btnimport_Click"
        Text="Import" />
        <asp:GridView ID="grvExcelData" runat="server"
        Height="80px" Width="234px">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<%--<Columns>
               <asp:BoundField HeaderText="First Name" />
                <asp:BoundField HeaderText="Last Name"/>
                <asp:BoundField HeaderText="Job Title" />
</Columns>--%>
</asp:GridView>
<asp:Button ID="btnexport" runat="server" Text="Export to Excel"
        onclick="btnexport_Click" />
</form>
&nbsp;&nbsp;&nbsp;
    </form>
</body>


using System;
using System.Collections.Generic;
using System.Linq;
//using System;
//using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Web;
using System.Web.Services;
using System.ServiceModel.Description;
using System.Net;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Xrm.Sdk.Query;
using System.Configuration;
//using Sulekha.Order.CrmSdk;
using System.Linq.Expressions;
using Xrm;
using System.Collections.ObjectModel;
using System.Collections;
using System.Collections.Specialized;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
namespace FullExcel
{
    public partial class Excelwork : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Order_Accepted();
        }

        protected void Order_Accepted()
        {

             ClientCredentials credentials = new ClientCredentials();
            credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
            Uri OrganizationUri = new Uri("http://crmsrv/kryptos/XRMServices/2011/Organization.svc");
            Uri HomeRealmUri = null;
            using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, credentials, null))
            {
                Microsoft.Xrm.Sdk.IOrganizationService service = (Microsoft.Xrm.Sdk.IOrganizationService)serviceProxy;

                QueryExpression query = new QueryExpression("contact");
                query.ColumnSet.AddColumns("firstname", "lastname", "jobtitle", "contactid");
                EntityCollection result1 = serviceProxy.RetrieveMultiple(query);
                DataSet ds = new DataSet();
                DataTable dt = new DataTable();
                dt.Columns.Add("First Name");
                dt.Columns.Add("Last Name");
                dt.Columns.Add("Job Title");
                dt.Columns.Add("Contact Id");
                //dt.Columns.Add("Product Price");
                //dt.Columns.Add("Order Status");
                //dt.Columns.Add("Shipped to City");
                foreach (Entity entities in result1.Entities)
                {
                    DataRow dr = dt.NewRow();
                    dr["First Name"] = entities.Attributes["firstname"].ToString();
                    dr["Last Name"] = entities.Attributes["lastname"].ToString();
                    dr["Job Title"] = entities.Attributes["jobtitle"].ToString();
                    dr["Contact Id"] = entities.Attributes["contactid"].ToString();
                    dt.Rows.Add(dr);
                }
                ds.Tables.Add(dt);
                grvExcelData.DataSource = ds;
                grvExcelData.DataBind();
                Session["dtlist"] = dt;

                grvExcelData.HeaderRow.Cells[3].Visible = false;
                foreach (GridViewRow gvr in grvExcelData.Rows)
                {
                    gvr.Cells[3].Visible = false;
                }
            }

        }

        protected void btnexport_Click(object sender, EventArgs e)
        {
       


            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition",
             "attachment;filename=GridViewExport.csv");
            Response.Charset = "";
            Response.ContentType = "application/text";          
            DataTable dt1 = (DataTable)Session["dtlist"];      

            grvExcelData.DataSource = dt1;
            grvExcelData.AllowPaging = false;
            grvExcelData.DataBind();
            StringBuilder sb = new StringBuilder();
            for (int k = 0; k < dt1.Columns.Count; k++)
            {
                //add separator
                sb.Append(dt1.Columns[k].Caption + ',');
            }
            //append new line
            sb.Append("\r\n");
            for (int i = 0; i < grvExcelData.Rows.Count; i++)
            {
                for (int k = 0; k < dt1.Columns.Count; k++)
                {
                    //add separator
                    sb.Append(grvExcelData.Rows[i].Cells[k].Text + ',');
                }
                //append new line
                sb.Append("\r\n");
            }
            Response.Output.Write(sb.ToString());
            Response.Flush();
            Response.End();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {

        }

        protected void btnimport_Click(object sender, EventArgs e)
        {
         
        }
        private object ReadToEnd(string filePath)
        {
            DataTable dtDataSource = new DataTable();
            string[] fileContent = File.ReadAllLines(filePath);
            if (fileContent.Count() > 0)
            {
                //Create data table columns
                string[] columns = fileContent[0].Split(',');
                for (int i = 0; i < columns.Count(); i++)
                {
                    dtDataSource.Columns.Add(columns[i]);
                }

                //Add row data
                for (int i = 1; i < fileContent.Count(); i++)
                {
                    string[] rowData = fileContent[i].Split(',');
                    dtDataSource.Rows.Add(rowData);
                }
            }
            return dtDataSource;
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            string filePath = string.Empty;
            if (fu_ImportCSV.HasFile && fu_ImportCSV.PostedFile.ContentType.Equals("application/vnd.ms-excel"))
            {
                string fn = System.IO.Path.GetFileName(fu_ImportCSV.PostedFile.FileName);
                string naming = fn.Split('.')[0] + DateTime.Now.ToString("yyyymmdd") + ".csv";// +fn.Split('.')[1];
                string SaveLocation = Server.MapPath("Data") + "\\" + naming;
                try
                {
                    fu_ImportCSV.PostedFile.SaveAs(SaveLocation);
                    Response.Write("The file has been uploaded.");
                }
                catch (Exception ex)
                {
                    Response.Write("Error: " + ex.Message);
                    //Note: Exception.Message returns a detailed message that describes the current exception.
                    //For security reasons, we do not recommend that you return Exception.Message to end users in
                    //production environments. It would be better to return a generic error message.
                }

                DataTable dtCSVTable = (DataTable)ReadToEnd(fu_ImportCSV.PostedFile.FileName);
                foreach (DataRow dr in dtCSVTable.Rows)
                {
                    string fname = dr["First Name"].ToString();
                    string lname = dr["Last Name"].ToString();
                    string jt = dr["Job Title"].ToString();
                    string cid = dr["Contact Id"].ToString();
                    string city = dr["City"].ToString();
                    Guid conid = new Guid();
                    conid = new Guid(cid);
                    ClientCredentials credentials = new ClientCredentials();
                    credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
                    Uri OrganizationUri = new Uri("http://crmsrv/kryptos/XRMServices/2011/Organization.svc");
                    Uri HomeRealmUri = null;
                    using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, credentials, null))
                    {
                        Microsoft.Xrm.Sdk.IOrganizationService service = (Microsoft.Xrm.Sdk.IOrganizationService)serviceProxy;

                        ColumnSet cols = new ColumnSet(true);
                        var conts = service.Retrieve("contact", conid, cols);

                        conts["firstname"] = fname;
                        conts["lastname"] = lname;
                        conts["jobtitle"] = jt;
                        conts["address1_city"] = city;//dr["City"].ToString();
                        service.Update(conts);
                    }

                }
            }

        }
    }
}

create one folder with name "Data" and create early bound.


Thursday 3 January 2013

export into .csv format

c sharp code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web.SessionState;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.OleDb;
using System.Text;

namespace excel_upload
{
    public partial class upload : System.Web.UI.Page
    {
        protected System.Web.UI.HtmlControls.HtmlInputFile File1;
        protected System.Web.UI.HtmlControls.HtmlInputButton Submit1;
        DataTable dt = new DataTable();
        DataSet ds = new DataSet();
        protected void Page_Load(object sender, EventArgs e)
        {
         
            //if (IsPostBack)
            //{
            //    Button1_Click(sender,e);
            //}

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
            {
                string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);

                string naming = fn.Split('.')[0] + DateTime.Now.ToString("yyyymmdd") + ".csv";// +fn.Split('.')[1]; //fn.Substring(0, 4);// fn + DateTime.Now;
                //string sure = naming + DateTime.Now + ".csv";
                string SaveLocation = Server.MapPath("Data") + "\\" + naming;
                try
                {
                    File1.PostedFile.SaveAs(SaveLocation);
                    Response.Write("The file has been uploaded.");
                }
                catch (Exception ex)
                {
                    Response.Write("Error: " + ex.Message);
                    //Note: Exception.Message returns a detailed message that describes the current exception.
                    //For security reasons, we do not recommend that you return Exception.Message to end users in
                    //production environments. It would be better to return a generic error message.
                }
            }
            else
            {
                Response.Write("Please select a file to upload.");
            }
        }

        protected void btnimport_Click(object sender, EventArgs e)
        {

            if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
            {
                string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);

                string naming = fn.Split('.')[0] + DateTime.Now.ToString("yyyymmdd") + ".xls";// +fn.Split('.')[1]; //fn.Substring(0, 4);// fn + DateTime.Now;
                //string sure = naming + DateTime.Now + ".csv";
                string SaveLocation = Server.MapPath("Data") + "\\" + naming;
                try
                {
                    File1.PostedFile.SaveAs(SaveLocation);
                    Response.Write("The file has been uploaded.");
                }
                catch (Exception ex)
                {
                    Response.Write("Error: " + ex.Message);
                    //Note: Exception.Message returns a detailed message that describes the current exception.
                    //For security reasons, we do not recommend that you return Exception.Message to end users in
                    //production environments. It would be better to return a generic error message.
                }
            }
            else
            {
                Response.Write("Please select a file to upload.");
            }

            string connString = "";
            string strFileType = Path.GetExtension(File1.PostedFile.FileName).ToLower();
            string path = File1.PostedFile.FileName;
            if (strFileType.Trim() == ".xls")
            {
                connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
            }

            //if (strFileType.Trim() == ".csv")
            //{
            //    connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
            //}
            if (strFileType.Trim() == ".xlsx")
            {
                connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
            }

            string query = "SELECT * FROM [Sheet1$]";

            OleDbConnection conn = new OleDbConnection(connString);
            if (conn.State == ConnectionState.Closed)
                conn.Open();
            OleDbCommand cmd = new OleDbCommand(query, conn);
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
           // DataSet ds = new DataSet();
            da.Fill(ds);
           
            dt = ds.Tables[0];
            foreach (DataRow dr in dt.Rows)
            {
                string name = dr["Name"].ToString();
                string Extention = dr["Extension"].ToString();
                string customer = dr["Customer"].ToString();
                string bt = dr["BASE TABLE"].ToString();

            }
            grvExcelData.DataSource = ds.Tables[0];
            grvExcelData.DataBind();
            ViewState["dtList"] = dt;


            da.Dispose();
            conn.Close();
            conn.Dispose();
        }
        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */
        }

        protected void btnexport_Click(object sender, EventArgs e)
        {
            //Response.ClearContent();
            //Response.Buffer = true;
            //Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
            //Response.ContentType = "application/ms-excel";
            //StringWriter sw = new StringWriter();
            //HtmlTextWriter htw = new HtmlTextWriter(sw);
            //grvExcelData.AllowPaging = false;
            //grvExcelData.DataBind();
            //grvExcelData.RenderControl(htw);
            //Response.Write(sw.ToString());
            //Response.End();



            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition",
             "attachment;filename=GridViewExport.csv");
            Response.Charset = "";
            Response.ContentType = "application/text";
            //Button1_Click(sender, e);
            grvExcelData.AllowPaging = false;
            grvExcelData.DataBind();
           

            StringBuilder sb = new StringBuilder();
            for (int k = 0; k < grvExcelData.Columns.Count; k++)
            {
                //add separator
                sb.Append(grvExcelData.Columns[k].HeaderText + ',');
            }
            //append new line
            sb.Append("\r\n");
            for (int i = 0; i < grvExcelData.Rows.Count; i++)
            {
                for (int k = 0; k < grvExcelData.Columns.Count; k++)
                {
                    //add separator
                    sb.Append(grvExcelData.Rows[i].Cells[k].Text + ',');
                }
                //append new line
                sb.Append("\r\n");
            }
            Response.Output.Write(sb.ToString());
            Response.Flush();
            Response.End();




            //try
            //{
            //    DataTable dt1 = (DataTable)ViewState["dtList"];
            //    if (dt1 == null)
            //    {
            //        throw new Exception("No Records to Export");
            //    }
            //    string Path = "D:\\ImportExcelFromDatabase\\myexcelfile_" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + ".csv";
            //    FileInfo FI = new FileInfo(Path);
            //    StringWriter stringWriter = new StringWriter();
            //    HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
            //    DataGrid DataGrd = new DataGrid();
            //    DataGrd.DataSource = dt1;
            //    DataGrd.DataBind();

            //    DataGrd.RenderControl(htmlWrite);
            //    string directory = Path.Substring(0, Path.LastIndexOf("\\"));// GetDirectory(Path);
            //    if (!Directory.Exists(directory))
            //    {
            //        Directory.CreateDirectory(directory);
            //    }

            //    System.IO.StreamWriter vw = new System.IO.StreamWriter(Path, true);
            //    stringWriter.ToString().Normalize();
            //    vw.Write(stringWriter.ToString());
            //    vw.Flush();
            //    vw.Close();
            //    WriteAttachment(FI.Name, "application/text", stringWriter.ToString());
            //}
            //catch (Exception ex)
            //{
            //    //throw new Exception(ex.Message);
            //}
         
        }
        public static void WriteAttachment(string FileName, string FileType, string content)
        {
            HttpResponse Response = System.Web.HttpContext.Current.Response;
            Response.ClearHeaders();
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
            Response.ContentType = FileType;
            Response.Write(content);
            Response.End();

        }

    }
}

aspx code:


<body>
    <form id="Form1" method="post" enctype="multipart/form-data" runat="server">
<input type="file" id="File1" name="File1" runat="server" />
<br/>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="upload" />
    <asp:Button ID="btnimport" runat="server" onclick="btnimport_Click"
        Text="Import" />
        <asp:GridView ID="grvExcelData" runat="server">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
<asp:Button ID="btnexport" runat="server" Text="Export to Excel"
        onclick="btnexport_Click" />
</form>
</body>

reading .csv format file in c sharp

c sharp code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web.SessionState;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.OleDb;
using System.Text;


namespace excel_upload
{
    public partial class onlyupload : System.Web.UI.Page
    {
        protected System.Web.UI.HtmlControls.HtmlInputFile File1;
        protected System.Web.UI.HtmlControls.HtmlInputButton Submit1;
        DataTable dt = new DataTable();
        DataSet ds = new DataSet();

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        //protected void btnimport_Click(object sender, EventArgs e)
        //{
        //    string filePath = string.Empty;
        //    if (fu_ImportCSV.HasFile && fu_ImportCSV.PostedFile.ContentType.Equals("application/vnd.ms-excel"))
        //    {
        //        gv_GridView.DataSource = (DataTable)ReadToEnd(fu_ImportCSV.PostedFile.FileName);
        //        gv_GridView.DataBind();
        //        lbl_ErrorMsg.Visible = false;
        //    }
        //    else
        //    {
        //        lbl_ErrorMsg.Text = "Please check the selected file type";
        //        lbl_ErrorMsg.Visible = true;
        //    }

        //}

        private object ReadToEnd(string filePath)
        {
            DataTable dtDataSource = new DataTable();
            string[] fileContent = File.ReadAllLines(filePath);
            if (fileContent.Count() > 0)
            {
                //Create data table columns
                string[] columns = fileContent[0].Split(',');
                for (int i = 0; i < columns.Count(); i++)
                {
                    dtDataSource.Columns.Add(columns[i]);
                }

                //Add row data
                for (int i = 1; i < fileContent.Count(); i++)
                {
                    string[] rowData = fileContent[i].Split(',');
                    dtDataSource.Rows.Add(rowData);
                }
            }
            return dtDataSource;
        }

        protected void btn_ImportCSV_Click(object sender, EventArgs e)
        {
            string filePath = string.Empty;
            if (fu_ImportCSV.HasFile && fu_ImportCSV.PostedFile.ContentType.Equals("application/vnd.ms-excel"))
            {
                DataTable dtCSVTable = (DataTable)ReadToEnd(fu_ImportCSV.PostedFile.FileName);
                gv_GridView.DataSource = (DataTable)ReadToEnd(fu_ImportCSV.PostedFile.FileName);
                gv_GridView.DataBind();
                lbl_ErrorMsg.Visible = false;
            }
            else
            {
                lbl_ErrorMsg.Text = "Please check the selected file type";
                lbl_ErrorMsg.Visible = true;
            }
        }
    }
}

aspx page:


<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="fu_ImportCSV" runat="server" />
        <asp:Button ID="btn_ImportCSV" runat="server" Text="Import CSV" OnClick="btn_ImportCSV_Click" />
        <br />
        <br />
        <asp:Label ID="lbl_ErrorMsg" runat="server" Visible="false"></asp:Label>
        <br />
        <br />
        <asp:GridView ID="gv_GridView" runat="server" CellPadding="4" ForeColor="#333333"
            GridLines="None">
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <RowStyle BackColor="#EFF3FB" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>
    </div>
    </form>
</body>

reference :

http://forums.asp.net/t/1705264.aspx/1

export and import excel sheet through c sharp

 c sharp code :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web.SessionState;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.OleDb;

namespace excel_upload
{
    public partial class upload : System.Web.UI.Page
    {
        protected System.Web.UI.HtmlControls.HtmlInputFile File1;
        protected System.Web.UI.HtmlControls.HtmlInputButton Submit1;
        DataTable dt = new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {
            //if (IsPostBack)
            //{
            //    Button1_Click(sender,e);
            //}

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
            {
                string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);

                string naming = fn.Split('.')[0] + DateTime.Now.ToString("yyyymmdd") + ".csv";// +fn.Split('.')[1]; //fn.Substring(0, 4);// fn + DateTime.Now;
                //string sure = naming + DateTime.Now + ".csv";
                string SaveLocation = Server.MapPath("Data") + "\\" + naming;
                try
                {
                    File1.PostedFile.SaveAs(SaveLocation);
                    Response.Write("The file has been uploaded.");
                }
                catch (Exception ex)
                {
                    Response.Write("Error: " + ex.Message);
                    //Note: Exception.Message returns a detailed message that describes the current exception.
                    //For security reasons, we do not recommend that you return Exception.Message to end users in
                    //production environments. It would be better to return a generic error message.
                }
            }
            else
            {
                Response.Write("Please select a file to upload.");
            }
        }

        protected void btnimport_Click(object sender, EventArgs e)
        {

            if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
            {
                string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);

                string naming = fn.Split('.')[0] + DateTime.Now.ToString("yyyymmdd") + ".xls";// +fn.Split('.')[1]; //fn.Substring(0, 4);// fn + DateTime.Now;
                //string sure = naming + DateTime.Now + ".csv";
                string SaveLocation = Server.MapPath("Data") + "\\" + naming;
                try
                {
                    File1.PostedFile.SaveAs(SaveLocation);
                    Response.Write("The file has been uploaded.");
                }
                catch (Exception ex)
                {
                    Response.Write("Error: " + ex.Message);
                    //Note: Exception.Message returns a detailed message that describes the current exception.
                    //For security reasons, we do not recommend that you return Exception.Message to end users in
                    //production environments. It would be better to return a generic error message.
                }
            }
            else
            {
                Response.Write("Please select a file to upload.");
            }

            string connString = "";
            string strFileType = Path.GetExtension(File1.PostedFile.FileName).ToLower();
            string path = File1.PostedFile.FileName;
            if (strFileType.Trim() == ".xls")
            {
                connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
            }

            //if (strFileType.Trim() == ".csv")
            //{
            //    connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
            //}
            if (strFileType.Trim() == ".xlsx")
            {
                connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
            }

            string query = "SELECT * FROM [Sheet1$]";

            OleDbConnection conn = new OleDbConnection(connString);
            if (conn.State == ConnectionState.Closed)
                conn.Open();
            OleDbCommand cmd = new OleDbCommand(query, conn);
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
           
            dt = ds.Tables[0];
            foreach (DataRow dr in dt.Rows)
            {
                string name = dr["Name"].ToString();
                string Extention = dr["Extension"].ToString();
                string customer = dr["Customer"].ToString();
                string bt = dr["BASE TABLE"].ToString();

            }
            grvExcelData.DataSource = ds.Tables[0];
            grvExcelData.DataBind();
            ViewState["dtList"] = dt;


            da.Dispose();
            conn.Close();
            conn.Dispose();
        }
        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */
        }

        protected void btnexport_Click(object sender, EventArgs e)
        {
            //Response.ClearContent();
            //Response.Buffer = true;
            //Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
            //Response.ContentType = "application/ms-excel";
            //StringWriter sw = new StringWriter();
            //HtmlTextWriter htw = new HtmlTextWriter(sw);
            //grvExcelData.AllowPaging = false;
            //grvExcelData.DataBind();
            //grvExcelData.RenderControl(htw);
            //Response.Write(sw.ToString());
            //Response.End();

            try
            {
                DataTable dt1 = (DataTable)ViewState["dtList"];
                if (dt1 == null)
                {
                    throw new Exception("No Records to Export");
                }
                string Path = "D:\\ImportExcelFromDatabase\\myexcelfile_" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + ".xls";
                FileInfo FI = new FileInfo(Path);
                StringWriter stringWriter = new StringWriter();
                HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
                DataGrid DataGrd = new DataGrid();
                DataGrd.DataSource = dt1;
                DataGrd.DataBind();

                DataGrd.RenderControl(htmlWrite);
                string directory = Path.Substring(0, Path.LastIndexOf("\\"));// GetDirectory(Path);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                System.IO.StreamWriter vw = new System.IO.StreamWriter(Path, true);
                stringWriter.ToString().Normalize();
                vw.Write(stringWriter.ToString());
                vw.Flush();
                vw.Close();
                WriteAttachment(FI.Name, "application/vnd.ms-excel", stringWriter.ToString());
            }
            catch (Exception ex)
            {
                //throw new Exception(ex.Message);
            }
         
        }
        public static void WriteAttachment(string FileName, string FileType, string content)
        {
            HttpResponse Response = System.Web.HttpContext.Current.Response;
            Response.ClearHeaders();
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
            Response.ContentType = FileType;
            Response.Write(content);
            Response.End();

        }

    }
}

asp.net code :

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="upload.aspx.cs" Inherits="excel_upload.upload" EnableEventValidation="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>
</head>
<body>
    <form id="Form1" method="post" enctype="multipart/form-data" runat="server">
<input type="file" id="File1" name="File1" runat="server" />
<br/>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="upload" />
    <asp:Button ID="btnimport" runat="server" onclick="btnimport_Click"
        Text="Import" />
        <asp:GridView ID="grvExcelData" runat="server">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
<asp:Button ID="btnexport" runat="server" Text="Export to Excel"
        onclick="btnexport_Click" />
</form>
</body>
</html>

create one folder with name Data in project.

reference :