RevokeAccess Message

Revokes access rights to the entity instance for the specified security principal (user or team).

Remarks

To use this message, pass an instance of the RevokeccessRequest class as the request parameter in the Execute method.

This method also applies to all child instances of the target instance. For all child instances, if the caller does not have share privileges for those entity types or share rights to the instances, access to the child instances is not revoked. As a result, the owner of the instance or a user who shares the instance with share rights automatically has share rights to all child instances of the target instance. In this case, only the lack of privileges to a particular entity type prevents access to the child instances from being revoked.

For a description of how actions on a parent instance affect child instances, see Cascading Rules.

To perform this action, the caller must have access rights on the entity instance specified in the request class. For a list of required privileges, see RevokeAccess Privileges.

 
//#The following code example shows how to use the RevokeAccess message.

// Set up the CRM service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the SecurityPrincipal.
SecurityPrincipal principal = new SecurityPrincipal();
principal.Type = SecurityPrincipalType.User;

// PrincipalId is the GUID of the user whose access is being revoked.
principal.PrincipalId = new Guid("7B222F98-F48A-4AED-9D09-77A19CB6EE82");

// Create the target for the request.
TargetOwnedAccount target = new TargetOwnedAccount();

// EntityId is the GUID of the account to which access is being revoked.
target.EntityId = new Guid("2B951FBC-1C56-4430-B23B-20A1349068F3");

// Create the request object.
RevokeAccessRequest revoke = new RevokeAccessRequest();

// Set the properties of the request object.
revoke.Revokee = principal;
revoke.Target = target;

// Execute the request.
RevokeAccessResponse revoked = (RevokeAccessResponse)service.Execute(revoke);





Send a Custom E-mail for a Campaign Activity

The following sample shows how to send an e-mail for a campaign activity.



[C#]
public void SendEmail(Guid campaignActivityID)
{
CrmService service = new CrmService();
service.Credentials =
System.Net.CredentialCache.DefaultCredentials;

service.CallerIdValue = new CallerId();
// Replace the GUID with the GUID of your Microsoft Dynamics CRM
// Administrator.
service.CallerIdValue.CallerGuid =
new Guid("FD80F8E8-C852-DA11-B1FB-0007E94D105B");

SendEmailRequest req = new SendEmailRequest();
req.EmailId = campaignActivityID;
req.TrackingToken = "";
req.IssueSend = true;

try
{
SendEmailResponse res =
(SendEmailResponse)service.Execute(req);
}
catch (System.Web.Services.Protocols.SoapException er)
{
//Process any error messages here.
}
}




Cancel Message

Cancels a contract or salesorder

    //#Cancels a Contract
// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the cancel request for a previously created contract
CancelContractRequest contactCancelationRequest = new CancelContractRequest();

// Set the properties for the request
contactCancelationRequest.ContractId = new Guid("C15AF217-C17E-DA11-B90F-000874DE7397");
contactCancelationRequest.CancelDate = new CrmDateTime();
contactCancelationRequest.CancelDate.Value = DateTime.Now.ToString();
contactCancelationRequest.Status = 5;

// Execute the request
service.Execute(contactCancelationRequest);




The following code example demonstrates how to cancel a sales order.

 
//# cancel a sales order.
// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the order close activity object.
orderclose close = new orderclose();

// Set the properties of the order close object.
close.subject = "orderclose";

// Create a Lookup for the sales order being canceled.
close.salesorderid = new Lookup();
close.salesorderid.type = EntityName.salesorder.ToString();
close.salesorderid.Value = created.id;

// Create the request object.
CancelSalesOrderRequest cancel = new CancelSalesOrderRequest();

// Set the properties of the request object.
cancel.OrderClose = close;
cancel.Status = -1;

// Execute the request.
CancelSalesOrderResponse canceled = (CancelSalesOrderResponse) service.Execute(cancel);




Book Message

Schedules or "books" an appointment.




//# The following example shows how to use the Book message to schedule an appointment.
// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the activityparty entity instance.
activityparty party = new activityparty();
party.scheduledstart = new CrmDateTime();
party.scheduledstart.Value = DateTime.Now.AddHours(1).ToString();
party.scheduledend = new CrmDateTime();
party.scheduledend.Value = DateTime.Now.AddHours(2).ToString();
party.partyid = new Lookup();
party.partyid.type = EntityName.systemuser.ToString();
party.partyid.Value = user.UserId;

// Create the appointment entity instance.
appointment appointment = new appointment();

// Set the appointment's properties.
appointment.description = "This is a test of the book message.";
appointment.scheduledstart = new CrmDateTime();
appointment.scheduledstart.Value = DateTime.Now.AddHours(1).ToString();
appointment.scheduledend = new CrmDateTime();
appointment.scheduledend.Value = DateTime.Now.AddHours(2).ToString();
appointment.location = "Office";
appointment.subject = "Testing book appointment";
appointment.requiredattendees = new activityparty[] {party};
appointment.statecode = new AppointmentStateInfo();
appointment.statecode.Value = AppointmentState.Open;
appointment.statuscode = new Status();
// This is the default value.
appointment.statuscode.Value = -1;

// Create the target.
TargetScheduleAppointment target = new TargetScheduleAppointment();

// Set the target properties.
target.Appointment = appointment;

// Create the request.
BookRequest book = new BookRequest();

// Set the request properties.
book.Target = target;

// Execute the request.
BookResponse booked = (BookResponse)service.Execute(book);



BackgroundSendEmail Message



//# Sends an e-mail asynchronously.
// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create a query for the BackgroundSendEmailRequest object that will find all
// e-mails with the text "SDK Sample E-mail" in the subject and a status code of
// "Pending Send".

// NOTE: A more robust query would include e-mails that have been downloaded
// previously but not sent for some reason and exclude emails that have failed
// delivery too many times.

// Create the condition for e-mail subject text.
ConditionExpression subjectCondition = new ConditionExpression();
subjectCondition.AttributeName = "subject";
subjectCondition.Operator = ConditionOperator.Like;
subjectCondition.Values = new string[] { "SDK Sample Email%" };

// Create the condition for e-mail status. Only draft e-mails will be sent.
ConditionExpression statusCondition = new ConditionExpression();
statusCondition.AttributeName = "statuscode";
statusCondition.Operator = ConditionOperator.Equal;
statusCondition.Values = new object[] { EmailStatus.PendingSend };

// Create the query filter.
FilterExpression emailFilter = new FilterExpression();
emailFilter.Conditions = new ConditionExpression[] { statusCondition };
emailFilter.FilterOperator = LogicalOperator.And;

// Query for e-mail activity to send.
QueryExpression emailsQuery = new QueryExpression();
// Be aware that using AllColumns may adversely affect
// performance and cause unwanted cascading in subsequent
// updates. A best practice is to retrieve the least amount of
// data required.
emailsQuery.ColumnSet = new AllColumns();
emailsQuery.EntityName = EntityName.email.ToString();
emailsQuery.Criteria = emailFilter;

// Create the request.
BackgroundSendEmailRequest bkgrndSendEmailRequest = new BackgroundSendEmailRequest();

// Set the query.
bkgrndSendEmailRequest.Query = emailsQuery;

// Execute the request. This will change the status from "Pending Send" to "Sending".
BackgroundSendEmailResponse bkgrndSendEmailResponse = (BackgroundSendEmailResponse)service.Execute(bkgrndSendEmailRequest);

foreach (email emailRecordToProcess in bkgrndSendEmailResponse.BusinessEntityCollection.BusinessEntities)
{
// Use SMTP or MAPI to compose actual emails and submit them for delivery.
}




Assigns the specified entity instance to a new security principal

Assigns the specified entity instance to a new security principal (user). This changes the ownerid attribute of the instance.

//# The following code example demonstrates how to assign the specified entity instance to a new security principal (user).

// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the SecurityPrincipal object.
SecurityPrincipal assignee = new SecurityPrincipal();
assignee.Type = SecurityPrincipalType.User;

// PrincipalId is some known Guid belonging to the user or team that will own this record.
assignee.PrincipalId = new Guid("326A0053-71CB-465E-9BEB-633E2E0851A9");

// Create the target object for the request.
TargetOwnedAccount target = new TargetOwnedAccount();

// Set the properties of the target object.
// EntityId is some known Guid belonging to the account that is being assigned to the user.
target.EntityId = new Guid("2B951FBC-1C56-4430-B23B-20A1349068F3");

// Create the request object.
AssignRequest assign = new AssignRequest();

// Set the properties of the request object.
assign.Assignee = assignee;
assign.Target = target;

// Execute the request.
AssignResponse assignResponse = (AssignResponse)service.Execute(assign);




How to use the SetStateAccount message

Sets the state of an account.

//# The following code example shows how to use the SetStateAccount message.

// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the request object.
SetStateAccountRequest state = new SetStateAccountRequest();

// Set the properties of the request object.
state.AccountState = AccountState.Inactive;
state.AccountStatus = 2;

// EntityId is the GUID of the account whose state is being changed.
state.EntityId = new Guid("AD618DB2-F0DB-4A6A-8C4B-2F2213EAA38E");;

// Execute the request.
SetStateAccountResponse stateSet = (SetStateAccountResponse)service.Execute(state);





AddMembers to a team

//The following code example demonstrates how to add a set of users to a team.
// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the AddMembersTeamRequest object.
AddMembersTeamRequest addRequest = new AddMembersTeamRequest();

// Set the AddMembersTeamRequest TeamID property to the object ID of 
// an existing team.
addRequest.TeamId = new Guid("9AF74EF9-A04C-DA11-A0C5-000D9DD8CDAC");

// Set the AddMembersTeamRequest MemberIds property to an 
// array of GUIDs that contains the object IDs of one or more system users.
addRequest.MemberIds =  new Guid[] {new Guid("A0F2D8FE-6468-DA11-B748-000D9DD8CDAC")};

// Execute the request.
AddMembersTeamResponse addResponse = (AddMembersTeamResponse)service.Execute(addRequest);




AddMember to a list

Adds a member to a list. The member added must be one of the following entity types: account, contact, or lead.
To use this message, pass an instance of the AddMemberListRequest class as the request parameter in the Execute method.
To perform this action, the caller must have access rights on the list (marketing list) entity instance. For a list of required privileges, seeAddMemberList Privileges.
//# The following code example demonstrates how to add a member to a list.
// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://<servername7gt;:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the request object.
AddMemberListRequest add = new AddMemberListRequest();

// Set the properties of the request object.
add.EntityId = new Guid("b050f053-yur3-dc31-bb3a-0003ffbad37a");
add.ListId = new Guid("C15AF217-C17E-DA11-B90F-000874DE7397");

// Execute the request.
AddMemberListResponse added = (AddMemberListResponse) service.Execute(add);




Retrieves a business entity instance with the specified ID

Retrieves a business entity instance with the specified ID.

Remarks

To use this message, pass an instance of the RetrieveRequest class as the request parameter in the Execute method. If the columnset includes attributes that are not valid for retrieve, they will be ignored. To perform this action, the caller must have access rights on the entity instance specified in the request class. For a list of required privileges, see Retrieve Privileges.

For better performance, use the Retrieve method instead of using this message.

//# The following code example shows how to use the Retrieve message.

// Set up the CRM service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the column set object that indicates the fields to be retrieved.
ColumnSet cols = new ColumnSet();

// Set the properties of the column set.
cols.Attributes = new string [] {"name"};

// Create the target object for the request.
TargetRetrieveAccount target = new TargetRetrieveAccount();

// Set the properties of the target object.
// EntityId is the GUID of the record being retrieved.
target.EntityId = new Guid("2B951FBC-1C56-4430-B23B-20A1349068F3");

// Create the request object.
RetrieveRequest retrieve = new RetrieveRequest();

// Set the properties of the request object.
retrieve.Target = target;
retrieve.ColumnSet = cols;

// Execute the request.
RetrieveResponse retrieved = (RetrieveResponse)service.Execute(retrieve);




Add an item to a campaign

Adds an item to a campaign. The item added must be one of the following entity types: campaign, list, product, or salesliterature.

The relevant classes are specified in the following table.

Type                         Class

Request                     AddItemCampaignRequest

Response                  AddItemCampaignResponse

Entity                          campaign

Optional Parameters   RequestIdOptionalParameter

Remarks

To use this message, pass an instance of the AddItemCampaignRequest class as the request parameter in the Execute method.

To perform this action, the caller must have access rights on the campaign entity instance. For a list of required privileges, seeAddItemCampaign Privileges.

//The following code example demonstrates how to add an item to a campaign.
// Set up the CRM Service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration.
token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the request object.
AddItemCampaignRequest add = new AddItemCampaignRequest();

// Set the properties of the request object.
add.CampaignId =  new Guid("b4502053-6968-dc11-bb3a-0003ffbad8542");
add.EntityId =  new Guid("b050f053-yur3-dc31-bb3a-0003ffbad37a");
add.EntityName = EntityName.product;
// Execute the request.
AddItemCampaignResponse added = (AddItemCampaignResponse)service.Execute(add);




Send Mail through SQL (using CDOSYS object)

--Start SP # 3 Send Mail through SQL (using CDOSYS object)

-- drop old cdosysmail_failures table if exists
IF (EXISTS (SELECT
  * FROM dbo.sysobjects WHERE name = N'cdosysmail_failures' AND type='U')) DROP TABLE [dbo].[cdosysmail_failures]
GO
-- Create new cdosysmail_failures table
CREATE TABLE [dbo].[cdosysmail_failures]
        ([Date
  of Failure] datetime,
        [Spid]
  int NULL,
        [From] varchar(100)
  NULL,
        [To] varchar(100)
  NULL,
        [Subject] varchar(100)
  NULL,
        [Body] varchar(4000)
  NULL,
        [iMsg] int NULL,
        [Hr]
  int NULL,
        [Source of Failure]
  varchar(255) NULL,
        [Description
  of Failure] varchar(500) NULL,
        [Output
  from Failure] varchar(1000) NULL,
        [Comment
  about Failure] varchar(50) NULL)
GO

IF (EXISTS (SELECT * FROM
  dbo.sysobjects WHERE name = N'sp_send_cdosysmail' AND type='P')) DROP PROCEDURE [dbo].[sp_send_cdosysmail]
GO

    CREATE
  PROCEDURE [dbo].[sp_send_cdosysmail]
      
  @From varchar(100) ,
       @To varchar(100)
  ,
       @Subject varchar(100)=" ",
      
  @Body varchar(4000) =" "
    /*********************************************************************

    This
  stored procedure takes the parameters and sends an e-mail.
    All
  the mail configurations are hard-coded in the stored procedure.
    Comments
  are added to the stored procedure where necessary.
    References
  to the CDOSYS objects are at the following MSDN Web site:
  
   http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_messaging.asp


     ***********************************************************************/
       AS
      
  Declare @iMsg int
       Declare @hr int
      
  Declare @source varchar(255)
       Declare
  @description varchar(500)
       Declare
  @output varchar(1000)

    --************* Create the CDO.Message Object ************************
       EXEC @hr = sp_OACreate 'CDO.Message', @iMsg OUT
       IF @hr <>0
        
  BEGIN
           SELECT
  @hr
           INSERT
  INTO [dbo].[cdosysmail_failures] VALUES (getdate(), @@spid, @From, @To, @Subject,
  @Body, @iMsg, @hr, @source, @description, @output, 'Failed at sp_OACreate')
           EXEC @hr =
  sp_OAGetErrorInfo NULL, @source OUT, @description OUT
          
  IF @hr = 0
            
  BEGIN
              
  SELECT @output = '  Source: ' + @source
              
  PRINT  @output
              
  SELECT @output = '  Description: ' + @description
              
  PRINT  @output
                  
  INSERT INTO [dbo].[cdosysmail_failures] VALUES (getdate(), @@spid, @From, @To,
  @Subject, @Body, @iMsg, @hr, @source, @description, @output, 'sp_OAGetErrorInfo for sp_OACreate')
                  
  RETURN
            
  END
           ELSE
            
  BEGIN
              
  PRINT '  sp_OAGetErrorInfo failed.'
              
  RETURN
            
  END
         END

    --***************Configuring the Message Object ******************
    -- This is to configure a remote SMTP server.
    --
  http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_schema_configuration_sendusing.asp
      
  EXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/sendusing").Value','2'
       IF @hr <>0
        
  BEGIN
           SELECT
  @hr
           INSERT
  INTO [dbo].[cdosysmail_failures] VALUES (getdate(), @@spid, @From, @To, @Subject,
  @Body, @iMsg, @hr, @source, @description, @output, 'Failed at sp_OASetProperty sendusing')
           EXEC @hr =
  sp_OAGetErrorInfo NULL, @source OUT, @description OUT
          
  IF @hr = 0
            
  BEGIN
              
  SELECT @output = '  Source: ' + @source
              
  PRINT  @output
              
  SELECT @output = '  Description: ' + @description
              
  PRINT  @output
                  
  INSERT INTO [dbo].[cdosysmail_failures] VALUES (getdate(), @@spid, @From, @To,
  @Subject, @Body, @iMsg, @hr, @source, @description, @output, 'sp_OAGetErrorInfo for sp_OASetProperty sendusing')
                  
  GOTO send_cdosysmail_cleanup
            
  END
           ELSE
            
  BEGIN
              
  PRINT '  sp_OAGetErrorInfo failed.'
              
  GOTO send_cdosysmail_cleanup
            
  END
         END
    -- This is to configure the Server Name or IP address.
    --
  Replace MailServerName by the name or IP of your SMTP Server.
       EXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/smtpserver").Value', cdoSMTPServerName
       IF @hr <>0
        
  BEGIN
           SELECT
  @hr
           INSERT
  INTO [dbo].[cdosysmail_failures] VALUES (getdate(), @@spid, @From, @To, @Subject,
  @Body, @iMsg, @hr, @source, @description, @output, 'Failed at sp_OASetProperty smtpserver')
           EXEC @hr =
  sp_OAGetErrorInfo NULL, @source OUT, @description OUT
          
  IF @hr = 0
            
  BEGIN
              
  SELECT @output = '  Source: ' + @source
              
  PRINT  @output
              
  SELECT @output = '  Description: ' + @description
              
  PRINT  @output
              
  INSERT INTO [dbo].[cdosysmail_failures] VALUES (getdate(), @@spid, @From, @To,
  @Subject, @Body, @iMsg, @hr, @source, @description, @output, 'sp_OAGetErrorInfo for sp_OASetProperty smtpserver')
                  
  GOTO send_cdosysmail_cleanup
            
  END
           ELSE
            
  BEGIN
              
  PRINT '  sp_OAGetErrorInfo failed.'
              
  GOTO send_cdosysmail_cleanup
            
  END
         END

    -- Save the configurations to the message object.
       EXEC @hr = sp_OAMethod @iMsg, 'Configuration.Fields.Update', null
       IF @hr <>0
        
  BEGIN
           SELECT
  @hr
           INSERT
  INTO [dbo].[cdosysmail_failures] VALUES (getdate(), @@spid, @From, @To, @Subject,
  @Body, @iMsg, @hr, @source, @description, @output, 'Failed at sp_OASetProperty Update')
           EXEC @hr =
  sp_OAGetErrorInfo NULL, @source OUT, @description OUT
          
  IF @hr = 0
            
  BEGIN
              
  SELECT @output = '  Source: ' + @source
              
  PRINT  @output
              
  SELECT @output = '  Description: ' + @description
              
  PRINT  @output
              
  INSERT INTO [dbo].[cdosysmail_failures] VALUES (getdate(), @@spid, @From, @To,
  @Subject, @Body, @iMsg, @hr, @source, @description, @output, 'sp_OAGetErrorInfo for sp_OASetProperty Update')
           GOTO send_cdosysmail_cleanup
            
  END
           ELSE
            
  BEGIN
              
  PRINT '  sp_OAGetErrorInfo failed.'
              
  GOTO send_cdosysmail_cleanup
            
  END
         END

    -- Set the e-mail parameters.
       EXEC @hr = sp_OASetProperty @iMsg, 'To', @To
       IF @hr <>0
        
  BEGIN
           SELECT
  @hr
           INSERT
  INTO [dbo].[cdosysmail_failures] VALUES (getdate(), @@spid, @From, @To, @Subject,
  @Body, @iMsg, @hr, @source, @description, @output, 'Failed at sp_OASetProperty To')
           EXEC @hr =
  sp_OAGetErrorInfo NULL, @source OUT, @description OUT
          
  IF @hr = 0
            
  BEGIN
              
  SELECT @output = '  Source: ' + @source
              
  PRINT  @output
              
  SELECT @output = '  Description: ' + @description
              
  PRINT  @output
              
  INSERT INTO [dbo].[cdosysmail_failures] VALUES (getdate(), @@spid, @From, @To,
  @Subject, @Body, @iMsg, @hr, @source, @description, @output, 'sp_OAGetErrorInfo for sp_OASetProperty To')
                  
  GOTO send_cdosysmail_cleanup
            
  END
           ELSE
            
  BEGIN
              
  PRINT '  sp_OAGetErrorInfo failed.'
              
  GOTO send_cdosysmail_cleanup
            
  END
         END

      
  EXEC @hr = sp_OASetProperty @iMsg, 'From', @From
       IF @hr <>0
        
  BEGIN
           SELECT
  @hr
           INSERT
  INTO [dbo].[cdosysmail_failures] VALUES (getdate(), @@spid, @From, @To, @Subject,
  @Body, @iMsg, @hr, @source, @description, @output, 'Failed at sp_OASetProperty From')
           EXEC @hr =
  sp_OAGetErrorInfo NULL, @source OUT, @description OUT
          
  IF @hr = 0
            
  BEGIN
              
  SELECT @output = '  Source: ' + @source
              
  PRINT  @output
              
  SELECT @output = '  Description: ' + @description
              
  PRINT  @output
              
  INSERT INTO [dbo].[cdosysmail_failures] VALUES (getdate(), @@spid, @From, @To,
  @Subject, @Body, @iMsg, @hr, @source, @description, @output, 'sp_OAGetErrorInfo for sp_OASetProperty From')
                  
  GOTO send_cdosysmail_cleanup
            
  END
           ELSE
            
  BEGIN
              
  PRINT '  sp_OAGetErrorInfo failed.'
              
  GOTO send_cdosysmail_cleanup
            
  END
         END

      
  EXEC @hr = sp_OASetProperty @iMsg, 'Subject', @Subject
       IF @hr <>0
        
  BEGIN
           SELECT
  @hr
           INSERT
  INTO [dbo].[cdosysmail_failures] VALUES (getdate(), @@spid, @From, @To, @Subject,
  @Body, @iMsg, @hr, @source, @description, @output, 'Failed at sp_OASetProperty Subject')
           EXEC @hr =
  sp_OAGetErrorInfo NULL, @source OUT, @description OUT
          
  IF @hr = 0
            
  BEGIN
              
  SELECT @output = '  Source: ' + @source
              
  PRINT  @output
              
  SELECT @output = '  Description: ' + @description
              
  PRINT  @output
              
  INSERT INTO [dbo].[cdosysmail_failures] VALUES (getdate(), @@spid, @From, @To,
  @Subject, @Body, @iMsg, @hr, @source, @description, @output, 'sp_OAGetErrorInfo for sp_OASetProperty Subject')
                  
  GOTO send_cdosysmail_cleanup
            
  END
           ELSE
            
  BEGIN
              
  PRINT '  sp_OAGetErrorInfo failed.'
              
  GOTO send_cdosysmail_cleanup
            
  END
         END

    -- If you are using HTML e-mail, use 'HTMLBody' instead of 'TextBody'.
       EXEC @hr = sp_OASetProperty @iMsg, 'TextBody', @Body
       IF @hr <>0
        
  BEGIN
           SELECT
  @hr
           INSERT
  INTO [dbo].[cdosysmail_failures] VALUES (getdate(), @@spid, @From, @To, @Subject,
  @Body, @iMsg, @hr, @source, @description, @output, 'Failed at sp_OASetProperty TextBody')
           EXEC @hr =
  sp_OAGetErrorInfo NULL, @source OUT, @description OUT
          
  IF @hr = 0
            
  BEGIN
              
  SELECT @output = '  Source: ' + @source
              
  PRINT  @output
              
  SELECT @output = '  Description: ' + @description
              
  PRINT  @output
              
  INSERT INTO [dbo].[cdosysmail_failures] VALUES (getdate(), @@spid, @From, @To,
  @Subject, @Body, @iMsg, @hr, @source, @description, @output, 'sp_OAGetErrorInfo for sp_OASetProperty TextBody')
                  
  GOTO send_cdosysmail_cleanup
            
  END
           ELSE
            
  BEGIN
              
  PRINT '  sp_OAGetErrorInfo failed.'
              
  GOTO send_cdosysmail_cleanup
            
  END
         END

      
  EXEC @hr = sp_OAMethod @iMsg, 'Send', NULL
       IF @hr <>0
        
  BEGIN
           SELECT
  @hr
           INSERT
  INTO [dbo].[cdosysmail_failures] VALUES (getdate(), @@spid, @From, @To, @Subject,
  @Body, @iMsg, @hr, @source, @description, @output, 'Failed at sp_OAMethod Send')
           EXEC @hr =
  sp_OAGetErrorInfo NULL, @source OUT, @description OUT
          
  IF @hr = 0
            
  BEGIN
              
  SELECT @output = '  Source: ' + @source
              
  PRINT  @output
              
  SELECT @output = '  Description: ' + @description
              
  PRINT  @output
              
  INSERT INTO [dbo].[cdosysmail_failures] VALUES (getdate(), @@spid, @From, @To,
  @Subject, @Body, @iMsg, @hr, @source, @description, @output, 'sp_OAGetErrorInfo for sp_OAMethod Send')
                  
  GOTO send_cdosysmail_cleanup
            
  END
           ELSE
            
  BEGIN
              
  PRINT '  sp_OAGetErrorInfo failed.'
              
  GOTO send_cdosysmail_cleanup
            
  END
         END


    -- Do some error handling after each step if you have to.
    --
  Clean up the objects created.
        send_cdosysmail_cleanup:
    If
  (@iMsg IS NOT NULL) -- if @iMsg is NOT NULL then destroy it
    BEGIN
        EXEC
  @hr=sp_OADestroy @iMsg

        --
  handle the failure of the destroy if needed
        IF
  @hr <>0
            
  BEGIN
            select
  @hr
                    INSERT
  INTO [dbo].[cdosysmail_failures] VALUES (getdate(), @@spid, @From, @To, @Subject,
  @Body, @iMsg, @hr, @source, @description, @output, 'Failed at sp_OADestroy')
                  
  EXEC @hr = sp_OAGetErrorInfo NULL, @source OUT, @description OUT

            -- if sp_OAGetErrorInfo
  was successful, print errors
            IF
  @hr = 0
            BEGIN
                SELECT
  @output = '  Source: ' + @source
                    PRINT  @output
                    SELECT
  @output = '  Description: ' + @description
                    PRINT  @output
                INSERT
  INTO [dbo].[cdosysmail_failures] VALUES (getdate(), @@spid, @From, @To, @Subject,
  @Body, @iMsg, @hr, @source, @description, @output, 'sp_OAGetErrorInfo for sp_OADestroy')
            END

            -- else sp_OAGetErrorInfo
  failed
            ELSE
            BEGIN
                PRINT
  '  sp_OAGetErrorInfo failed.'
                    RETURN
            END
        END
    END
    ELSE
    BEGIN
        PRINT
  ' sp_OADestroy skipped because @iMsg is NULL.'
        INSERT INTO [dbo].[cdosysmail_failures]
  VALUES (getdate(), @@spid, @From, @To, @Subject, @Body, @iMsg, @hr, @source,
  @description, @output, '@iMsg is NULL, sp_OADestroy skipped')
            RETURN

     END


--Next, use the stored procedure that you created and provide the correct parameters.
  declare @Body varchar(4000)
   select @Body =
  'This is a Test Message'
   exec sp_send_cdosysmail ''dummyuserreceipient@gmail.com',''dummyuserreceipient@gmail.com','Test of CDOSYS',@Body

--End SP # 3 Send Mail through SQL

Common Context

This section describes the information that is available in the InputParameters and OutputParameters properties of IPluginExecutionContext. To understand the nature of this information, the relationship between an application making Web service calls and the context that a plug-in receives because of those calls must be described.

The following source code sample shows some typical calls to the Microsoft Dynamics CRM Web service.

[C#]
// Set up the CRM Service.
CrmService service = new CrmService();
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the account object.
account account = new account();
account.name = "Fourth Coffee";

// Create the target object for the request.
TargetCreateAccount target = new TargetCreateAccount();
target.Account = account;

// Create the request object.
CreateRequest createRequest = new CreateRequest();
createRequest.Target = target;

// Execute the request.
CreateResponse createResponse = (CreateResponse)service.Execute(createRequest);
Guid accountID = createResponse.id;


Although this example uses Request/Response messages and the Execute method, you can use the other CrmService methods such as Create, Update, and Deleteto work with your business entities. The Microsoft Dynamics CRM system takes the information from those CrmService methods and transforms it intoRequest/Response messages that are processed by the event execution pipeline. The information on input/output parameters that follows still applies.

The following documentation relates the Web service calls in the example code to the context that a plug-in is passed. For the examples described herein, assume that a plug-in is registered to execute during the post-event of account creation so that the sample code causes the plug-in to execute.

Input Parameters


The InputParameters property bag contains all the information specified in the Request class whose message caused the plug-in to execute. The keys used to obtain values from the property bag are named according to the name of the Request class instance properties. An example of this is described next.

In the code sample, an account is created by using the CreateRequest class. The Target property of CreateRequest refers to a TargetCreateAccount object, which refers to an account object. This is shown in the following diagram.

CreateRequest and associated classes

When the plug-in is executed, the information that is in the Request object is passed to the plug-in in the InputParameters property of IPluginExecutionContext. For this example, the InputParameters property bag contains two key/value pairs. The first key is named "Target" and its associated value is the target of the request, namely the account object. The second key is named "OptionalParameters" and its associated value is the OptionalParameters instance property that is defined in the Request class from which CreateRequest is derived. In the sample code, no optional parameters were added to the CreateRequest, so that the optional parameters value in InputParameters is null.

The following figure shows an example plug-in that is being debugged in Visual Studio 2005.

Viewing the InputParameters property bag in a debugger

The figure shows the contents of the InputParameters property bag that has been passed in the context to the plug-in. Two key/value pairs are shown: Target andOptionalParameters.

The recommended way to specify these key names in code is to use the predefined names in the ParameterName class. For example, you can useParameterName.Target instead of "Target". Doing this reduces the possibility of a typing mistake in the key name when coding.

InputParameters contains Object types. Therefore, you must cast the property bag values to their appropriate types. The following sample plug-in code shows how to obtain the original account object.

[C#] DynamicEntity entity = (DynamicEntity)context.InputParameters.Properties[ParameterName.Target]

The account attributes can then be accessed in the plug-in.

[C#] string accountName = entity["name"]

Note The dynamic entity obtained from the InputParameters of the context contains only those attributes that are set to a value or null.

Output Parameters


For a post-event, the OutputParameters property bag contains the result of the core operation that is returned in the Response message. The key names that are used to access the values in the OutputParameters property bag match the names of the Response class instance properties.

CreateResponse class

In the source code example, the CreateResponse object contains the GUID of the new account instance after the Execute method is called. A post-event registered plug-in can obtain the GUID from the OutputParameters property bag by using the "id" key name or ParameterName.Id.

//[C#] 
Guid regardingobjectid = (Guid)context.OutputParameters[ParameterName.Id]

If a plug-in is registered for a pre-event, the OutputParameters property bag would not contain a value for the "id" key because the core operation would not yet have occurred.

CRM 2011 Visualizations

Visualizations - Charts


Visualizations - Dashboards

How to use the RemoveItemCampaign message

Removes an item from a campaign.

//# The following code example shows how to use the RemoveItemCampaign message.

// Set up the CRM service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the request object.
RemoveItemCampaignRequest remove = new RemoveItemCampaignRequest();

// Set the ID of the campaign.
remove.CampaignId =  new Guid("d7f33457-660e-de11-bf40-00155da4c706");

// Set the ID of the campaign item to remove.
remove.EntityId =  new Guid("6e47aeb7-c30d-de11-bf40-00155da4c706");

// Execute the request.
RemoveItemCampaignResponse removed = 
(RemoveItemCampaignResponse)service.Execute(remove);                                     




Send Mail through SQL (using CDONTS)

SQL Code Snippets to send emailBelow are snippets which can be used to send emails from SQL Server

--Start SP # 2 Send Mail through SQL (using CDONTS)
CREATE PROCEDURE [dbo].[usp_send_cdontsmail]
@From varchar(100),
@To
  varchar(100),
@Subject varchar(100),
@Body varchar(4000),
@CC
  varchar(100) = null,
@BCC varchar(100) = null
AS
Declare @MailID
  int
Declare @hr int
EXEC @hr = sp_OACreate 'CDONTS.NewMail', @MailID OUT
EXEC @hr = sp_OASetProperty @MailID, 'From',@From
EXEC @hr = sp_OASetProperty @MailID, 'Body', @Body
EXEC @hr = sp_OASetProperty @MailID, 'BCC',@BCC
EXEC @hr = sp_OASetProperty @MailID, 'CC', @CC
EXEC @hr = sp_OASetProperty @MailID, 'Subject', @Subject
EXEC @hr = sp_OASetProperty @MailID, 'To', @To
EXEC @hr = sp_OAMethod @MailID, 'Send', NULL
EXEC @hr = sp_OADestroy @MailID

exec usp_send_cdontsmail
  ''dummyuserreceipient@gmail.com',''dummyuserreceipient@gmail.com','Test of CDONTS','It works'

--End SP # 2 Send Mail through SQL

Removes a member from a list

Removes a member from a list.

//# The following code example shows how to use the RemoveMemberList message.

// Set up the CRM service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the request object.
RemoveMemberListRequest remove = new RemoveMemberListRequest();

// Set the ID of the list.
remove.ListId = new Guid("18ECA720-493E-4800-BBFD-638BD54EB325");
// Set the ID of the list item to remove.
remove.EntityId = new Guid("2B951FBC-1C56-4430-B23B-20A1349068F3");

// Execute the request.
RemoveMemberListResponse removed = (RemoveMemberListResponse)service.Execute(remove);




Retrive Dynamic Entity based on Entity name & Guid

public DynamicEntity retriveEntity(string EntityName, string recordGuid)
{
TargetRetrieveDynamic targetRetrieve = new TargetRetrieveDynamic();

// Set the properties of the target.
targetRetrieve.EntityName = "contact";
targetRetrieve.EntityId = new Guid(rec_guid);

// Create the request object.
RetrieveRequest retrieve = new RetrieveRequest();

// Set the properties of the request object.
retrieve.Target = targetRetrieve;
retrieve.ColumnSet = new AllColumns();

// Indicate that the BusinessEntity should be retrieved as a DynamicEntity.
retrieve.ReturnDynamicEntities = true;

// Execute the request.
RetrieveResponse retrieved = (RetrieveResponse)_svc.Execute(retrieve);

// Extract the DynamicEntity from the request.
DynamicEntity R_entity = (DynamicEntity)retrieved.BusinessEntity;
return R_entity;
}




Publish the customizations for the specified entities

Publish the customizations for the specified entities.

//# The following code example shows how to use the PublishXml message.

// Set up the CRM service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the request.
PublishXmlRequest request = new PublishXmlRequest();

request.ParameterXml = @"<importexportxml>
<entities>
<entity>account</entity>
<entity>contact</entity>
</entities>
<nodes />
<securityroles />
<settings />
<workflows />
</importexportxml>";

// Execute the request.
PublishXmlResponse response = (PublishXmlResponse)service.Execute(request);




CRM 2011 UX Extensibility

UX Extensibility - Intro


UX Extensibility - WebResources


UX Extensibility - Client Scripting


UX Extensibility - Filtered Lookups

How to convert a fax to a task

This sample code shows how to convert a fax to a task. The code first creates an incoming Fax activity, and then converts it to a Follow-up Task with a due date a week after it was received.

[C#]
using System;
using Microsoft.Crm.Sdk.Utility;

namespace Microsoft.Crm.Sdk.HowTo
{
// Microsoft Dynamics CRM namespaces.
using CrmSdk;

/// 
/// This sample shows how to convert a fax into a task.
/// 
public class ConvertFaxToTask
{
static void Main(string[] args)
{
// TODO: Change the server URL and organization to match your Microsoft Dynamics CRM server and Microsoft Dynamics CRM organization.
ConvertFaxToTask.Run("http://localhost:5555", "CRM_Organization");
}

public static bool Run(string crmServerUrl, string orgName)
{
#region Setup Data Required for this sample.

bool success = false;

#endregion

try
{
// Set up the CRM service.
CrmService service = CrmServiceUtility.GetCrmService(crmServerUrl, orgName);
service.PreAuthenticate = true;

// Get the current user.
WhoAmIRequest userRequest = new WhoAmIRequest();
WhoAmIResponse user = (WhoAmIResponse)service.Execute(userRequest);

// Create the fax object.
fax fax = new fax();

// Set the properties of the fax.
fax.subject = "Test Fax";
fax.description = "New Fax";

// Create the party sending and receiving the fax.
activityparty party = new activityparty();

// Set the properties of the activity party.
party.partyid = new Lookup();
party.partyid.type = EntityName.systemuser.ToString();
party.partyid.Value = user.UserId;

// The party sends and receives the fax.
fax.from = new activityparty[] { party };
fax.to = new activityparty[] { party };

// Create the fax.
Guid createdFaxId = service.Create(fax);

// Retrieve the created fax.
// Be aware that using AllColumns may adversely affect
// performance and cause unwanted cascading in subsequent 
// updates. A best practice is to retrieve the least amount of 
// data required.
fax newFax = (fax)service.Retrieve(EntityName.fax.ToString(), createdFaxId, new AllColumns());

// Create the task object.
task task = new task();

// Set the properties of the task.
task.subject = "Follow Up: " + newFax.subject;

// Set the due date of the task.
task.scheduledend = new CrmDateTime();

// Get the date that the fax was received.
CrmDateTime endDate = newFax.createdon;

// Set the due date of the task to one week later.
task.scheduledend.Value = endDate.UniversalTime.AddDays(7).ToString();

// Create the task.
Guid createdTaskId = service.Create(task);

#region check success

if (createdTaskId != Guid.Empty)
{
success = true;
}

#endregion

#region Remove Data Required for this Sample

service.Delete(EntityName.fax.ToString(), createdFaxId);
service.Delete(EntityName.task.ToString(), createdTaskId);

#endregion
}
catch (System.Web.Services.Protocols.SoapException)
{
// Add your error handling code here.
}

return success;
}
}
}





How to merges the information from two instances

Merges the information from two entity instances of the same type.

//# The following code example shows how to use the Merge message.

// Set up the CRM service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0; 
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the target for the request.
TargetMergeAccount target = new TargetMergeAccount();
// EntityId is the GUID of the account that is being merged into.
target.EntityId = new Guid("2B951FBC-1C56-4430-B23B-20A1349068F3");

// Create the request.
MergeRequest merge = new MergeRequest();
// SubordinateId is the GUID of the account merging.
merge.SubordinateId = new Guid("AD618DB2-F0DB-4A6A-8C4B-2F2213EAA38E");
merge.Target = target;
merge.PerformParentingChecks = false;

account updateContent = new account();
updateContent.address1_line1 = "test";
merge.UpdateContent = updateContent;


// Execute the request.
MergeResponse merged = (MergeResponse)service.Execute(merge);




CRM 2011 Solutions

Solutions - Data Modeling


Solutions - Introduction


Solutions - Managed & UnManaged


Solutions - Publishing

Retrieve a List of Messages and Entities that Support Plug-ins

The following code displays a list of messages and entities that support plug-ins. This sample code can be found in the following file in the SDK download:

Use the Methods in the Outlook SDK Assembly

This sample shows how to use the methods and properties in the assembly Microsoft.Crm.Outlook.Sdk. Before running this sample, you should start Microsoft Dynamics CRM for Outlook.

send mail through SQL

SQL Code Snippets to send emailBelow are snippets which can be used to send emails from SQL Server Note: you need to set the email parameters like the SMTP server e.t.c. wherever mentioned.

--Start SP # 1 Send Mail through SQL

CREATE PROCEDURE usp_SMTPMail
    @SenderName varchar(100),
    @SenderAddress varchar(100),
    @RecipientName varchar(100),
    @RecipientAddress varchar(100),
    @Subject varchar(200),
    @Body varchar(8000),
    @MailServer varchar(100) = '' --Specify the smtpserver with domain here
AS    
SET nocount on
--Set up the procedure and the parameters. 
    declare @oMail int --Object reference
    declare @resultcode int
    EXEC @resultcode = sp_OACreate 'SMTPsvg.Mailer', @oMail OUT
--sp_OACreate has an output parameter that returns a reference to the object instance, this is used to assign parameters. The result code is 0 for success. 
    if @resultcode = 0
    BEGIN
        EXEC @resultcode = sp_OASetProperty @oMail, 'RemoteHost',  @mailserver
        EXEC @resultcode = sp_OASetProperty @oMail, 'FromName', @SenderName
        EXEC @resultcode = sp_OASetProperty @oMail, 'FromAddress',  @SenderAddress
--sp_OASetProperty takes the reference to the object (@oMail), takes the property name and sets the value. 
EXEC @resultcode = sp_OAMethod @oMail, 'AddRecipient', NULL, @RecipientName,  @RecipientAddress
--sp_OAMethod calls a method of the object. We pass the object reference, then the method name "AddRecipient". The next parameter is for returning a value from a method. In this case I don't want one so I pass it a null. After that I pass the parameters of the method.
  The "AddRecipient" method has Name and Email Address parameters so I am passing them in. 
        EXEC
  @resultcode = sp_OASetProperty @oMail, 'Subject', @Subject
        EXEC @resultcode
  = sp_OASetProperty @oMail, 'BodyText', @Body
        EXEC @resultcode =
  sp_OAMethod @oMail, 'SendMail', NULL
--Similar code here, we set the subject and message body, then call the "SendMail"
  method which sends the email. 
        EXEC sp_OADestroy @oMail
    END    
    SET
  nocount off
--sp_OADestory cleans up and destroys the reference to the object. The object is
  meant to be destroyed when the procedure finishes, but I always like to clean
  up after myself. 


--To use this procedure, call it like this. 
exec usp_SMTPMail @SenderName='me', @SenderAddress='dummyuser@gmail.com', 
@RecipientName = 'dummyuserreceipient@gmail.com', @RecipientAddress = 'dummyuserreceipient@gmail.com', 
@Subject='SQL Test', @body='Hello, this is a test email from SQL Server'

--End SP # 1 Send Mail through SQL

Use Filtered Views in CRM 4

This sample shows how to use filtered views to retrieve all invoices where the lead source was "Employee Referral".
Note    Access to the SQL database is not supported in Microsoft Dynamics CRM Online
Example
The following code shows how to connect to the Microsoft Dynamics CRM SQL database directly and query this database securely using a filtered view.

Use a Join to Retrieve Activities by Participant

This sample demonstrates doing a simple JOIN to the activityparty entity using a query expression.


Plug-in Context in CRM 4

All plug-ins must implement the IPlugin interface. The IPlugin interface defines an Execute method, which takes an IPluginExecutionContext parameter. When a system event is fired for which a plug-in is registered, the system creates and populates the context. The system then calls the plug-in's Execute method, passing in the context as a parameter.
At run time, the execution context is passed to each registered plug-in in the pipeline when they are executed. Each plug-in in the execution pipeline is able to modify writable properties in the context. For example, given a plug-in registered for a pre-event and another plug-in registered for a post-event, the post-event plug-in can receive a context that has been modified by the pre-event plug-in. The same situation applies to plug-ins that are registered within the same stage. 
The context contains information that describes the run-time environment that the plug-in is executing in, information related to the execution pipeline, and entity business information.


All the properties in the class are read-only. However, your plug-in can modify the contents of those properties that are of type PropertyBag.
There are two methods provided in IPluginExecutionContext: CreateCrmService and CreateMetadataService. We recommend that plug-in code should create an instance of the Microsoft Dynamics CRM Web services through these methods. The platform provides the correct Web service URLs and network credentials for you when you use these methods. However, do not use these methods if you are writing code for a plug-in in that is used in a child pipeline. In a child pipeline, you must instantiate the CrmService or MetadataService manually. For examples about how to call these methods, see the plug-in code provided in the SDK samples.




Create a Campaign

The following code example demonstrates how to create a campaign and retrieve the members from the marketing list that is used during a bulk operation, such as a distributing phone activity.



using System;
using CrmSdk;
using Microsoft.Crm.Sdk.Utility;
using System.Web.Services.Protocols;

namespace Microsoft.Crm.Sdk.Reference.BulkOperation
{
public class RetrieveMembersBulkOperation
{

public RetrieveMembersBulkOperation()
{

}

public static bool Run(string crmServerUrl, string orgName)
{
bool success = false;

// Set up the CRM Service.
CrmService service = Microsoft.Crm.Sdk.Utility.CrmServiceUtility.GetCrmService(crmServerUrl, orgName);
service.PreAuthenticate = true;

#region Setup Data Required for this Sample

// Create a campaign.
campaign sampleCampaign = new campaign();
sampleCampaign.name = "SDK Sample Campaign";

Guid createdCampaignId = service.Create(sampleCampaign);

// Create a campaign activity.
campaignactivity sampleActivity = new campaignactivity();
sampleActivity.regardingobjectid = new Lookup();
sampleActivity.regardingobjectid.type = EntityName.campaign.ToString();
//sampleActivity.regardingobjectid.Value = createdCampaign.id;
sampleActivity.regardingobjectid.Value = createdCampaignId;
sampleActivity.subject = "Sample Campaign Activity";
sampleActivity.channeltypecode = new Picklist(1); // 1 == phone

Guid createdCampaignActivityId = service.Create(sampleActivity);

// Create a list to add to the activity.
list marketingList = new list();
marketingList.listname = "SDK Sample Marketing List";
marketingList.createdfromcode = new Picklist();
marketingList.createdfromcode.Value = 1; // 1 == account

Guid createdMarketingListId = service.Create(marketingList);

// Create an account to add to the marketing list.
// This will be the name returned by the RetrieveMembersBulkOperation message.
account sampleAccount = new account();
sampleAccount.name = "Fourth Coffee";

Guid createdAccountId = service.Create(sampleAccount);

AddMemberListRequest addAccountRequest = new AddMemberListRequest();
addAccountRequest.ListId = createdMarketingListId;
addAccountRequest.EntityId = createdAccountId;

service.Execute(addAccountRequest);

// First, associate the list with the campaign.
AddItemCampaignRequest addListToCampaignRequest = new AddItemCampaignRequest();
addListToCampaignRequest.CampaignId = createdCampaignId;
addListToCampaignRequest.EntityName = EntityName.list;
addListToCampaignRequest.EntityId = createdMarketingListId;

AddItemCampaignResponse createdCampaignItem = (AddItemCampaignResponse)service.Execute(addListToCampaignRequest);

// Then, associate the list with the campaign activity.
AddItemCampaignActivityRequest addListToCampaignActivityRequest = new AddItemCampaignActivityRequest();
addListToCampaignActivityRequest.CampaignActivityId = createdCampaignActivityId;
addListToCampaignActivityRequest.EntityName = EntityName.list;
addListToCampaignActivityRequest.ItemId = createdMarketingListId;

AddItemCampaignActivityResponse createdCampaignActivityItem = (AddItemCampaignActivityResponse)service.Execute(addListToCampaignActivityRequest);

#endregion

// Create a phone activity to be distributed (bulk operation).
phonecall samplePhoneCall = new phonecall();
samplePhoneCall.subject = "Sample phone call to distribute to a marketing list.";

// The owner property is REQUIRED.
WhoAmIRequest systemUserRequest = new WhoAmIRequest();
WhoAmIResponse systemUser = (WhoAmIResponse)service.Execute(systemUserRequest);

// Execute a bulk operation.
DistributeCampaignActivityRequest distributeCampaignRequest = new DistributeCampaignActivityRequest();
distributeCampaignRequest.Activity = samplePhoneCall;
distributeCampaignRequest.CampaignActivityId = createdCampaignActivityId;
distributeCampaignRequest.Propagate = true;
distributeCampaignRequest.SendEmail = false;
distributeCampaignRequest.Owner = new Moniker();
distributeCampaignRequest.Owner.Id = systemUser.UserId;
distributeCampaignRequest.Owner.Name = EntityName.systemuser.ToString();

DistributeCampaignActivityResponse distributeCampaignResponse = (DistributeCampaignActivityResponse)service.Execute(distributeCampaignRequest);

// Execute the request.
RetrieveMembersBulkOperationRequest getMembers = new RetrieveMembersBulkOperationRequest();
getMembers.BulkOperationId = distributeCampaignResponse.BulkOperationId;
getMembers.BulkOperationSource = BulkOperationSource.CampaignActivity;
getMembers.EntitySource = EntitySource.Account;
getMembers.ReturnDynamicEntities = false;

RetrieveMembersBulkOperationResponse membersResponse = (RetrieveMembersBulkOperationResponse)service.Execute(getMembers);

#region check success

ColumnSet returnSet = new ColumnSet();
returnSet.Attributes = new string[] { "activityid", "statuscode" };

// Wait for the bulk operation to complete.
bulkoperation retrieveMembersOperation = service.Retrieve(EntityName.bulkoperation.ToString(), distributeCampaignResponse.BulkOperationId, returnSet) as bulkoperation;
int secondsTicker = 20;
while (secondsTicker > 0 && retrieveMembersOperation.statuscode.Value != BulkOperationStatus.Completed)
{
retrieveMembersOperation = service.Retrieve(EntityName.bulkoperation.ToString(), distributeCampaignResponse.BulkOperationId, returnSet) as bulkoperation;
System.Threading.Thread.Sleep(1000);
secondsTicker--;
}

// Verify that the account created and added to the marketing list was returned.
if (retrieveMembersOperation.statuscode.Value == BulkOperationStatus.Completed && membersResponse.BusinessEntityCollection.BusinessEntities.Length == 1)
{
account verifyAccount = membersResponse.BusinessEntityCollection.BusinessEntities[0] as account;
if (verifyAccount.accountid.Value == createdAccountId)
{
success = true;
}
}

#endregion

#region Remove Data Required for this Sample

// Query for all phonecall activities created so that they can be removed.
ColumnSet resultSet = new ColumnSet();
resultSet.Attributes = new string[] {"activityid"};

ConditionExpression phoneCallCondition = new ConditionExpression();
phoneCallCondition.AttributeName = "regardingobjectid";
phoneCallCondition.Operator = ConditionOperator.Equal;
phoneCallCondition.Values = new object[] {createdCampaignActivityId};

FilterExpression regardingObjectFilter = new FilterExpression();
regardingObjectFilter.Conditions = new ConditionExpression[] { phoneCallCondition };
regardingObjectFilter.FilterOperator = LogicalOperator.And;

QueryExpression phoneCallQuery = new QueryExpression();
phoneCallQuery.ColumnSet = resultSet;
phoneCallQuery.Criteria = regardingObjectFilter;
phoneCallQuery.EntityName = EntityName.phonecall.ToString();

BusinessEntityCollection phoneCalls = service.RetrieveMultiple(phoneCallQuery);

foreach (phonecall aPhoneCall in phoneCalls.BusinessEntities)
{
service.Delete(EntityName.phonecall.ToString(), aPhoneCall.activityid.Value);
}

// Remove the campaign activity.
service.Delete(EntityName.campaignactivity.ToString(), createdCampaignActivityId);

// Remove the campaign.
service.Delete(EntityName.campaign.ToString(), createdCampaignId);

// Remove the marketing list.
service.Delete(EntityName.list.ToString(), createdMarketingListId);

// Remove the account.
service.Delete(EntityName.account.ToString(), createdAccountId);

#endregion

return success;
}
}
}






get field data from CRM 4

    
// get field data from crm 4.0 entity

public string getLookup(string _prop)
{
Lookup lkp = (Lookup)entity[_prop];
return lkp.name;
}

internal string getPicklist(string _prop)
{
Picklist pick = (Picklist)entity[_prop];
return pick.name;
}

public string getDate(string _prop)
{
CrmDateTimeProperty cdp = new CrmDateTimeProperty(_prop, (CrmDateTime)entity.Properties[_prop]);
return cdp.Value.date;
}

public string getBool(string _prop)
{
string ret = "";
try
{
CrmBooleanProperty CBP = new CrmBooleanProperty(_prop, (CrmBoolean)entity.Properties[_prop]);
ret = CBP.Value.Value.ToString();
}
catch (Exception ex)
{
ret = "";
}
return ret;
}

internal string getOwner(string _prop)
{
Owner own = (Owner)entity[_prop];
return own.name;
}

public string getData(string _prop)
{
string ret = "";
string type = null;

try
{
type = entity.Properties[_prop].GetType().ToString();
System.Diagnostics.Debug.Print("TYPE( {0} ):= {1}",_prop, type);
}
catch (Exception e)
{
type = e.Message;
ret = e.Message;
return ret;
}

if (type == "Microsoft.Crm.Sdk.Owner")
{
ret = ret = getOwner(_prop);
}
else if (type == "Microsoft.Crm.Sdk.CrmBoolean")
{
ret = getBool(_prop);
}
else if(type == "System.String")
{
//StringProperty sp = new StringProperty(_prop, (string)entity.Properties[_prop]);
ret = entity.Properties[_prop].ToString();
}
else if (type == "Microsoft.Crm.Sdk.Lookup")
{
ret = getLookup(_prop);
}
else if (type == "Microsoft.Crm.Sdk.Picklist")
{
ret = getPicklist(_prop);
}

return ret;
}




Create a Marketing Automation List

The following code example demonstrates how to create a Marketing Automation list and add a member to it.




using System;
using CrmSdk;
using Microsoft.Crm.Sdk.Utility;

namespace Microsoft.Crm.Sdk.HowTo
{
///
/// Summary description for MarketingAutomationListCreation.
///

public class MarketingAutomationListCreation
{
static void Main(string[] args)
{
// TODO: Change the server URL and Organization to match your CRM Server and CRM Organization
MarketingAutomationListCreation.Run("http://localhost:5555", "CRM_SDK");
}

public static bool Run(string crmServerUrl, string orgName)
{
// Set up the CRM Service.
CrmService service = CrmServiceUtility.GetCrmService(crmServerUrl, orgName);

#region Setup Data Required for this Sample
account accountCreate = new account();
accountCreate.name = "Fourth Coffee";
accountCreate.description = "Coffee House";

Guid createdId = service.Create(accountCreate);
#endregion

#region Create List

list autoList = new list();
autoList.listname = "Test List";
autoList.membertype = new CrmNumber();
autoList.membertype.Value = 1;
autoList.createdfromcode = new Picklist();
autoList.createdfromcode.Value = 1;

Guid listId = service.Create(autoList);

#endregion

#region Add Member to List
AddMemberListRequest addRequest = new AddMemberListRequest();
addRequest.EntityId = createdId;
addRequest.ListId = listId;

AddMemberListResponse response = (AddMemberListResponse) service.Execute(addRequest);
#endregion

#region check success

bool success = false;

if (response.Id != Guid.Empty)
{
success = true;
}
#endregion

#region Remove Data Required for this Sample
service.Delete(EntityName.account.ToString(), createdId);
service.Delete(EntityName.list.ToString(), listId);
#endregion

return success;
}
}
}

Schedule a Resource

This sample code shows how to schedule a resource with the following scenario. A plumber and van need to be scheduled to investigate and fix a leak at a customer site. The earliest available appointment needs to be made. In order for this to be accomplished, all preliminary records must be created. The default 24-hour calendars will be used. No sites are created for this sample.




using System;
using CrmSdk;
using Microsoft.Crm.Sdk.Utility;

namespace Microsoft.Crm.Sdk.HowTo
{
///
/// This sample shows how to schedule a resource.
///

public class ServiceManagement
{
public static bool Run(string crmServerUrl, string orgName)
{
// Set up the CRM Service.
CrmService service = CrmServiceUtility.GetCrmService(crmServerUrl, orgName);

#region Setup Data Required for this Sample
bool success = false;

#endregion

try
{
// Get the current user's information.
WhoAmIRequest userRequest = new WhoAmIRequest();
WhoAmIResponse user = (WhoAmIResponse) service.Execute(userRequest);

// Create the van resource.
equipment van = new equipment();
van.name = "Van 1";
van.timezonecode = new CrmNumber();
van.timezonecode.Value = 1;
van.businessunitid = new Lookup();
van.businessunitid.type = EntityName.businessunit.ToString();
van.businessunitid.Value = user.BusinessUnitId;

// Create the van object.
Guid vanId = service.Create(van);

// Create the plumber resource group.
constraintbasedgroup group = new constraintbasedgroup();
group.businessunitid = new Lookup();
group.businessunitid.type = EntityName.businessunit.ToString();
group.businessunitid.Value = user.BusinessUnitId;
group.name = "Plumber with Van 1";
System.Text.StringBuilder builder = new System.Text.StringBuilder("");
builder.Append("");
builder.Append("");
builder.Append("resource[\"Id\"] == ");
builder.Append(user.UserId.ToString("B"));
builder.Append(" || resource[\"Id\"] == ");
builder.Append(vanId.ToString("B"));
builder.Append("");
builder.Append("");
builder.Append("");
builder.Append("
");
builder.Append("
");
builder.Append("
");
builder.Append("
");
group.constraints = builder.ToString();
group.grouptypecode = new Picklist();
group.grouptypecode.Value = 0;

Guid groupId = service.Create(group);

// Create the resource specification.
resourcespec spec = new resourcespec();
spec.businessunitid = new Lookup();
spec.businessunitid.type = EntityName.businessunit.ToString();
spec.businessunitid.Value = user.BusinessUnitId;
spec.objectiveexpression = @"

udf ""Random""(factory,resource,appointment,request,leftoffset,rightoffset)









";
spec.requiredcount = new CrmNumber();
spec.requiredcount.Value = 1;
spec.name = "Test Spec";
spec.groupobjectid = new UniqueIdentifier();
spec.groupobjectid.Value = groupId;

Guid specId = service.Create(spec);

// Create the plumber required resource object.
RequiredResource plumberReq = new RequiredResource();
plumberReq.ResourceId = user.UserId;// assume current user is the plumber
plumberReq.ResourceSpecId = specId;

// Create the van required resource object.
RequiredResource vanReq = new RequiredResource();
vanReq.ResourceId = vanId;
vanReq.ResourceSpecId = specId;

// Create the service.
service plumberService = new service();
plumberService.name = "Plumber1";
plumberService.duration = new CrmNumber();
plumberService.duration.Value = 60;
plumberService.initialstatuscode = new Status();
plumberService.initialstatuscode.Value = 1;
plumberService.granularity = "FREQ=MINUTELY;INTERVAL=15;";
plumberService.resourcespecid = new Lookup();
plumberService.resourcespecid.type = EntityName.resourcespec.ToString();
plumberService.resourcespecid.Value = specId;
plumberService.strategyid = new Lookup();
// This is a known GUID for the default strategy.
plumberService.strategyid.Value = new Guid("07F7DC72-1671-452D-812C-7172D3CA881F");

Guid plumberServiceId = service.Create(plumberService);

// Create the appointment request.
AppointmentRequest appointmentReq = new AppointmentRequest();
appointmentReq.RequiredResources = new RequiredResource[] {vanReq};
appointmentReq.Direction = SearchDirection.Forward;
appointmentReq.Duration = 60;
appointmentReq.NumberOfResults = 10;
appointmentReq.NumberOfResults = 1;
appointmentReq.ServiceId = plumberServiceId;

// The search window describes the time when the resouce can be scheduled.
// It must be set.
appointmentReq.SearchWindowStart = new CrmDateTime();
appointmentReq.SearchWindowStart.Value = DateTime.Now.ToUniversalTime().ToString();
appointmentReq.SearchWindowEnd = new CrmDateTime();
appointmentReq.SearchWindowEnd.Value = DateTime.Now.AddDays(7).ToUniversalTime().ToString();
appointmentReq.UserTimeZoneCode = 1;

// Create the request object.
SearchRequest search = new SearchRequest();

// Set the properties of the request object.
search.AppointmentRequest = appointmentReq;

// Execute the request.
SearchResponse searched = (SearchResponse)service.Execute(search);

#region check success

if (searched.SearchResults.Proposals.Length > 0)
{
success = true;
}

#endregion

#region Remove Data Required for this Sample

service.Delete(EntityName.service.ToString(), plumberServiceId);
service.Delete(EntityName.equipment.ToString(), vanId);

#endregion
}
catch (System.Web.Services.Protocols.SoapException ex)
{
// Add your error handling code here.
Console.WriteLine(ex.Detail.InnerText);
success = false;
}

return success;
}
}
}





Send email through cdosys

using System;

namespace CdoSys
{
 class Class1
 {
  static void Main(string[] args)
  {
   try 
   {   
    CDO.Message oMsg = new CDO.Message();
    CDO.IConfiguration iConfg; 

    iConfg = oMsg.Configuration;

    ADODB.Fields oFields;
    oFields = iConfg.Fields;       

    // Set configuration.
    ADODB.Field oField = oFields["http://schemas.microsoft.com/cdo/configuration/sendusing"];
                        
    //TODO: To send by using the smart host, uncomment the following lines:
    //oField.Value = CDO.CdoSendUsing.cdoSendUsingPort;
    //oField = oFields["http://schemas.microsoft.com/cdo/configuration/smtpserver"];
    //oField.Value = "smarthost";

    // TODO: To send by using local SMTP service. 
    //oField = oFields["http://schemas.microsoft.com/cdo/configuration/sendusing"];
    //oField.Value = 1;  

    oFields.Update();

    // Set common properties from message.

    //TODO: To send text body, uncomment the following line: 
    //oMsg.TextBody = "Hello, how are you doing?";
   

    //TODO: To send HTML body, uncomment the following lines:
    //String sHtml;
    //sHtml = "\n" + 
    // "\n" +
    // "Sample GIF\n" +
    // "\n" +
    // "

\n" + // "

Inline graphics

\n" + // "\n" + // ""; //oMsg.HTMLBody = sHtml; //TOTO: To send WEb page in an e-mail, uncomment the following lines and make changes in TODO section. //TODO: Replace with your preferred Web page //oMsg.CreateMHTMLBody("http://www.microsoft.com", // CDO.CdoMHTMLFlags.cdoSuppressNone, // "", ""); oMsg.Subject = "Test SMTP"; //TODO: Change the To and From address to reflect your information. oMsg.From = "someone@example.com"; oMsg.To = "someone@example.com"; //ADD attachment. //TODO: Change the path to the file that you want to attach. oMsg.AddAttachment("C:\\Hello.txt", "", ""); oMsg.AddAttachment("C:\\Test.doc", "", ""); oMsg.Send(); } catch (Exception e) { Console.WriteLine("{0} Exception caught.", e); } return; } } }

Retrieve the Roles for a User

This sample shows how to build a QueryExpression to for use with RetrieveMultiple to find all the roles for a user. To do this, you have to build a query for roles where you join 'role' to 'systemuserroles', and then join systemuserroles' to 'systemuser' and add a condition where systemuser.systemuserid equals the attribute UserId.




// Retrieve the GUID of the logged on user.
WhoAmIRequest whoReq = new WhoAmIRequest();
WhoAmIResponse whoResp = (WhoAmIResponse) service.Execute(whoReq);
Guid userid = whoResp.UserId;

// Create a QueryExpression.
QueryExpression qe = new QueryExpression();
qe.EntityName = "role";
// Be aware that using AllColumns may adversely affect
// performance and cause unwanted cascading in subsequent
// updates. A best practice is to retrieve the least amount of
// data required.
qe.ColumnSet = new AllColumns();

// Set up the join between the role entity
// and the intersect table systemuserroles.
LinkEntity le = new LinkEntity();
le.LinkFromEntityName = "role";
le.LinkFromAttributeName = "roleid";
le.LinkToEntityName = "systemuserroles";
le.LinkToAttributeName = "roleid";

// Set up the join between the intersect table
// systemuserroles and the systemuser entity.
LinkEntity le2 = new LinkEntity();
le2.LinkFromEntityName = "systemuserroles";
le2.LinkFromAttributeName = "systemuserid";
le2.LinkToEntityName = "systemuser";
le2.LinkToAttributeName = "systemuserid";

// The condition is to find the user ID.
ConditionExpression ce = new ConditionExpression();
ce.AttributeName = "systemuserid";
ce.Operator = ConditionOperator.Equal;
ce.Values = new object[]{userid};

le2.LinkCriteria = new FilterExpression();
le2.LinkCriteria.Conditions = new ConditionExpression[]{ce};

le.LinkEntities = new LinkEntity[]{le2};
qe.LinkEntities = new LinkEntity[]{le};

// Execute the query.
BusinessEntityCollection bec = service.RetrieveMultiple(qe);





Retrieve the Metadata

This sample shows how to use the MetadataService Web Service. It creates an XML file that provides a snapshot of the database using the Metadata APIs. All relationships and attributes for all of the entities are retrieved.



using System;
using System.Xml.Serialization;
using System.Xml;
using System.IO;

using Microsoft.Crm.Sdk.Utility;
using CrmSdk;
using MetadataServiceSdk;

namespace Microsoft.Crm.Sdk.HowTo
{
///
/// This sample shows how to retrieve all the metadata and write it to a file.
///

public class HowToMetaData
{
static void Main(string[] args)
{
// TODO: Change the server URL and Organization to match your CRM Server and CRM Organization
HowToMetaData.Run("http://localhost:5555", "CRM_SDK");
}

public static bool Run(string crmServerUrl, string orgName)
{
// Standard MetaData Service Setup
MetadataService service = CrmServiceUtility.GetMetadataService(crmServerUrl, orgName);

#region Setup Data Required for this Sample

bool success = false;

#endregion

try
{
// Retrieve the Metadata
RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest();
request.MetadataItems = MetadataItems.All;
RetrieveAllEntitiesResponse metadata = (RetrieveAllEntitiesResponse)service.Execute(request);


// Create an instance of StreamWriter to write text to a file.
// The using statement also closes the StreamWriter.
using (StreamWriter sw = new StreamWriter("testfile.xml"))
{
// Create Xml Writer.
XmlTextWriter metadataWriter = new XmlTextWriter(sw);

// Start Xml File.
metadataWriter.WriteStartDocument();

// Metadata Xml Node.
metadataWriter.WriteStartElement("Metadata");

AttributeMetadata currentAttribute;// Declared outside of loop

// Iterate through all entities and add their attributes and relationships to the file.
foreach(EntityMetadata currentEntity in metadata.CrmMetadata)
{
// Start Entity Node
metadataWriter.WriteStartElement("Entity");

// Write the Entity's Information.
metadataWriter.WriteElementString("Name", currentEntity.LogicalName);

if (currentEntity.DisplayName.UserLocLabel != null)
{
metadataWriter.WriteElementString("DisplayName", currentEntity.DisplayName.UserLocLabel.Label);
}
else
{
metadataWriter.WriteElementString("DisplayName", "[NONE]");
}

if (currentEntity.DisplayCollectionName.UserLocLabel != null)
{
metadataWriter.WriteElementString("DisplayCollectionName", currentEntity.DisplayCollectionName.UserLocLabel.Label);
}
else
{
metadataWriter.WriteElementString("DisplayCollectionName", "[NONE]");
}

metadataWriter.WriteElementString("IsCustomEntity", currentEntity.IsCustomEntity.ToString());
metadataWriter.WriteElementString("IsCustomizable", currentEntity.IsCustomizable.ToString());
metadataWriter.WriteElementString("ReportViewName", currentEntity.ReportViewName);
metadataWriter.WriteElementString("PrimaryField", currentEntity.PrimaryField);
metadataWriter.WriteElementString("PrimaryKey", currentEntity.PrimaryKey);

#region Attributes

// Write Entity's Attributes.
metadataWriter.WriteStartElement("Attributes");

for (int j = 0; j < currentEntity.Attributes.Length; j++)
{
// Get Current Attribute.
currentAttribute = currentEntity.Attributes[j];
// Start Attribute Node
metadataWriter.WriteStartElement("Attribute");

// Write Attribute's information.
metadataWriter.WriteElementString("Name", currentAttribute.LogicalName);
metadataWriter.WriteElementString("Type", currentAttribute.AttributeType.ToString());

if (currentAttribute.DisplayName.UserLocLabel != null)
{
metadataWriter.WriteElementString("DisplayName", currentAttribute.DisplayName.UserLocLabel.Label);
}
else
{
metadataWriter.WriteElementString("DisplayName", "[NONE]");
}

metadataWriter.WriteElementString("Description", currentAttribute.IsCustomField.ToString());
metadataWriter.WriteElementString("IsCustomField", currentAttribute.IsCustomField.ToString());
metadataWriter.WriteElementString("RequiredLevel", currentAttribute.RequiredLevel.ToString());
metadataWriter.WriteElementString("ValidForCreate", currentAttribute.ValidForCreate.ToString());
metadataWriter.WriteElementString("ValidForRead", currentAttribute.ValidForRead.ToString());
metadataWriter.WriteElementString("ValidForUpdate", currentAttribute.ValidForUpdate.ToString());

// Write the Default Value if it is set.
if (currentAttribute.DefaultValue != null)
{
metadataWriter.WriteElementString("DefualtValue", currentAttribute.DefaultValue.ToString());
}

// Write the Description if it is set.
if (currentAttribute.Description != null &&
currentAttribute.Description.UserLocLabel != null)
{
metadataWriter.WriteElementString("Description", currentAttribute.Description.UserLocLabel.Label);
}


// Write Type Specific Attribute Information using helper functions.

Type attributeType = currentAttribute.GetType();

if (attributeType == typeof(DecimalAttributeMetadata))
{
writeDecimalAttribute((DecimalAttributeMetadata)currentAttribute, metadataWriter);
}
else if (attributeType == typeof(FloatAttributeMetadata))
{
writeFloatAttribute((FloatAttributeMetadata)currentAttribute, metadataWriter);
}
else if (attributeType == typeof(IntegerAttributeMetadata))
{
writeIntegerAttribute((IntegerAttributeMetadata)currentAttribute, metadataWriter);
}
else if (attributeType == typeof(MoneyAttributeMetadata))
{
writeMoneyAttribute((MoneyAttributeMetadata)currentAttribute, metadataWriter);
}
else if (attributeType == typeof(PicklistAttributeMetadata))
{
writePicklistAttribute((PicklistAttributeMetadata)currentAttribute, metadataWriter);
}
else if (attributeType == typeof(StateAttributeMetadata))
{
writeStateAttribute((StateAttributeMetadata)currentAttribute, metadataWriter);
}
else if (attributeType == typeof(StatusAttributeMetadata))
{
writeStatusAttribute((StatusAttributeMetadata)currentAttribute, metadataWriter);
}
else if (attributeType == typeof(StringAttributeMetadata))
{
writeStringAttribute((StringAttributeMetadata)currentAttribute, metadataWriter);
}

// End Attribute Node
metadataWriter.WriteEndElement();

}
// End Attributes Node
metadataWriter.WriteEndElement();

#endregion

#region References From

metadataWriter.WriteStartElement("OneToMany");

// Get Current ReferencesFrom
foreach (OneToManyMetadata currentRelationship in currentEntity.OneToManyRelationships)
{
// Start ReferencesFrom Node
metadataWriter.WriteStartElement("From");
metadataWriter.WriteElementString("Name", currentRelationship.SchemaName);
metadataWriter.WriteElementString("IsCustomRelationship", currentRelationship.IsCustomRelationship.ToString());
metadataWriter.WriteElementString("ReferencedEntity", currentRelationship.ReferencedEntity);
metadataWriter.WriteElementString("ReferencingEntity", currentRelationship.ReferencingEntity);
metadataWriter.WriteElementString("ReferencedAttribute", currentRelationship.ReferencedAttribute);
metadataWriter.WriteElementString("ReferencingAttribute", currentRelationship.ReferencingAttribute);

// End ReferencesFrom Node
metadataWriter.WriteEndElement();
}

metadataWriter.WriteEndElement();

#endregion

#region References To

metadataWriter.WriteStartElement("ManyToOne");

foreach (OneToManyMetadata currentRelationship in currentEntity.ManyToOneRelationships)
{
// Start ReferencesFrom Node
metadataWriter.WriteStartElement("To");
metadataWriter.WriteElementString("Name", currentRelationship.SchemaName);
metadataWriter.WriteElementString("IsCustomRelationship", currentRelationship.IsCustomRelationship.ToString());
metadataWriter.WriteElementString("ReferencedEntity", currentRelationship.ReferencedEntity);
metadataWriter.WriteElementString("ReferencingEntity", currentRelationship.ReferencingEntity);
metadataWriter.WriteElementString("ReferencedAttribute", currentRelationship.ReferencedAttribute);
metadataWriter.WriteElementString("ReferencingAttribute", currentRelationship.ReferencingAttribute);

// End ReferencesFrom Node
metadataWriter.WriteEndElement();
}

metadataWriter.WriteEndElement();

#endregion

// End Entity Node
metadataWriter.WriteEndElement();
}

// End Metadata Xml Node
metadataWriter.WriteEndElement();
metadataWriter.WriteEndDocument();

// Close xml writer.
metadataWriter.Close();
}

#region check success

if (metadata.CrmMetadata.Length > 0)
{
success = true;
}

#endregion
}
catch (System.Web.Services.Protocols.SoapException)
{
// Add your error handling code here.
}

return success;
}


#region Specific Attribute Helper Functions

// Writes the Decimal Specific Attributes
private static void writeDecimalAttribute (DecimalAttributeMetadata attribute, XmlTextWriter writer)
{
writer.WriteElementString("MinValue", attribute.MinValue.ToString());
writer.WriteElementString("MaxValue", attribute.MaxValue.ToString());
writer.WriteElementString("Precision", attribute.Precision.ToString());
}

// Writes the Float Specific Attributes
private static void writeFloatAttribute (FloatAttributeMetadata attribute, XmlTextWriter writer)
{
writer.WriteElementString("MinValue", attribute.MinValue.ToString());
writer.WriteElementString("MaxValue", attribute.MaxValue.ToString());
writer.WriteElementString("Precision", attribute.Precision.ToString());
}

// Writes the Integer Specific Attributes
private static void writeIntegerAttribute (IntegerAttributeMetadata attribute, XmlTextWriter writer)
{
writer.WriteElementString("MinValue", attribute.MinValue.ToString());
writer.WriteElementString("MaxValue", attribute.MaxValue.ToString());
}

// Writes the Money Specific Attributes
private static void writeMoneyAttribute (MoneyAttributeMetadata attribute, XmlTextWriter writer)
{
writer.WriteElementString("MinValue", attribute.MinValue.ToString());
writer.WriteElementString("MaxValue", attribute.MaxValue.ToString());
writer.WriteElementString("Precision", attribute.Precision.ToString());
}

// Writes the Picklist Specific Attributes
private static void writePicklistAttribute (PicklistAttributeMetadata attribute, XmlTextWriter writer)
{
// Writes the picklist's options
writer.WriteStartElement("Options");

// Writes the attributes of each picklist option
for (int i = 0; i < attribute.Options.Length; i++)
{
writer.WriteStartElement("Option");
writer.WriteElementString("OptionValue", attribute.Options[i].Value.ToString());
writer.WriteElementString("Description", attribute.Options[i].Label.UserLocLabel.Label);
writer.WriteEndElement();
}

writer.WriteEndElement();
}

// Writes the State Specific Attributes
private static void writeStateAttribute (StateAttributeMetadata attribute, XmlTextWriter writer)
{
// Writes the state's options
writer.WriteStartElement("Options");

// Writes the attributes of each picklist option
for (int i = 0; i < attribute.Options.Length; i++)
{
writer.WriteStartElement("Option");
writer.WriteElementString("OptionValue", attribute.Options[i].Value.ToString());
writer.WriteElementString("Description", attribute.Options[i].Label.UserLocLabel.Label);
writer.WriteElementString("DefaultStatus", attribute.Options[i].DefaultStatus.ToString());
writer.WriteEndElement();
}

writer.WriteEndElement();
}

// Writes the Status Specific Attributes
private static void writeStatusAttribute (StatusAttributeMetadata attribute, XmlTextWriter writer)
{
// Writes the status's options
writer.WriteStartElement("Options");

// Writes the attributes of each picklist option
for (int i = 0; i < attribute.Options.Length; i++)
{
writer.WriteStartElement("Option");
writer.WriteElementString("OptionValue", attribute.Options[i].Value.ToString());
writer.WriteElementString("Description", attribute.Options[i].Label.UserLocLabel.Label);
writer.WriteElementString("State", attribute.Options[i].State.ToString());
writer.WriteEndElement();
}

writer.WriteEndElement();
}

// Writes the String Specific Attributes
private static void writeStringAttribute (StringAttributeMetadata attribute, XmlTextWriter writer)
{
writer.WriteElementString("MaxLength", attribute.MaxLength.ToString());
}
#endregion
}
}