How to retrieve all the fields of entity details in Salesforce using SOQL

Step 1: First create the salesforce API. Please refer to my my previous post.
Step 2: Pass the account ids as array.. as  GetAccountDetails(new string {“6ghgg687ihh”, “9hhj789899n”})

public List<Account> GetAccountDetails(string[] accountIds)
        {
            List<Account> objAccountList = new List<Account>();
            Account objAccount = new Account();
            String sQuery = string.Empty;
            String accountFieldNames = "";
            String contactFieldNames = "";
            DescribeSObjectResult describeSObjectResult = svc.describeSObject("Account");

            foreach (var item in describeSObjectResult.fields)
            {
                if (accountFieldNames == "")
                {
                    accountFieldNames = item.name;
                }
                else
                {
                    accountFieldNames += ',' + item.name;
                }
            }

            describeSObjectResult = svc.describeSObject("Contact");

            foreach (var item in describeSObjectResult.fields)
            {
                if (contactFieldNames == "")
                {
                    contactFieldNames = item.name;
                }
                else
                {
                    contactFieldNames += ',' + item.name;
                }
            }
            sQuery = "Select " + accountFieldNames + ", (Select " + contactFieldNames + " From Contacts) From Account where Id='" + accountIds[0] + "'";
            sObject[] sobjects = svc.query(sQuery).records;
            if (sobjects != null)
            {
                for (int i = 0; i < sobjects.Length; i++)
                {
                    objAccount = new Account();
                    objAccount.Id = sobjects[i].Id;
                    objAccount.AccountNumber = ((Account)sobjects[i]).AccountNumber;
                    objAccount.Name = ((Account)sobjects[i]).Name;
                    objAccount.Website = ((Account)sobjects[i]).Website;
                    objAccount.ShippingCity = ((Account)sobjects[i]).ShippingCity;
                    objAccount.ShippingCountry = ((Account)sobjects[i]).ShippingCountry;
                    objAccount.ShippingPostalCode = ((Account)sobjects[i]).ShippingPostalCode;
                    objAccount.ShippingState = ((Account)sobjects[i]).ShippingState;
                    objAccount.ShippingStreet = ((Account)sobjects[i]).ShippingStreet;
                    objAccount.BillingCity = ((Account)sobjects[i]).BillingCity;
                    objAccount.BillingCountry = ((Account)sobjects[i]).BillingCountry;
                    objAccount.BillingPostalCode = ((Account)sobjects[i]).BillingPostalCode;
                    objAccount.BillingState = ((Account)sobjects[i]).BillingState;
                    objAccount.BillingStreet = ((Account)sobjects[i]).BillingStreet;
                    objAccount.AccountSource = ((Account)sobjects[i]).AccountSource;
                    objAccount.AnnualRevenue = ((Account)sobjects[i]).AnnualRevenue;
                    objAccount.AnnualRevenueSpecified = ((Account)sobjects[i]).AnnualRevenueSpecified;
                    objAccount.Contacts = ((Account)sobjects[i]).Contacts;
                    objAccount.CreatedBy = ((Account)sobjects[i]).CreatedBy;
                    objAccount.CreatedById = ((Account)sobjects[i]).CreatedById;
                    objAccount.CreatedDate = ((Account)sobjects[i]).CreatedDate;
                    objAccount.CreatedDateSpecified = ((Account)sobjects[i]).CreatedDateSpecified;
                    objAccount.Fax = ((Account)sobjects[i]).Fax;
                    objAccount.Industry = ((Account)sobjects[i]).Industry;
                    objAccount.IsDeleted = ((Account)sobjects[i]).IsDeleted;
                    objAccount.IsDeletedSpecified = ((Account)sobjects[i]).IsDeletedSpecified;
                    objAccount.Jigsaw = ((Account)sobjects[i]).Jigsaw;
                    objAccount.JigsawCompanyId = ((Account)sobjects[i]).JigsawCompanyId;
                    objAccount.LastActivityDate = ((Account)sobjects[i]).LastActivityDate;
                    objAccount.LastActivityDateSpecified = ((Account)sobjects[i]).LastActivityDateSpecified;
                    objAccount.LastModifiedBy = ((Account)sobjects[i]).LastModifiedBy;
                    objAccount.LastModifiedById = ((Account)sobjects[i]).LastModifiedById;
                    objAccount.LastModifiedDate = ((Account)sobjects[i]).LastModifiedDate;
                    objAccount.LastModifiedDateSpecified = ((Account)sobjects[i]).LastModifiedDateSpecified;
                    objAccount.NumberOfEmployees = ((Account)sobjects[i]).NumberOfEmployees;
                    objAccount.NumberOfEmployeesSpecified = ((Account)sobjects[i]).NumberOfEmployeesSpecified;
                    objAccount.NumberofLocations__c = ((Account)sobjects[i]).NumberofLocations__c;
                    objAccount.NumberofLocations__cSpecified = ((Account)sobjects[i]).NumberofLocations__cSpecified;
                    objAccount.Owner = ((Account)sobjects[i]).Owner;
                    objAccount.OwnerId = ((Account)sobjects[i]).OwnerId;
                    objAccount.Ownership = ((Account)sobjects[i]).Ownership;
                    objAccount.Phone = ((Account)sobjects[i]).Phone;
                    objAccount.Rating = ((Account)sobjects[i]).Rating;
                    objAccount.Sic = ((Account)sobjects[i]).Sic;
                    objAccount.SicDesc = ((Account)sobjects[i]).SicDesc;
                    objAccount.Site = ((Account)sobjects[i]).Site;
                    objAccount.Type = ((Account)sobjects[i]).Type;
                    objAccountList.Add(objAccount);
                }
            }
            return objAccountList;
        }
Posted in Salesforce | Tagged , , | Leave a comment

How to integrate Salesforce with third party ERP, finance systems or any external application.

Step 1: Create an account on Developer Edition of Salesforce.Developer Edition provides access to all of the features available with Enterprise Edition.
Step 2: Regenerate the WSDL file (Generate or Obtain the Web Service WSDL)
To generate the WSDL file for your organization:

1. Log in to your Enterprise, Unlimited, or Developer Edition Salesforce account. You must log in as an administrator or as a user who has the “Modify All Data” permission.
2. Click Setup, and then under App Setup, click Integrate.
3. Click Apex API to display the WSDL download page.
4. Right-click Enterprise WSDL to display your browser’s save options, and save the enterprise WSDL to a local directory.

Step 3: Import it into your environment (Import the WSDL File Into Your Development Platform)

To access an XML Web service from managed code:

1. Add a Web reference to your project for the XML Web service that you want to access. The Web reference creates a proxy class with methods that serve as proxies for each exposed method of the XML Web service.
2. Add the namespace for the Web reference.
3. Create an instance of the proxy class and then access the methods of that class as you would the methods of any other class.

To add a Web reference:

1. On the Project menu, choose Add Web Reference.
2. In the URL box of the Add Web Reference dialog box, type the URL to obtain the service description of the XML Web service you want to access, such as:
file:///c:\WSDLFiles\enterprise.wsdl
3. Click Go to retrieve information about the XML Web service.
4. In the Web reference name box, rename the Web reference to sforce, which is the namespace you will use for this Web reference.
5. Click Add Reference to add a Web reference for the target XML Web service. For more information, see the topic “Adding and Removing Web References” in the Visual Studio documentation.
6. Visual Studio retrieves the service description and generates a proxy class to interface between your application and the XML Web service.

Step 4: When accessing salesforce.com from outside of your company’s trusted networks, you must add a security token to your password to log in to a desktop client, such as Connect for Outlook, Connect Offline, Connect for Office, Connect for Lotus Notes, or the Data Loader.New security tokens are automatically sent to you when your salesforce.com password is changed or when you request to reset your security token.

/*
* login sample
* Prompts for username and password, set class variable binding
* resets the url for the binding and adds the session header to
* the binding class variable
*/

private bool login()
{
string securitytoken = "5wVvr7MWSwKmWItdcpD4Nl3uY";
string un = "[email protected]";
string pw = "abc123" + securitytoken;

Console.WriteLine("Creating the binding to the web service...");
/* * Create the binding to the sforce servics */

private SforceService binding == new SforceService();
// Time out after a minute
binding.Timeout = 60000;
//Attempt the login giving the user feedback
Console.WriteLine("LOGGING IN NOW....");
try
{
loginResult = binding.login(un, pw);
}
catch (System.Web.Services.Protocols.SoapException e)
{
// This is likley to be caused by bad username or password
Console.Write(e.Message + ", please try again.\n\nHit return to continue...");
Console.ReadLine();
return false;
}
catch (Exception e)
{
// This is something else, probably comminication
Console.Write(e.Message + ", please try again.\n\nHit return to continue...");
Console.ReadLine();
return false;
}
Console.WriteLine("\nThe session id is: " + loginResult.sessionId);
Console.WriteLine("\nThe new server url is: " + loginResult.serverUrl);
//Change the binding to the new endpoint
binding.Url = loginResult.serverUrl;
//Create a new session header object and set the session id to that returned by the login
binding.SessionHeaderValue = new apex.SessionHeader();
binding.SessionHeaderValue.sessionId = loginResult.sessionId;
apex.GetUserInfoResult userInfo = loginResult.userInfo;
return true;
}
Posted in Salesforce | Tagged , , | Leave a comment

Comparison between Microsoft Dynamics CRM and SalesForce.com based on simple Customization

We will look at the Out of the Box customization functionality of both Dynamics CRM and Salesforce.com.

There are several business cases for wanting to customize your system. A very common type of customization is a change made to a record such as adding a new field or creating a view within the record to surface relevant data. Both Dynamics CRM and Salesforce.com facilitate basic record customization, and while the Dynamics approach in regards to this feature is clean, intuitive, and simple, the SalesForce.com approach is disjointed, cumbersome, and complex.

Let’s compare the two different systems in regards to these 3 simple and basic customization functions:

– Customizing record forms: fields

– Customizing record forms: Surfacing related records and data

– Saving/Publishing your customizations

Let’s review the overall UI for record customizations:

In Dynamics CRM you can go to the record you want to customize and it’s one click on the customizations tab, and one click on the customize form button. You are then brought to a single screen that facilitates all 3 of the mentioned customizations as well as a few others.

SalesForce offers similar functionality (you can customize directly from the record) however each customization link brings you to a different screen. There is no one screen that allows the user to visually see the record AND all of the customization options in one place. The UI is disjointed and confusing.

Posted in MS CRM 2011 | Tagged , | Leave a comment

How to Retrieve OptionSets Label Text in Dynamics CRM 2011

Calling Below Method as

string labelValue = GetOptionSetValueLabel(CrmService, accEntity.LogicalName, "homeroof" , 100001);

// Method to retrieve OptionSet label value
Private string GetOptionSetValueLabel(IOrganizationService CrmWebService, string prmEntityName, string prmAttributeName, int prmOptionSetValue)
{
string ReturnLabel = string.Empty;

OptionMetadataCollection OptionsSetLabels = null;

OptionsSetLabels = RetrieveOptionSetMetaDataCollection(ref CrmWebService, prmEntityName, prmAttributeName);

foreach (OptionMetadata OptionMetdaData in OptionsSetLabels)
{
if (OptionMetdaData.Value == prmOptionSetValue)
{
ReturnLabel = OptionMetdaData.Label.UserLocalizedLabel.Label;
break;
}
}

return ReturnLabel;
}

// Method to Retrieve OptionSet Options Metada Data Collection.
Private OptionMetadataCollection RetrieveOptionSetMetaDataCollection( IOrganizationService CrmWebService, string prmEntityName, string prmAttributeName)
{

OptionMetadataCollection ReturnOptionsCollection = null;
RetrieveEntityRequest RetrieveEntityRequest = new RetrieveEntityRequest();
RetrieveEntityResponse RetrieveEntityResponse = new RetrieveEntityResponse();

RetrieveEntityRequest.LogicalName = prmEntityName;

RetrieveEntityRequest.EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Attributes;

RetrieveEntityResponse = (RetrieveEntityResponse)CrmWebService.Execute(RetrieveEntityRequest);

foreach (AttributeMetadata AttributeMetadata in RetrieveEntityResponse.EntityMetadata.Attributes)
{
if (AttributeMetadata.AttributeType == AttributeTypeCode.Picklist &amp;&amp;
AttributeMetadata.LogicalName == prmAttributeName)
{
ReturnOptionsCollection = ((PicklistAttributeMetadata)AttributeMetadata).OptionSet.Options;
break;
}
}

return ReturnOptionsCollection;
}
Posted in MS CRM 2011 | Tagged , | Leave a comment

How to modify PDF file using iTextSharp

Step 1: First you need to stamp the PDF file using PDF stamper ( For example: for first name, last name etc.)
Step 2: Download iTextSharp dll and add reference to your solution.
Step 3: Modify the Below code as per your requirement.

void textwriter()
{
string fileNameExisting = @”C:\Users\amar.prakash\Desktop\SC.pdf”;
string fileNameNew = @”C:\Users\amar.prakash\Desktop\NewSC.pdf”;

using (var existingFileStream = new FileStream(fileNameExisting, FileMode.Open))
using (var newFileStream = new FileStream(fileNameNew, FileMode.Create))
{
// Open existing PDF
var pdfReader = new PdfReader(existingFileStream);

// PdfStamper, which will create
var stamper = new PdfStamper(pdfReader, newFileStream);

var form = stamper.AcroFields;
var fieldKeys = form.Fields.Keys;

foreach (string fieldKey in fieldKeys)
{
//if (fieldKey.StartsWith(“T”))
// form.SetField(fieldKey, “REPLACED!”);
//if (fieldKey.StartsWith(“c”))
// form.SetField(fieldKey, “Yes”);
if (fieldKey.Equals(“Text1”))
form.SetField(fieldKey, “ABC Inc”);
if (fieldKey.Equals(“Text2”))
form.SetField(fieldKey, “Amar”);
if (fieldKey.Equals(“Text3”))
form.SetField(fieldKey, “Anand”);
if (fieldKey.Equals(“Text4”))
form.SetField(fieldKey, “REPLACED!”);
}

// “Flatten” the form so it wont be editable/usable anymore
stamper.FormFlattening = true;

// You can also specify fields to be flattened, which
// leaves the rest of the form still be editable/usable
stamper.PartialFormFlattening(“field1”);

stamper.Close();
pdfReader.Close();
}

Posted in General | Tagged , | 2 Comments

Workflow Process “Save As” functionality in Dynamics CRM 2011

Often there is a need to create a complex Process (workflow) and then shortly thereafter, recreate it with slightly different parameters. Dynamics CRM 2011 does not come with a “Save as” mechanism for workflows like it does for advanced finds and Views so it would seem you would have to go in and recreate the new workflow to match the one that already exists.

There is a requirement for the creation of multiple views (27 to be exact) and accompanying workflows that could be run on demand to affect just the records in these views. The views were fairly easy to recreate as only one piece of data in the grid was changed and after creating one and doing a “Save As” for the other 26, the process was straight forward.

The workflows were not quite that easy to create but very simple to duplicate. Each workflow did essentially the same thing (set a completion date on an entity after some validity checking) but each view represented a different date field on that entity. What we did was create a workflow for the first view and instead of saving with the ‘Activate As” value of “Process”, we saved it as a “Process Template”. We published this and as we created the other workflows, we simply chose to base them on this template.

All that needed to be done with this new workflow was to change the values being looked at in the steps that determined if an update was required and also change the field that was being updated. After the 26 “copies” were made, we unpublished the original “template” workflow, set the “Active As” to “Process” re-saved it and we had all 27 workflows done in a very short time.

As an additional benefit, all of the commenting of the workflow was identical so the end result was in a consistent form.

Posted in MS CRM 2011 | Tagged , | 3 Comments

Building clients for Windows Phone and Windows 8 RT

The Microsoft.Xrm.Sdk.dll library provided as part of the Dynamics CRM 2011 SDK makes it easy to write  .NET applications that target the desktop. This library has dependencies on .NET 4.0 and Windows Identity Foundation (WIF), neither of which are available for Windows Phone and Windows 8 RT platforms. Although the WS-Trust protocol used by Dynamics CRM 2011 for authentication is fairly well defined and several folks have built implementations for other languages/platforms, we want to make it easy for you to build amazing applications on these platforms , so a reference implementation of the CRM SDK for these platforms is provided here. Unlike the desktop version, where we only provided you with the binary assembly, we have provided the complete source code, so you should be able to make changes to fit your specific needs.  Please note that this works for Dynamics CRM Online deployments, both Office 365 and Windows Live ID, and for Internet Facing Deployments (IFD). It does not work for Dynamics CRM on-premises deployments using Active Directory authentication.

This code is provided “as is”, so you are responsible for making any fixes.

The rest of this post describes how to use the code to authenticate and send web service requests.

Authenticating to the CRM Web Services

Use ServiceConfigurationFactory to construct a DiscoveryServiceConfiguration or an OrganizationServiceConfiguration object. These classes load the relevant metadata and raise one of these events:

  • MetadataLoaded event if the service metadata has been loaded successfully
  • MetadataLoadFailure for other failure cases, such as when the endpoint is not reachable

Once the metadata has been loaded, you can call the Authenticate method. On completion, the Authenticatemethods raise the SignInComplete event. The SignOnCompletedEventArgs object on the event callback contains the returned token in the Result property on successful authentication, and contains a non-null exception in the Error property in the case of failed authentication. You can use the returned token to call CRM web service methods.

Windlows Live ID authentication requires device authentication to be performed first, in which case the authentication flow is AuthenticateDevice -> DeviceSigninComplete event -> Authenticate ->SignInComplete event, which can be achieved as shown below:

  1. Attach to the DeviceSigninComplete event and do the following in the event handler:
    1. Handle any error in device authentication by examining the SignOnCompletedEventArgs.Errorproperty. If there is no error, continue with the following
    2. Attach to the SignInComplete event for the user authentication. In the handler, handle any error/read the returned token
    3. Call Authenticate(ClientCredentials clientCredentials, RequestSecurityTokenResponsedeviceSecurityToken) passing in the user credentials and the returned token response from device authentication
  2. Call AuthenticateDevice passing in the device credentials to trigger the authentication flow. TheDeviceSigninComplete event triggers the user authentication (achieved by step 1)

Calling the CRM Web Services

  1. If no cached token available, authenticate as shown above, and cache the returned token.
  2. Instantiate either the DiscoveryServiceProxy or the OrganizationServiceProxy object as needed.
  3. Set the SecurityTokenReponse property on the proxy object to the cached token.
  4. Attach to the corresponding completion event for the method to be called. For example, useCreateCompleted for the Create method, ExecuteCompleted for the Execute method.
  5. Call the web service method on the DiscoveryServiceProxy or OrganizationServiceProxy objects.
Posted in MS CRM 2011 | Tagged , | Leave a comment

How to consume WCF Service using Channel Factory

A Channel Factory is implemented by the IChannelFactory Interface and their associated channels are used by the initiators of a communication pattern. The Channel Factory class is useful when you want to share a common service contract DLL between the client and the server.
When to use Channel Factory

The Channel Factory class is used to construct a channel between the client and server without creating a Proxy. In some of the cases in which your service is tightly bound with to the client application, we can use an interface DLL directly and with the help of a Channel Factory, call a method. The advantage of the Channel Factory route is that it gives you access method(s) that wouldn’t be available if you use svcutil.exe.

Channel Factory is also useful when you do not share more than just the service contract with a client. If you know that your entity will not change frequently than it is better to use a Channel Factory than a Proxy.

ChannelFactory<T> takes a generic parameter of the service type (it must be a service contract interface) to create a channel. Because ChannelFactory only requires knowledge of the service contract, it makes good design sense to put service/data contracts in separate assemblies from service implementations. This way, you can safely distribute contract assemblies to third parties who wish to consume services, without the risk of disclosing their actual implementation.

using System;
using System.ServiceModel;

// This code generated by svcutil.exe.

[ServiceContract()]
interface IMath
{
[OperationContract()]
double Add(double A, double B);
}

public class Math : IMath
{
public double Add(double A, double B)
{
return A + B;
}
}

public sealed class Test
{
static void Main()
{
// Code not shown.
}

public void Run()
{
// This code is written by an application developer.
// Create a channel factory.
BasicHttpBinding myBinding = new BasicHttpBinding();
EndpointAddress myEndpoint = new EndpointAddress(“http://159.195.1.28/MathService/Service.svc”);
ChannelFactory myChannelFactory = new ChannelFactory(myBinding, myEndpoint);
// Create a channel.
IMath wcfClient1 = myChannelFactory.CreateChannel();
double s = wcfClient1.Add(3, 39);
Console.WriteLine(s.ToString());
((IClientChannel)wcfClient1).Close();

// Create another channel.
IMath wcfClient2 = myChannelFactory.CreateChannel();
s = wcfClient2.Add(15, 27);
Console.WriteLine(s.ToString());
((IClientChannel)wcfClient2).Close();
myChannelFactory.Close();
}
}

Posted in General, MS CRM 2011 | Tagged , , | Leave a comment

Create E-mail Activity and Multiple E-mail Attachment in MS CRM 2011

Copy and paste the below function to get it work. You can use this function to create email activity and email attachment related to the same email activity from Plugin/ Custom Workflow / Or any external web application or windows application.

private void CreateEmailAndEmailAttachment(OrderDTO orderDTO)
{
Guid _emailId;
string[] emailAddresses;
string temp;
string emailstring;

List<ActivityParty> objtoParty = new List<ActivityParty>();
List<ActivityParty> objccParty = new List<ActivityParty>();
List<ActivityParty> objbccParty = new List<ActivityParty>();
List<ActivityParty> objfromParty = new List<ActivityParty>();

// Email From
var activityParty = new ActivityParty
{
AddressUsed = orderDTO.EmailFrom
};
objfromParty.Add(activityParty);

// Email To
emailAddresses = orderDTO.EmailTo.Split(‘;’);
foreach (string sAddr in emailAddresses)
{
temp = sAddr.Trim();

if (temp.IndexOf(“<“, StringComparison.Ordinal) == -1)
{
activityParty = new ActivityParty
{
AddressUsed = temp
};
}
else
{
emailstring = temp.Substring(temp.IndexOf(“<“, StringComparison.Ordinal) + 1, temp.IndexOf(“>”, StringComparison.Ordinal) – temp.IndexOf(“<“, StringComparison.Ordinal) – 1);
activityParty = new ActivityParty
{
AddressUsed = emailstring
};
}
objtoParty.Add(activityParty);
}

// Email CC
if (orderDTO.EmailCC.Length != 0)
{
emailAddresses = orderDTO.EmailCC.Split(‘;’);
foreach (string sAddr in emailAddresses)
{
temp = sAddr.Trim();

if (temp.IndexOf(“<“, StringComparison.Ordinal) == -1)
{
activityParty = new ActivityParty
{
AddressUsed = temp
};
}
else
{
emailstring = temp.Substring(temp.IndexOf(“<“, StringComparison.Ordinal) + 1, temp.IndexOf(“>”, StringComparison.Ordinal) – temp.IndexOf(“<“, StringComparison.Ordinal) – 1);
activityParty = new ActivityParty
{
AddressUsed = emailstring
};
}
objccParty.Add(activityParty);
}
}

// Email Bcc
if (orderDTO.EmailBcc.Length != 0)
{
emailAddresses = orderDTO.EmailBcc.Split(‘;’);
foreach (string sAddr in emailAddresses)
{
temp = sAddr.Trim();

if (temp.IndexOf(“<“, StringComparison.Ordinal) == -1)
{
activityParty = new ActivityParty
{
AddressUsed = temp
};
}
else
{
emailstring = temp.Substring(temp.IndexOf(“<“, StringComparison.Ordinal) + 1, temp.IndexOf(“>”, StringComparison.Ordinal) – temp.IndexOf(“<“, StringComparison.Ordinal) – 1);
activityParty = new ActivityParty
{
AddressUsed = emailstring
};
}
objbccParty.Add(activityParty);
}
}

//Creating Email Activity
Email email = new Email
{
Subject = orderDTO.EmailSubject,
ActivityId = Guid.NewGuid(),
To = objtoParty,
From = objfromParty,
Cc = objccParty,
Bcc = objbccParty,
Description = orderDTO.EmailBody,
RegardingObjectId = new EntityReference(Quote.EntityLogicalName, new Guid(orderDTO.OrderHeaderDTO.ordergroup_id))
};
_emailId = this.crmService.Create(email);

#region Creating Multiple E-mail Attachment

//Create Email Attachment
ActivityMimeAttachment _fileAttachment = new ActivityMimeAttachment
{
ObjectId = new EntityReference(Email.EntityLogicalName, _emailId),
ObjectTypeCode = Email.EntityLogicalName,
Subject = orderDTO.EmailSubject,
Body = System.Convert.ToBase64String(orderDTO.EmailAttachmentFileContent),
FileName = orderDTO.EmailAttachmentFileName
};
this.crmService.Create(_fileAttachment);

if (orderDTO.EmailAttachmentFileContent1 != null)
{
//Create Email Attachment1
_fileAttachment = new ActivityMimeAttachment
{
ObjectId = new EntityReference(Email.EntityLogicalName, _emailId),
ObjectTypeCode = Email.EntityLogicalName,
Subject = orderDTO.EmailSubject,
Body = System.Convert.ToBase64String(orderDTO.EmailAttachmentFileContent1),
FileName = orderDTO.EmailAttachmentFileName1
};
this.crmService.Create(_fileAttachment);
}

if (orderDTO.EmailAttachmentFileContent2 != null)
{
//Create Email Attachment2
_fileAttachment = new ActivityMimeAttachment
{
ObjectId = new EntityReference(Email.EntityLogicalName, _emailId),
ObjectTypeCode = Email.EntityLogicalName,
Subject = orderDTO.EmailSubject,
Body = System.Convert.ToBase64String(orderDTO.EmailAttachmentFileContent2),
FileName = orderDTO.EmailAttachmentFileName2
};
this.crmService.Create(_fileAttachment);
}

if (orderDTO.EmailAttachmentFileContent3 != null)
{
//Create Email Attachment3
_fileAttachment = new ActivityMimeAttachment
{
ObjectId = new EntityReference(Email.EntityLogicalName, _emailId),
ObjectTypeCode = Email.EntityLogicalName,
Subject = orderDTO.EmailSubject,
Body = System.Convert.ToBase64String(orderDTO.EmailAttachmentFileContent3),
FileName = orderDTO.EmailAttachmentFileName3
};
this.crmService.Create(_fileAttachment);
}

if (orderDTO.EmailAttachmentFileContent3 != null)
{
//Create Email Attachment4
_fileAttachment = new ActivityMimeAttachment
{
ObjectId = new EntityReference(Email.EntityLogicalName, _emailId),
ObjectTypeCode = Email.EntityLogicalName,
Subject = orderDTO.EmailSubject,
Body = System.Convert.ToBase64String(orderDTO.EmailAttachmentFileContent4),
FileName = orderDTO.EmailAttachmentFileName4
};
this.crmService.Create(_fileAttachment);
#endregion
}

Posted in MS CRM 2011 | Tagged , , | 2 Comments

New Xrm.Utility Functions in Update Rollup 8 for Microsoft Dynamics CRM 2011 and Microsoft Dynamics CRM Online.

Xrm.Utility Reference
The Xrm.Utility object provides a container for useful functions not directly related to the current page.
These functions are available in every application page that supports scripting. You can use them in form scripts or in ribbon commands. For HTML web resources, they are available when you include the ClientGlobalContext.js.aspx page. For more information, see ClientGlobalContext.js.aspx.

Functions

The following table lists the functions of Xrm.Utility.

Function Description
openEntityForm Opens an entity form.
openWebResource Opens an HTML web resource.

openEntityForm

Opens an entity form.

Xrm.Utility.openEntityForm(name,id,parameters)

Parameters

  • name
    • Type: String
    • Required: The logical name of an entity.
  • id
    • Type: String
    • Optional: The string representation of a unique identifier or the record to open in the form. If not set, a form to create a new record is opened.
  • parameters
    • Type: Object
    • Optional: A dictionary object that passes extra query string parameters to the form. Invalid query string parameters will cause an error.Valid extra query string parameters are:

Return Value: Window object.

Remarks: This function provides a better developer experience than the process of manipulating the URL passed to the window.open method described in Open Forms, Views, and Dialogs with a URL. Using this function also helps ensure that users are not prompted to log in again under certain circumstances.

Examples:

Open a new account record

Xrm.Utility.openEntityForm("account");

Open an existing account record

Xrm.Utility.openEntityForm("account","A85C0252-DF8B-E111-997C-00155D8A8410");

Open a new account record with a specific form and setting default values

var parameters = {};
parameters["formid"] = "b053a39a-041a-4356-acef-ddf00182762b";
parameters["name"] = "Test";
parameters["telephone1"] = "(425) 555-1234";
Xrm.Utility.openEntityForm("account", null, parameters);

Open a new contact record, move it to the top left corner of the screen, and set the size of the window

Note

You cannot use window object methods such as moveTo or resizeTo in scripts that will run in Microsoft Dynamics CRM for Microsoft Office Outlook.

var newWindow = Xrm.Utility.openEntityForm("contact");
newWindow.moveTo(0,0);
newWindow.resizeTo(800,600);

openWebResource

Opens an HTML web resource.

Xrm.Utility.openWebResource(webResourceName,webResourceData,width, height)

Parameters

  • webResourceName
    • Type: String
    • Required: The name of the HTML web resource to open.
  • webResourceData
    • Type: String
    • Optional: Data to be passed into the data parameter.
  • width
    • Type: Number
    • Optional: The width of the window to open in pixels.
  • height
    • Type: Number
    • Optional: The height of the window to open in pixels.

Return Value: Window object.

Remarks: An HTML web resource can accept the parameter values described in Passing Parameters to HTML Web Resources . This function only provides for passing in the optional data parameter. To pass values for the other valid parameters, you must append them to the webResourceNameparameter.

Examples:

Open an HTML web resource named “new_webResource.htm”:

Xrm.Utility.openWebResource("new_webResource.htm");

Open an HTML web resource including a single item of data for the data parameter”

Xrm.Utility.openWebResource("new_webResource.htm","dataItemValue");

Open an HTML web resource passing multiple values through the data parameter

var customParameters = encodeURIComponent("first=First Value&second=Second Value&third=Third Value");
Xrm.Utility.openWebResource("new_webResource.htm",customParameters);

Note

These values have to be extracted from the value of the data parameter in the HTML web resource. For more information, see Sample: Pass Multiple Values to a Web Resource Through the Data Parameter.

Open an HTML web resource with the parameters expected by HTML web resources:

Xrm.Utility.openWebResource("new_webResource.htm?typename=account&userlcid=1033");

For more information, see Passing Parameters to HTML Web Resources .

Open an HTML web resource, setting the height and width:

Xrm.Utility.openWebResource("new_webResource.htm", null, 300,300);
Posted in MS CRM 2011 | Tagged , | Leave a comment