Wednesday 19 June 2019

Get the attachments from CRM 4.0 Onpremise Using Console

Today I have tried with getting all the attachments present inside CRM system through console application. So below is the code I used :

Before run this code create a folder where you want to keep the attachments files, An ex : D:\\attachments

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Query;
using System.IO;
using System.Web.Services.Protocols;

namespace ConsoleApplication1
{
    class Program
    {
        // private Guid _annotationId;
        //   private String _fileName;

        static void Main(string[] args)
        {

            CrmAuthenticationToken token = new CrmAuthenticationToken();
            token.AuthenticationType = 0;
            token.OrganizationName = "OrgName";
            CrmService service = new CrmService();
            service.Url = "http://<servername:port>/MSCRMServices/2007/CrmService.asmx";
            service.CrmAuthenticationTokenValue = token;
            service.Credentials = System.Net.CredentialCache.DefaultCredentials;
            Console.WriteLine("Connected to CRM......");
            Console.ReadLine();
            try
            {
                BusinessEntityCollection notes = new BusinessEntityCollection();
                //ICrmService service = context.CreateCrmService(true);
             //   if (context.MessageName == _DELETE)
            //    {
              //      entity = context.PreEntityImages["AnnotationDeleteImage"] as DynamicEntity;
           //     }
               // Lookup objLookup = new Lookup();
             //   objLookup = entity.Properties["objectid"] as Lookup;
             //   EntityNameReference enr = new EntityNameReference();
              //  enr = entity.Properties["objecttypecode"] as EntityNameReference;
                ColumnSet cols = new ColumnSet();
                cols.Attributes.Add("isdocument");
                cols.Attributes.Add("filename");
                cols.Attributes.Add("documentbody");
             //   ConditionExpression caseCondition = new ConditionExpression();
                //caseCondition.AttributeName = "objectid";
                //caseCondition.Operator = ConditionOperator.Equal;
                //caseCondition.Values = new object[] { objLookup.Value };
                // Build a search filter based on the above conditions.
                //FilterExpression filter = new FilterExpression();
                //filter.FilterOperator = LogicalOperator.And;
                //filter.Conditions.Add(caseCondition);
                QueryExpression query = new QueryExpression();
                query.EntityName = EntityName.annotation.ToString();
                query.ColumnSet = cols;
               // query.Criteria = filter;
                // Create the Web service request object.
                RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
                retrieve.Query = query;
                RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse)service.Execute(retrieve);
                notes = retrieved.BusinessEntityCollection;
                bool HasAttachment = false;
                if (notes.BusinessEntities.Count > 0)
                {
                    foreach (annotation item in notes.BusinessEntities)
                    {
                        if (item.isdocument.Value)
                        {
                            HasAttachment = true;
                            // Download the attachment in the current execution folder.
                            using (FileStream fileStream = new FileStream("D:\\attachments\\" + item.filename, FileMode.Append))
                            {
                                byte[] fileContent = Convert.FromBase64String(item.documentbody);
                                fileStream.Write(fileContent, 0, fileContent.Length);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

      //  public static string _AnnotationAttachmentPath { get; set; }
    }
}


Note : The above code will work only where the crm has been installed means for Active directory users.So this one worked for my local crm need to check for dev crm currently am getting issue with 
The request failed with HTTP status 401: Unauthorized. Need to check for this to make it work.

Hope the above one will help someone...Enjoyyy

No comments:

Post a Comment