Saturday, December 8, 2012

Sample code to execute stored procedure from C# (ADO.NET)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace ConsoleApplication2
    {
    class Program
        {
        static void Main(string[] args)
            {
            SqlDataReader rdr = null;
            var connectionString = @"server=myServer;database=myDatabase;uid=sa;pwd=mypassword";
            using (var conn = new SqlConnection(connectionString))
            using (var command = new SqlCommand("RetrieveSupplier", conn)
            {
                CommandType = CommandType.StoredProcedure

            })
      
                {
                command.Parameters.Add(new SqlParameter("@Supid",  4));
                conn.Open();
                rdr= command.ExecuteReader();
               
                while (rdr.Read())
                    {
                    Console.WriteLine(
                        "Name is {0}",
                        rdr["SupplierName"]
                );
                    }
                conn.Close();
                }
          
            Console.ReadKey();
            }
        }
    }

Friday, November 30, 2012

CRM 2011-Steps to migrate data using scribe insight

1.disable uac
2.install scribe
3.give "Full control" to access the folder and registry.
4.add the user to "scribe user console" group
5.Activate scribe insight .
6.create dts file using scribe workbench7.in scribe console,create the new collaboration and add the dts file with integration process

Wednesday, November 28, 2012

CRM 2011- Send SSRS reports via email & sample code to convert (render) report as pdf attachment

// <copyright file="RenderReport.cs" company="Microsoft">
// Copyright (c) 2012 All Rights Reserved
// </copyright>
// <author>Microsoft</author>
// <date>11/7/2012 10:53:22 AM</date>
// <summary>Implements the RenderReport Workflow Activity.</summary>
namespace.Workflow
    {
    using System;
    using System.Activities;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Workflow;
  
    using Xrm;

  public class RenderReport : CodeActivity
        {
        /// <summary>
        /// Executes the workflow activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        protected override void Execute(CodeActivityContext executionContext)
            {
            // Create the tracing service
            ITracingService tracingService = executionContext.GetExtension<ITracingService>();

            if (tracingService == null)
                {
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
                }

            tracingService.Trace("Entered RenderReport.Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                executionContext.ActivityInstanceId,
                executionContext.WorkflowInstanceId);

            // Create the context
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();

            if (context == null)
                {
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
                }

            tracingService.Trace("RenderReport.Execute(), Correlation Id: {0}, Initiating User: {1}",
                context.CorrelationId,
                context.InitiatingUserId);

            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            try
                {
                tracingService.Trace("1. Set up a report renderer");

                //string userName = @"xxx";
                //string password = "yyy";
                //string domain = "zzz";
                //tracingService.Trace("   username = {0}", userName);
                //tracingService.Trace("   password = {0}", password);
                //tracingService.Trace("   domain = {0}", domain);
                ReportRenderer renderer = new ReportRenderer(service, context.OrganizationName, this.ReportServer.Get<string>(executionContext), this.Username.Get<string>(executionContext), this.Password.Get<string>(executionContext), this.DomainName.Get<string>(executionContext));

                //ReportRenderer renderer = new ReportRenderer(service, workflowContext.OrganizationName, userName, password, domain);
                // 2. Render the report to a byte array
                tracingService.Trace("2. Render the report to a byte array");

                string reportName = this.ReportName.Get<string>(executionContext);
                tracingService.Trace("   reportName = {0}", reportName);
                Guid TransactionId = this.Transaction.Get<EntityReference>(executionContext).Id;
                //tracingService.Trace("   renewalId = {0}", renewalId.ToString());
                string mimeType;

                byte[] reportData = renderer.Render(reportName, new ReportParameter[]
            {
                new ReportParameter("TransactionId",TransactionId.ToString())
            }, out mimeType);
                //string reportData = renderer.TurnToPdf(reportName, "PDF");
                //tracingService.Trace("   report contains {0} bytes", reportData.Length);
                //tracingService.Trace("   mimeType = {0}", mimeType);

                // 3. Create an annotation
                tracingService.Trace("3. Create an annotation");

                string subject = this.Subject.Get<string>(executionContext);
                tracingService.Trace("   subject = {0}", subject);
                string fileName = this.FileName.Get<string>(executionContext);
                tracingService.Trace("   fileName = {0}", fileName);
                //var xy = new jmh_guntransaction();
                ////xy.jmh_guntransactionId
                var annotation = new Annotation();

                annotation.Subject = subject;
                annotation.ObjectId = new EntityReference(context.PrimaryEntityName, context.PrimaryEntityId);
                annotation.ObjectTypeCode = context.PrimaryEntityName;
                annotation.FileName = fileName;
                //annotation.FileSize = CrmTypes
                annotation.DocumentBody = Convert.ToBase64String(reportData);
                //annotation.DocumentBody = reportData;
                annotation.MimeType = @"application/pdf";
                //annotation.MimeType = "text/plain";
                //annotation.MimeType = @"application\ms-word";

                Guid annotationId = service.Create(annotation);
                tracingService.Trace("   annotationId = {0}", annotationId.ToString());

                // 4. Attach to email
                tracingService.Trace("4. Create attachment for email");

                //EntityReference emailReference = this.Email.Get<EntityReference>(executionContext);
                //if (emailReference != null)
                //    {
                //    tracingService.Trace("   emailId = {0}", emailReference.Id);

                //    Entity attachment = new Entity(EntityNames.ActivityMimeAttachment);
                //    attachment[ActivityMimeAttachmentAttributes.Subject] = subject;
                //    attachment[ActivityMimeAttachmentAttributes.ObjectId] = emailReference;
                //    attachment[ActivityMimeAttachmentAttributes.ObjectTypeCode] = service.GetEntityTypeCode(EntityNames.Email);
                //    attachment[ActivityMimeAttachmentAttributes.FileName] = fileName;
                //    attachment[ActivityMimeAttachmentAttributes.Body] = Convert.ToBase64String(reportData);
                //    attachment[ActivityMimeAttachmentAttributes.FileSize] = reportData.Length;
                //    attachment[ActivityMimeAttachmentAttributes.MimeType] = mimeType;
                //    attachment[ActivityMimeAttachmentAttributes.AttachmentNumber] = 0;

                //    Guid attachmentId = service.Create(attachment);
                //    tracingService.Trace("   attachmentId = {0}", attachmentId.ToString());
                //    }
                //else
                //    {
                //    tracingService.Trace("   no email specified");
                //    }

                // TODO: Implement your custom Workflow business logic.

                EntityReference emailReference = this.Email.Get<EntityReference>(executionContext);
                //Email em = new Email();
                if (emailReference != null)
                    {
                    tracingService.Trace("   emailId = {0}", emailReference.Id);


                    ActivityMimeAttachment attachment = new ActivityMimeAttachment();

                    attachment.Subject = subject;
                    attachment.ObjectId = emailReference;
                    attachment.ObjectTypeCode = emailReference.LogicalName;
                    attachment.FileName = fileName;
                    attachment.Body = Convert.ToBase64String(reportData);

                    attachment.MimeType = mimeType;
                    attachment.AttachmentNumber = 0;

                    Guid attachmentId = service.Create(attachment);
                    tracingService.Trace("   attachmentId = {0}", attachmentId.ToString());
                    }
                else
                    {
                    tracingService.Trace("   no email specified");
                    }
                SendEmailRequest sendrequest = new SendEmailRequest();
                sendrequest.EmailId = emailReference.Id;
                sendrequest.TrackingToken = "";
                sendrequest.IssueSend = true;

                service.Execute(sendrequest);
                // TODO: Implement your custom Workflow business logic.
                }
            catch (FaultException<OrganizationServiceFault> e)
                {
                tracingService.Trace("Exception: {0}", e.ToString());

                // Handle the exception.
                throw;
                }

            tracingService.Trace("Exiting RenderReport.Execute(), Correlation Id: {0}", context.CorrelationId);
            }

        [Input("Purchase order")]
        [ReferenceTarget("salesorder")]
        [RequiredArgument]
        public InArgument<EntityReference> Transaction { get; set; }

        [Input("Report name")]
        [RequiredArgument]
        public InArgument<string> ReportName { get; set; }


        [Input("Subject")]
        [RequiredArgument]
        public InArgument<string> Subject { get; set; }

        [Input("File name")]
        [RequiredArgument]
        public InArgument<string> FileName { get; set; }


        [Input("Report Server")]
        [RequiredArgument]
        public InArgument<string> ReportServer { get; set; }

        [Input("Email")]
        [ReferenceTarget("email")]
        [RequiredArgument]
        public InArgument<EntityReference> Email { get; set; }

        [Input("User name")]
        [RequiredArgument]
        public InArgument<string> Username { get; set; }

        [Input("Password")]
        [RequiredArgument]
        public InArgument<string> Password { get; set; }

        [Input("Domain Name")]
        [RequiredArgument]
        public InArgument<string> DomainName { get; set; }
        }
       
    }
using System;

using System.IO;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text;

using Microsoft.Xrm.Sdk;
using Microsoft.Crm.Sdk.Messages;
using .ReportExecutionService;
namespace Workflow
    {
    public class ReportRenderer
        {

        //public ReportRenderer(IOrganizationService service, string organisationName, string userName, string password, string domain)
        public ReportRenderer(IOrganizationService service, string organisationName, string ReportServer, string userName, string passWord, string domainName)
            {
         
            this.ReportBasePath = string.Format("/{0}_MSCRM/", organisationName);
        
            this.ReportServerUrl = ReportServer;
            _reportService = new ReportExecutionService.ReportExecutionService();
            _reportService.Url = string.Format("{0}/ReportExecution2005.asmx", this.ReportServerUrl);
            //_reportService.Credentials = new System.Net.NetworkCredential(userName, password, domain); // System.Net.CredentialCache.DefaultCredentials;
            //_reportService.Credentials = System.Net.CredentialCache.DefaultCredentials;
            _reportService.Credentials = new System.Net.NetworkCredential(userName, passWord, domainName);
            }

        private ReportExecutionService.ReportExecutionService _reportService;

        public string ReportBasePath { get; private set; }
        public string ReportServerUrl { get; private set; }
  
        public void RenderToStream(string reportName, ReportParameter[] parameters, out string mimeType, Stream stream)
            {
            byte[] data = this.Render(reportName, parameters, out mimeType);
            stream.Write(data, 0, data.Length);
            }

        public byte[] Render(string reportName, ReportParameter[] parameters, out string mimeType)
            {
            try
                {
                string reportPath = this.ReportBasePath + reportName;

                ExecutionInfo execInfo = new ExecutionInfo();
                ExecutionHeader execHeader = new ExecutionHeader();
                _reportService.ExecutionHeaderValue = execHeader;
                _reportService.Timeout = 9999999;
                execInfo = _reportService.LoadReport(reportPath, null);

                ReportExecutionService.ParameterValue[] reportParameters =
                    parameters.Select(p => new ReportExecutionService.ParameterValue()
                    {
                        Name = p.Name,
                        Label = p.Label,
                        Value = p.Value
                    }).ToArray<ReportExecutionService.ParameterValue>();
                //ReportExecutionService.ParameterValue[] reportParameters =new

                //ParameterValue[] parameters1 = new ParameterValue[1];
                //parameters1[0] = new ParameterValue();
                //parameters1[0].Name = "TransactionId";
                //parameters1[0].Value = "E1E3C748-7D1E-E211-9093-00155D000B45";

                //_reportService.SetExecutionParameters(reportParameters, "en-gb");
                //String SessionId = _reportService.ExecutionHeaderValue.ExecutionID;

                string extension = string.Empty;
                string encoding = string.Empty;
                string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
                ReportExecutionService.Warning[] warnings = null;
                string[] streamIds = null;


                byte[] data = null;

                data = _reportService.Render("PDF", devInfo, out extension, out encoding, out mimeType, out warnings, out streamIds);
                mimeType = mimeType ?? "application/pdf";
                return data;
                }
            catch (FaultException<OrganizationServiceFault> e)
                {
                //tracingService.Trace("Exception: {0}", e.ToString());

                // Handle the exception.
                throw new InvalidPluginExecutionException("Exception in renderreport: {0}" + e.Message);
                }

            }

        public string TurnToPdf(string reportName, string i_Format)
            {
            // Render arguments
            string encoded = "";
            try
                {
                ReportExecutionService.ReportExecutionService rs = new ReportExecutionService.ReportExecutionService();
                rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
                //rs.Credentials=  new System.Net.NetworkCredential("crmserver", "ntier@123", "ntier");

                byte[] result = null;
                string reportPath = this.ReportBasePath + reportName;
                string format = i_Format;
                string historyID = null;
                string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";

                //DataSourceCredentials[] credentials = null;
                //string showHideToggle = null;
                string encoding;
                string mimeType;
                string extension;
                Warning[] warnings = null;
                //ParameterValue[] reportHistoryParameters = null;
                string[] streamIDs = null;

                ExecutionInfo execInfo = new ExecutionInfo();
                ExecutionHeader execHeader = new ExecutionHeader();

                rs.ExecutionHeaderValue = execHeader;
                rs.Timeout = 9999999;
                execInfo = rs.LoadReport(reportPath, historyID);


                //ReportExecutionService.ParameterValue[] reportParameters =
                //    parameters.Select(p => new ReportExecutionService.ParameterValue()
                //    {
                //        Name = p.Name,
                //        Label = p.Label,
                //        Value = p.Value
                //    }).ToArray<ReportExecutionService.ParameterValue>();

                //_reportService.SetExecutionParameters(parameters1, "en-gb");
                //rs.SetExecutionParameters(parameters, "en-us");
                String SessionId = rs.ExecutionHeaderValue.ExecutionID;

                Console.WriteLine("SessionID: {0}", rs.ExecutionHeaderValue.ExecutionID);



                result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
                execInfo = rs.GetExecutionInfo();
                //FileStream st = System.IO.File.Create("d:\\test.pdf");
                //st.Write(result, 0, result.Length);
                //st.Close();
                encoded = System.Convert.ToBase64String(result);
                //encoded = "JVBERi0xLjMNCjEgMCBvYmoNClsvUERGIC9UZXh0IC9JbWFnZUIgL0ltYWdlQyAvSW1hZ2VJXQ0KZW5kb2JqDQozIDAgb2JqDQo8PCAvTGVuZ3RoIDM5IC9GaWx0ZXIgL0ZsYXRlRGVjb2RlID4+IHN0cmVhbQ0KeJzj5SpUMDfSMwASCiZmFkCGmQmILEpVCFfI4+UK5CWkAACtvw05DQplbmRzdHJlYW0NCmVuZG9iag0KMiAwIG9iag0KPDwgL1R5cGUgL1BhZ2UgL1BhcmVudCA0IDAgUiAvTWVkaWFCb3ggWzAgMCA2MTIuMCA3OTIuMF0gL0NvbnRlbnRzIDMgMCBSIC9SZXNvdXJjZXMgPDwgL1Byb2NTZXQgMSAwIFIgL1hPYmplY3QgPDwgPj4gL0ZvbnQgPDwgPj4gPj4gPj4NCmVuZG9iag0KNCAwIG9iag0KPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFsgMiAwIFIgXSAvQ291bnQgMSA+Pg0KZW5kb2JqDQo1IDAgb2JqDQo8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgNCAwIFIgPj4NCmVuZG9iag0KNiAwIG9iag0KPDwgL1RpdGxlIDxmZWZmMDA0MzAwNzUwMDczMDA3NDAwNmYwMDZkMDA2NTAwNzIwMDUyMDA2NTAwNzAwMDZmMDA3MjAwNzQ+DQovQXV0aG9yIDw+DQovU3ViamVjdCA8Pg0KL0NyZWF0b3IgKE1pY3Jvc29mdCBSZXBvcnRpbmcgU2VydmljZXMgMTAuMC4wLjApDQovUHJvZHVjZXIgKE1pY3Jvc29mdCBSZXBvcnRpbmcgU2VydmljZXMgUERGIFJlbmRlcmluZyBFeHRlbnNpb24gMTAuMC4wLjApDQovQ3JlYXRpb25EYXRlIChEOjIwMTIxMTE1MTIzODQ0KzA1JzMwJykNCj4+DQplbmRvYmoNCnhyZWYNCjAgNw0KMDAwMDAwMDAwMCA2NTUzNSBmDQowMDAwMDAwMDEwIDAwMDAwIG4NCjAwMDAwMDAxODAgMDAwMDAgbg0KMDAwMDAwMDA2NSAwMDAwMCBuDQowMDAwMDAwMzMzIDAwMDAwIG4NCjAwMDAwMDAzOTUgMDAwMDAgbg0KMDAwMDAwMDQ0NyAwMDAwMCBuDQp0cmFpbGVyIDw8IC9TaXplIDcgL1Jvb3QgNSAwIFIgL0luZm8gNiAwIFIgPj4NCnN0YXJ0eHJlZg0KNzMzDQolJUVPRg==";
                Console.WriteLine("Execution date and time: {0}", execInfo.ExecutionDateTime);

                }
            //catch (SoapException e)
            //{
            //    Console.WriteLine(e.Detail.OuterXml);
            //    encoded = "";
            //}
            catch (FaultException<OrganizationServiceFault> e)
                {


                // Handle the exception.
                throw new InvalidPluginExecutionException("Exception in trun to pdf: {0}" + e.Message);
                }


            return encoded;

            }

        }


    public class ReportParameter
        {
        public ReportParameter(string name, string label, string value)
            {
            this.Name = name;
            this.Label = label;
            this.Value = value;
            }

        public ReportParameter(string name, string value)
            : this(name, name, value)
        { }

        public string Name { get; set; }
        public string Label { get; set; }
        public string Value { get; set; }
        }
    }
 reference:
http://ekoncis.blogspot.in/2012/01/crm-2011-custom-email-with-pdf-report.html
note:
1.SSRS report has to be deployed in report server before you run the workflow


2.create a workflow in which create a email record and pass the id to the workflow activity as it is in
http://www.stefan-scheller.com/2012/04/crm-2011-send-email-including-lines-of-document-pdf-attachment-walkthrough/

2.To add reference report execution service,right click the project->add service reference->advanced->add web reference-> http://<report server>/reportserver/reportexecution2005.asmx















CRM 2011-SSIS (helper class to connect with CRM)

Steps to integrating CRM 2011 using SSIS..click the following link and use the following code to suuport .NET 3.5 project

SSIS 2008 for CRM 2011
 http://a33ik.blogspot.in/2012/02/integrating-crm-2011-using-sql.html

SSIS  2012 for CRM 2011
http://a33ik.blogspot.com/2012/11/integrating-crm-2011-using-sql.html

SSIS for CRM 2013
http://microsoft-ssis.blogspot.com/2014/01/insert-update-and-delete-records-in-crm.html

Connecting to Dynamics CRM 2011 Online (365) from SSIS 2008
http://www.it-gems.com/2013/02/connecting-to-crm-2011-online-365-from.html

http://www.it-gems.com/2013/09/howtocrm2011ssis200801.html


SSIS vs Windows Service:
http://stackoverflow.com/questions/3698618/advantage-of-ssis-package-over-windows-scheduled-exe


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CrmProxy.Crm;
using System.ServiceModel.Channels;
using System.ServiceModel.Security.Tokens;
using System.ServiceModel;
using System.Net;
using System.ServiceModel.Security;

namespace CrmProxy
    {
    [System.Runtime.Serialization.KnownTypeAttribute(typeof(EntityReference))]
    [System.Runtime.Serialization.KnownTypeAttribute(typeof(OptionSetValue))]
    [System.Runtime.Serialization.KnownTypeAttribute(typeof(Money))]
    public class CrmHelper
        {
      
        public static IOrganizationService getservice(string url)
            {
            Uri orgURL = new Uri(url);
            SymmetricSecurityBindingElement security = SecurityBindingElement.CreateSspiNegotiationBindingElement();
            security.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Default;
            security.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
            security.IncludeTimestamp = true;
            security.KeyEntropyMode = SecurityKeyEntropyMode.CombinedEntropy;
            security.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature;
            security.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
            security.LocalClientSettings.CacheCookies = true;
            security.LocalClientSettings.DetectReplays = true;
            security.LocalClientSettings.ReplayCacheSize = 900000;
            security.LocalClientSettings.MaxClockSkew = new TimeSpan(0, 5, 0);
            security.LocalClientSettings.MaxCookieCachingTime = new TimeSpan(23, 0, 0, 0);
            security.LocalClientSettings.ReplayWindow = new TimeSpan(0, 5, 0);
            security.LocalClientSettings.SessionKeyRenewalInterval = new TimeSpan(15, 0, 0);
            security.LocalClientSettings.SessionKeyRolloverInterval = new TimeSpan(0, 5, 0);
            security.LocalClientSettings.ReconnectTransportOnFailure = true;
            security.LocalClientSettings.TimestampValidityDuration = new TimeSpan(0, 5, 0);
            security.LocalClientSettings.CookieRenewalThresholdPercentage = 60;
            security.LocalServiceSettings.DetectReplays = true;
            security.LocalServiceSettings.IssuedCookieLifetime = new TimeSpan(10, 0, 0);
            security.LocalServiceSettings.MaxStatefulNegotiations = 128;
            security.LocalServiceSettings.ReplayCacheSize = 900000;
            security.LocalServiceSettings.MaxClockSkew = new TimeSpan(0, 5, 0);
            security.LocalServiceSettings.NegotiationTimeout = new TimeSpan(0, 1, 0);
            security.LocalServiceSettings.ReplayWindow = new TimeSpan(0, 5, 0);
            security.LocalServiceSettings.InactivityTimeout = new TimeSpan(0, 2, 0);
            security.LocalServiceSettings.SessionKeyRenewalInterval = new TimeSpan(15, 0, 0);
            security.LocalServiceSettings.SessionKeyRolloverInterval = new TimeSpan(0, 5, 0);
            security.LocalServiceSettings.ReconnectTransportOnFailure = true;
            security.LocalServiceSettings.MaxPendingSessions = 128;
            security.LocalServiceSettings.MaxCachedCookies = 1000;
            security.LocalServiceSettings.TimestampValidityDuration = new TimeSpan(0, 5, 0);

            TextMessageEncodingBindingElement textEncoding = new TextMessageEncodingBindingElement();
            textEncoding.MaxReadPoolSize = 64;
            textEncoding.MaxWritePoolSize = 16;
            textEncoding.MessageVersion = MessageVersion.Default;
            textEncoding.WriteEncoding = System.Text.Encoding.UTF8;



            HttpTransportBindingElement httpTransport = new HttpTransportBindingElement();
            httpTransport.ManualAddressing = false;
            httpTransport.MaxBufferSize = 65536;
            httpTransport.MaxReceivedMessageSize = 65536;
            httpTransport.AllowCookies = false;
            httpTransport.AuthenticationScheme = AuthenticationSchemes.Anonymous;
            httpTransport.BypassProxyOnLocal = false;
            httpTransport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
            httpTransport.KeepAliveEnabled = true;
            httpTransport.MaxBufferPoolSize = 524288;
            httpTransport.ProxyAuthenticationScheme = AuthenticationSchemes.Anonymous;
            httpTransport.TransferMode = TransferMode.Buffered;
            httpTransport.UnsafeConnectionNtlmAuthentication = false;
            httpTransport.UseDefaultWebProxy = true;


            CustomBinding binding = new CustomBinding(new List<BindingElement> { security, textEncoding, httpTransport });
            EndpointAddress endpoint = new EndpointAddress(orgURL);

            OrganizationServiceClient client = new OrganizationServiceClient(binding, endpoint);





            IOrganizationService _orgservice = (IOrganizationService)client;
            return _orgservice;
            }
        }
    }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CrmProxy.Crm
    {
     [System.Runtime.Serialization.KnownTypeAttribute(typeof(EntityReference))]
     [System.Runtime.Serialization.KnownTypeAttribute(typeof(OptionSetValue))]
     [System.Runtime.Serialization.KnownTypeAttribute(typeof(Money))]

    partial class Entity
        {
        public Entity()
            {
            this.FormattedValuesField = new FormattedValueCollection();
            this.RelatedEntitiesField = new RelatedEntityCollection();
            }

        public T GetAttributeValue<T>(string attributeLogicalName)
            {
            if (null == this.Attributes) { this.Attributes = new AttributeCollection(); };

            object value;
            if (this.Attributes.TryGetValue(attributeLogicalName, out value))
                {
                return (T)value;
                }

            return default(T);
            }

        public object this[string attributeName]
            {
            get
                {
                if (null == this.Attributes) { this.Attributes = new AttributeCollection(); };
                return this.Attributes.GetItem(attributeName);
                }

            set
                {
                if (null == this.Attributes) { this.Attributes = new AttributeCollection(); };
                this.Attributes.SetItem(attributeName, value);
                }
            }
        }

    public static class CollectionExtensions
        {
        public static TValue GetItem<TKey, TValue>(this IList<KeyValuePair<TKey, TValue>> collection, TKey key)
            {
            TValue value;
            if (TryGetValue(collection, key, out value))
                {
                return value;
                }

            throw new System.Collections.Generic.KeyNotFoundException("Key = " + key);
            }

        public static void SetItem<TKey, TValue>(this IList<KeyValuePair<TKey, TValue>> collection, TKey key, TValue value)
            {
            int index;
            if (TryGetIndex<TKey, TValue>(collection, key, out index))
                {
                collection.RemoveAt(index);
                }

            //If the value is an array, it needs to be converted into a List. This is due to how Silverlight serializes
            //Arrays and IList<T> objects (they are both serialized with the same namespace). Any collection objects will
            //already add the KnownType for IList<T>, which means that any parameters that are arrays cannot be added
            //as a KnownType (or it will throw an exception).
            Array array = value as Array;
            if (null != array)
                {
                Type listType = typeof(List<>).GetGenericTypeDefinition().MakeGenericType(array.GetType().GetElementType());
                object list = Activator.CreateInstance(listType, array);
                try
                    {
                    value = (TValue)list;
                    }
                catch (InvalidCastException)
                    {
                    //Don't do the conversion because the types are not compatible
                    }
                }

            collection.Add(new KeyValuePair<TKey, TValue>(key, value));
            }

        public static bool ContainsKey<TKey, TValue>(this IList<KeyValuePair<TKey, TValue>> collection, TKey key)
            {
            int index;
            return TryGetIndex<TKey, TValue>(collection, key, out index);
            }

        public static bool TryGetValue<TKey, TValue>(this IList<KeyValuePair<TKey, TValue>> collection, TKey key, out TValue value)
            {
            int index;
            if (TryGetIndex<TKey, TValue>(collection, key, out index))
                {
                value = collection[index].Value;
                return true;
                }

            value = default(TValue);
            return false;
            }

        private static bool TryGetIndex<TKey, TValue>(IList<KeyValuePair<TKey, TValue>> collection, TKey key, out int index)
            {
            if (null == collection || null == key)
                {
                index = -1;
                return false;
                }

            index = -1;
            for (int i = 0; i < collection.Count; i++)
                {
                if (key.Equals(collection[i].Key))
                    {
                    index = i;
                    return true;
                    }
                }

            return false;
            }
        }

    }

Thursday, November 1, 2012

CRM 2011 -sample HTML web resource to get value from CRM

<!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>
    <title>Test Page </title>
    <script type="text/javascript">
        var Xrm;
        if (window.opener) { Xrm = window.opener.Xrm; }
        else if (window.parent) { Xrm = window.parent.Xrm; }

        onload = function () {
            var myOptionSet = Xrm.Page.data.entity.attributes.get("jmh_flag");
            // var optionSetValue = myOptionSet.getValue();
            var optionSetText = myOptionSet.getText();
            document.bgColor = optionSetText;
            //alert(optionSetValue + " " + optionSetText);
        }

</script>
</head>
<body>

</body>
</html>

CRM 2011-Set state and status reason by javascript

// JScript source code
SetStateRequest = function (_entName,_entId,_state, _status) {
    var requestMain = ""
    requestMain += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
    requestMain += "  <s:Body>";
    requestMain += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
    requestMain += "      <request i:type=\"b:SetStateRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
    requestMain += "        <a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>EntityMoniker</c:key>";
    requestMain += "            <c:value i:type=\"a:EntityReference\">";
    requestMain += "              <a:Id>" + _entId + "</a:Id>";
    requestMain += "              <a:LogicalName>" + _entName + "</a:LogicalName>";
    requestMain += "              <a:Name i:nil=\"true\" />";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>State</c:key>";
    requestMain += "            <c:value i:type=\"a:OptionSetValue\">";
    requestMain += "              <a:Value>" + _state + "</a:Value>";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>Status</c:key>";
    requestMain += "            <c:value i:type=\"a:OptionSetValue\">";
    requestMain += "              <a:Value>" + _status + "</a:Value>";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "        </a:Parameters>";
    requestMain += "        <a:RequestId i:nil=\"true\" />";
    requestMain += "        <a:RequestName>SetState</a:RequestName>";
    requestMain += "      </request>";
    requestMain += "    </Execute>";
    requestMain += "  </s:Body>";
    requestMain += "</s:Envelope>";
    var req = new XMLHttpRequest();
    req.open("POST", _getServerUrl(), false)
    // Responses will return XML. It isn't possible to return JSON.
    req.setRequestHeader("Accept", "application/xml, text/xml, */*");
    req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
    var successCallback = null;
    var errorCallback = null;
    req.onreadystatechange = function () { SetStateResponse(req, successCallback, errorCallback); };
    req.send(requestMain);
}

SetStateResponse = function (req, successCallback, errorCallback) {
    if (req.readyState == 4) {
        if (req.status == 200) {
            if (successCallback != null)
            { successCallback(); }
        }
        else {
            errorCallback(SDK.SAMPLES._getError(req.responseXML));
        }
    }
}


_getServerUrl = function () {
    var OrgServicePath = "/XRMServices/2011/Organization.svc/web";
    var serverUrl = "";
    if (typeof GetGlobalContext == "function") {
        var context = GetGlobalContext();
        serverUrl = context.getServerUrl();
    }
    else {
        if (typeof Xrm.Page.context == "object") {
            serverUrl = Xrm.Page.context.getServerUrl();
        }
        else
        { throw new Error("Unable to access the server URL"); }
    }
    if (serverUrl.match(/\/$/)) {
        serverUrl = serverUrl.substring(0, serverUrl.length - 1);
    }
    return serverUrl + OrgServicePath;
}

_getError = function (faultXml) {
    var errorMessage = "Unknown Error (Unable to parse the fault)";
    if (typeof faultXml == "object") {
        try {
            var bodyNode = faultXml.firstChild.firstChild;
            //Retrieve the fault node
            for (var i = 0; i < bodyNode.childNodes.length; i++) {
                var node = bodyNode.childNodes[i];
                if ("s:Fault" == node.nodeName) {
                    for (var j = 0; j < node.childNodes.length; j++) {
                        var faultStringNode = node.childNodes[j];
                        if ("faultstring" == faultStringNode.nodeName) {
                            errorMessage = faultStringNode.text;
                            break;
                        }
                    }
                    break;
                }
            }
        }
        catch (e) { };
    }
    return new Error(errorMessage);
}
function ChangeStatus(entName, entId) {
    SetStateRequest(entName, entId, 1, 3);
    alert("quote is submitted succesfully for approval");
    window.location.reload(true);
}note : you can use like this
  SetStateRequest(1, 2);//1-is value of ' inactive' state,2-is value of 'completed' status in inactive

Reference:
http://sumedha8.blogspot.in/2011/11/state-statecode-and-statuscode-change.html

Tuesday, October 9, 2012

CRM 2011-Trigger a workflow process from cutom ribbon button using javascript

1.Create a new  web resource (javascipt) with following code

function TriggerWorkflow(workflowGuid) {


  /*Generate Soap Body.*/
  var soapBody = "<soap:Body>" +
                 "  <Execute xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
                 "    <Request xsi:type=\'ExecuteWorkflowRequest\'>" +
                 "      <EntityId>" + Xrm.Page.data.entity.getId() + "</EntityId>" +
                 "      <WorkflowId>" + workflowGuid + "</WorkflowId>" +
                 "    </Request>" +
                 "  </Execute>" +
                 "</soap:Body>";

  /*Wrap the Soap Body in a soap:Envelope.*/
  var soapXml = "<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'>" +
                GenerateAuthenticationHeader() +
                soapBody +
                "</soap:Envelope>";

  /* Create the XMLHTTP object for the execute method.*/
  var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  xmlhttp.open("POST", "/MSCRMservices/2007/crmservice.asmx", false);
  xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
  xmlhttp.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Execute");

  /* Send the XMLHTTP object. */
  xmlhttp.send(soapXml);
alert("The workflow has been triggered successfully");

}

2.Create the workflow process
3.Create a new button using visual ribbon editor and pass parameter  as follows
 
 
Function Name:TriggerWorkflow
Library: $webresource:<created web resource name>
String parameter Value: < Id of workflow process to be launched>
Reference: