Monday, April 11, 2011

Attach and Retrieve files and notes/annotations

---------------------------------ASPX------------------------------------

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="CaseNotes.aspx.cs" Inherits="_Default" %>

<!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>Case History</title>
  
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <table width="100%">
        <tr style="width:100%">
        <td style="width:90%">
                <asp:Label Text="Title" ID="lblTitle" Width="10%" runat="server" Font-Bold="true" Font-Names="Tahoma" Font-Size="Small"></asp:Label>
            </td>
            </tr>
         <tr style="width:100%">
            <td style="width:100%">
            <asp:TextBox ID="txtTitle" runat="server" TextMode="SingleLine"
                    Width="90%"  Font-Names="Tahoma"  Font-Size="Small"></asp:TextBox>
    </td>    
        </tr>
            <tr style="width:100%"><td >
                <asp:Label ID="Message" runat="server" Text="Comments" Font-Bold="true" Font-Names="Tahoma" Font-Size="Small" ></asp:Label>
            </td>
            </tr>
            <tr style="width:100%">
            <td style="width:100%">
            <asp:TextBox ID="txtNotes" runat="server" TextMode="MultiLine"
                    Height="91px" Width="90%"  Font-Names="Tahoma"  Font-Size="Small"></asp:TextBox>
    </td>    
        </tr>
        </table>
        <table width="90%">
        <tr style="width:100%">
             <td style="width:50%">
                <asp:Label ID="lblAttach" runat="server" Text="Attach a File "  Font-Bold="true"  Font-Names="Tahoma" Font-Size="Small"
                    ></asp:Label>
              <asp:FileUpload ID="FileUpload1" runat="server"  Font-Names="Tahoma" Font-Size="Small"/>
</td><td style="width:50%" align="right">
      <asp:Button ID="btnAddNotes" runat="server" Text="Add Case Notes"
            onclick="btnAddNotes_Click" Font-Bold="true"  Font-Names="Tahoma" Font-Size="Small"/>
        </td>
        </tr>
        </table>

       <%-- <asp:TextBox ID="txtHistory" runat="server" Height="299px" Width="777px" TextMode="MultiLine" Visible="false"></asp:TextBox>
        <asp:Panel ID="pnlHistory" runat="server" Height="299px" Width="777px" Direction="LeftToRight" HorizontalAlign="Justify" Visible="false">
        <asp:Table ID="tblhistory" runat="server" Width="100%" HorizontalAlign="Left">
        </asp:Table>
        </asp:Panel>--%>
        <asp:GridView ID="gvNotes" runat="server" onrowdatabound="gvNotes_RowDataBound"
            CellPadding="4" ForeColor="#333333"
            GridLines="None" AutoGenerateColumns="False" Width="100%"
            ShowHeader="False" Font-Names="Tahoma" Font-Size="Small" EnableViewState="true">
            <RowStyle BorderColor="White" BorderWidth="0px" BackColor="#F7F6F3"
                ForeColor="#333333" />
            <Columns>
                <asp:BoundField DataField="User" HeaderText="User" />
                <asp:BoundField HeaderText="Comments" DataField="Comments" ItemStyle-VerticalAlign="Bottom" HeaderStyle-Width="90%"/>
                <asp:BoundField HeaderText="AnnotationId" DataField="AnnotationId" />
                <asp:TemplateField  ItemStyle-VerticalAlign="Bottom" HeaderStyle-Width="10%">
                    <ItemTemplate>
                        <asp:LinkButton ID="downloadBtn" runat="server" onclick="downloadBtn_Click" Text="Download" Font-Bold="true"></asp:LinkButton>
                    </ItemTemplate>
                    <HeaderStyle BackColor="White" />
                    <ItemStyle BackColor="White" />
                </asp:TemplateField>            
            </Columns>
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#999999" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        </asp:GridView>
        </div>
    </form>
</body>
</html>

------------------------------------------CODE BEHIND------------------------------------------------



using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Query;
using System.IO;
using System.Text;



public partial class _Default : System.Web.UI.Page
{
    //string caseId = string.Empty;
    string caseId = "74F4528F-FD61-E011-A0F7-001CC4A7FE9A";
    CrmService crmservice = GetCrmService(ConfigurationManager.AppSettings["CrmServerURL"].ToString(), ConfigurationManager.AppSettings["orgName"].ToString());
    DataTable notestable = new DataTable();


    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["caseId"] != null)
        {
            caseId = Request.QueryString["caseId"].ToString();
        }
      
        //notestable = new DataTable();

        notestable.Columns.Add("User");
        notestable.Columns.Add("Comments");
        notestable.Columns.Add("AnnotationId");
      
        if (!IsPostBack)
        {
            setNotes(caseId);
            BindData();
        }
        //if (!IsPostBack)
        //{
        //    BindData();
        //}

    }

    private void BindData()
    {
        gvNotes.DataSource = notestable;
        gvNotes.DataBind();
    }

    private void setNotes(string caseId)
    {
      
        RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
        retrieve.ReturnDynamicEntities = true;

        QueryExpression query = new QueryExpression();
        query.ColumnSet = new AllColumns();
        query.EntityName = EntityName.annotation.ToString();

        FilterExpression filter = new FilterExpression();
        ConditionExpression ce = new ConditionExpression();
        ce.AttributeName = "objectid";
        ce.Operator = ConditionOperator.Equal;
        ce.Values = new object[] { caseId };
        filter.Conditions.Add(ce);

        OrderExpression order = new OrderExpression();
        order.AttributeName = "createdon";
        order.OrderType = OrderType.Descending;

        query.Orders.Add(order);
        query.Criteria = filter;

        retrieve.Query = query;

        try
        {
            RetrieveMultipleResponse response = (RetrieveMultipleResponse)crmservice.Execute(retrieve);
            if (response.BusinessEntityCollection != null && response.BusinessEntityCollection.BusinessEntities.Count > 0)
            {
                //txtHistory.Text = "";


                foreach (BusinessEntity be in response.BusinessEntityCollection.BusinessEntities)
                {
                    DataRow newRow = notestable.NewRow();
                    string strStatus = string.Empty;
                    string strUser = string.Empty;
                    DynamicEntity de = (DynamicEntity)be;
                    Lookup lkpUser = ((Lookup)(de.Properties["createdby"]));
                    if (lkpUser.name.ToString().ToLower().Equals("crmadmin prd"))
                    {
                        incident newincident = getCaseDetails(caseId);
                        Customer customer = new Customer();
                        customer = newincident.customerid;
                        CrmDateTime created = (CrmDateTime)(de.Properties["createdon"]);

                        strUser = strUser + customer.name + " on " + created.date + " " + created.time + ": ";                      
                    }
                    else
                    {
                        CrmDateTime created = (CrmDateTime)(de.Properties["createdon"]);
                        strUser = strUser + lkpUser.name + " on " + created.date + " " + created.time + ": ";
                    }
                    if (de.Properties.Contains("subject"))
                    {
                        strUser = strUser + de.Properties["subject"];
                    }
                    newRow["User"] = strUser;
                    newRow["Comments"] = strUser;
                    notestable.Rows.Add(newRow);
                    DataRow newsubrow = notestable.NewRow();
                  
                    if (de.Properties.Contains("notetext"))
                    {
                        strStatus = strStatus + de.Properties["notetext"].ToString() + " \n";
                        newsubrow["AnnotationId"] = string.Empty;
                    }
                  
                        if (de.Properties.Contains("filename"))
                        {
                            strStatus = strStatus + " Uploaded Document " + de.Properties["filename"] + " \n";
                            Key annotationid = (Key)(de.Properties["annotationid"]);
                            newsubrow["AnnotationId"] = annotationid.Value.ToString();
                        }
                  
                    // txtHistory.Text += strStatus;
                        newsubrow["Comments"] = strStatus;
                    notestable.Rows.Add(newsubrow);
                }
                //gvNotes.Visible = true;
            
            }
            //else
            //{
            //    gvNotes.Visible = false;
            //}

          
        }
        catch (System.Web.Services.Protocols.SoapException ex)
        {
        }
        catch (Exception ex)
        {
        }

    }

    private incident getCaseDetails(string caseId)
    {
        incident newincident = new incident();
      
        try
        {
            newincident = (incident) crmservice.Retrieve(EntityName.incident.ToString(), new Guid(caseId), new AllColumns());
        }
        catch (System.Web.Services.Protocols.SoapException ex)
        {
        }
        catch (Exception ex)
        {
        }
        return newincident;
    }
    private annotation getAnnotationDetails(string annotationId)
    {
        annotation newannotation = new annotation();
        try
        {
            newannotation = (annotation)crmservice.Retrieve(EntityName.annotation.ToString(), new Guid(annotationId), new AllColumns());
        }
        catch (System.Web.Services.Protocols.SoapException ex)
        {
        }
        catch (Exception ex)
        {
        }
        return newannotation;
    }
    protected void btnAddNotes_Click(object sender, EventArgs e)
    {
        annotation newannotation = new annotation();
        if (!FileUpload1.HasFile)
        {
            if (txtNotes.Text == "" || txtNotes.Text == string.Empty)
            {
                ClientScript.RegisterStartupScript(typeof(Page), "NoDocAlert", "<script>alert('There are no user comments or document selected. Please enter comments or select a document for adding');</script>");
                return;
            }
            newannotation.isdocument = new CrmBoolean(false);
        }
        else
        {
            newannotation.isdocument = new CrmBoolean(true);
        }
        newannotation.notetext = txtNotes.Text;
        newannotation.subject = txtTitle.Text;
        //newannotation.subject = txtSubject.Text;
        Lookup lkpCase = new Lookup();
        lkpCase.type = EntityName.incident.ToString();
        lkpCase.Value = new Guid(caseId);
        newannotation.objectid = lkpCase;
      
            EntityNameReference reference = new EntityNameReference("incident");
            newannotation.objecttypecode = reference;

            CrmService crmservice = GetCrmService(ConfigurationManager.AppSettings["CrmServerURL"].ToString(), ConfigurationManager.AppSettings["orgName"].ToString());
            CreateRequest create = new CreateRequest();
            TargetCreateAnnotation target = new TargetCreateAnnotation();
            target.Annotation = newannotation;
            create.Target = target;
            try
            {
                CreateResponse created = (CreateResponse)crmservice.Execute(create);
                Guid createdNoteId = created.id;
                if (FileUpload1.HasFile)
                {            
                    byte[] byteData = new byte[FileUpload1.FileBytes.Length];
                    byteData = FileUpload1.FileBytes;
  
                    // Encode the data using base64.
                    string encodedData = System.Convert.ToBase64String(byteData);

                    annotation updateNote = new annotation();
                    updateNote.annotationid = new Key();
                    updateNote.annotationid.Value = createdNoteId;
                    updateNote.documentbody = encodedData;
                    updateNote.filename = FileUpload1.FileName;
                    crmservice.Update(updateNote);
                }
              
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
            }
            catch (Exception ex)
            {
            }
            clearControls();
      
    }

    private void clearControls()
    {
        txtTitle.Text = "";
        txtNotes.Text = "";
       // txtSubject.Text = "";
        notestable.Clear();
        setNotes(caseId);
        BindData();
    }

    /// <summary>
    /// Set up the CRM Service.
    /// </summary>
    /// <param name="organizationName">My Organization</param>
    /// <returns>CrmService configured with AD Authentication</returns>
    private static CrmService GetCrmService(string crmServerUrl, string organizationName)
    {
        // Get the CRM Users appointments
        // Setup the Authentication Token
        if (crmServerUrl == null || crmServerUrl == string.Empty)
        {
            crmServerUrl = ConfigurationManager.AppSettings["CrmServerURL"].ToString();
        }
        CrmService crmService = new CrmService();
        CrmAuthenticationToken token = new CrmAuthenticationToken();
        token.OrganizationName = organizationName;
        token.AuthenticationType = 0;
        if (crmServerUrl != null &&
            crmServerUrl.Length > 0)
        {
            UriBuilder builder = new UriBuilder(crmServerUrl);
            builder.Path = "//MSCRMServices//2007//CrmService.asmx";
            crmService.Url = builder.Uri.ToString();
        }

        crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
        crmService.CrmAuthenticationTokenValue = token;
        return crmService;
    }
  
    protected void downloadBtn_Click(object sender, EventArgs e)
    {
       //BindData();
        LinkButton _lnkButton = (LinkButton)sender;
        GridViewRow gvRow = (GridViewRow)((_lnkButton).Parent.Parent);
        string annotationId = gvRow.Cells[2].Text;
        annotation newannotation = getAnnotationDetails(annotationId);
      
           string[] extensions = newannotation.filename.Split('.');
           string ext = extensions[extensions.Length - 1];
          // byte[] fileContent = new UTF8Encoding(true).GetBytes(newannotation.documentbody);
           byte[] fileContent = Convert.FromBase64String(newannotation.documentbody);
                Response.ClearContent();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + newannotation.filename);
                Response.AddHeader("Content-Length", newannotation.filesize.Value.ToString());
                Response.ContentType = ReturnExtension("."+ext);
                Response.BinaryWrite(fileContent);
                Response.End();

    }
    protected void gvNotes_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        GridViewRow gvRow = (GridViewRow)e.Row;
        if (gvRow.Cells[0].Text != "&nbsp;")
        {
            gvRow.Cells[1].Style.Add(HtmlTextWriterStyle.FontWeight, "Bold");
        }
        //else
        //{
        //    gvRow.Cells[1].Text = "<p>" + gvRow.Cells[1].Text + "</p>";
        //}
        if (gvRow.Cells[2].Text == string.Empty || gvRow.Cells[2].Text == "&nbsp;")
        {
            gvRow.Cells[3].Style.Add("display", "none");
        }
        else
        {
        }
        gvRow.Cells[2].Style.Add("display", "none");
        gvRow.Cells[0].Style.Add("display", "none");
    
    }
    private string ReturnExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".htm":
            case ".html":
            case ".log":
                return "text/HTML";
            case ".txt":
                return "text/plain";
            case ".doc":
                return "application/ms-word";
            case ".tiff":
            case ".tif":
                return "image/tiff";
            case ".asf":
                return "video/x-ms-asf";
            case ".avi":
                return "video/avi";
            case ".zip":
                return "application/zip";
            case ".xls":
            case ".csv":
                return "application/vnd.ms-excel";
            case ".gif":
                return "image/gif";
            case ".jpg":
            case "jpeg":
                return "image/jpeg";
            case ".bmp":
                return "image/bmp";
            case ".wav":
                return "audio/wav";
            case ".mp3":
                return "audio/mpeg3";
            case ".mpg":
            case "mpeg":
                return "video/mpeg";
            case ".rtf":
                return "application/rtf";
            case ".asp":
                return "text/asp";
            case ".pdf":
                return "application/pdf";
            case ".fdf":
                return "application/vnd.fdf";
            case ".ppt":
                return "application/mspowerpoint";
            case ".dwg":
                return "image/vnd.dwg";
            case ".msg":
                return "application/msoutlook";
            case ".xml":
            case ".sdxl":
                return "application/xml";
            case ".xdp":
                return "application/vnd.adobe.xdp+xml";
            default:
                return "application/octet-stream";
        }
    }
}

No comments:

Post a Comment