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.


No comments:

Post a Comment