Exemple #1
0
        public void AddLink(Entity source, Relationship relationship, Entity target)
        {
            if (!service.IsAttached(source))
            {
                service.Attach(source);
            }

            if (!service.IsAttached(target))
            {
                service.Attach(target);
            }

            service.AddLink(source, relationship, target);
        }
        /// <summary>
        /// Adds a Forum Thread Tag tag association by name to a Forum Thread.
        /// </summary>
        /// <param name="threadId">The ID of the Forum Thread whose tags will be affected.</param>
        /// <param name="tagName">
        /// The name of the tag to be associated with the thread (will be created if necessary).
        /// </param>
        /// <remarks>
        /// <para>
        /// This operation may call SaveChanges on this context--please ensure any queued
        /// changes are mananged accordingly.
        /// </para>
        /// </remarks>
        public static void AddTagToForumThreadAndSave(this OrganizationServiceContext context, Guid threadId, string tagName)
        {
            if (context.MergeOption == MergeOption.NoTracking)
            {
                throw new ArgumentException("The OrganizationServiceContext.MergeOption cannot be MergeOption.NoTracking.", "context");
            }

            if (string.IsNullOrEmpty(tagName))
            {
                throw new ArgumentException("Can't be null or empty.", "tagName");
            }

            if (threadId == Guid.Empty)
            {
                throw new ArgumentException("Argument must be a non-empty GUID.", "threadId");
            }

            var thread = context.CreateQuery("adx_communityforumthread").Single(e => e.GetAttributeValue <Guid>("adx_communityforumthreadid") == threadId);

            var tag = GetForumThreadTagByName(context, tagName);

            // If the tag doesn't exist, create it
            if (tag == null)
            {
                tag = new Entity("adx_communityforumthreadtag");

                tag["adx_name"] = tagName;

                context.AddObject(tag);
                context.SaveChanges();
                context.ReAttach(thread);
                context.ReAttach(tag);
            }

            if (!thread.GetRelatedEntities(context, "adx_forumthreadtag_forumthread").Any(t => t.GetAttributeValue <Guid>("adx_communityforumthreadtagid") == tag.Id))
            {
                context.AddLink(thread, "adx_forumthreadtag_forumthread", tag);

                context.SaveChanges();
            }
        }
        /// <summary>
        /// Adds a Page Tagtag association by name to a Web Page.
        /// </summary>
        /// <param name="pageId">The ID of the Web Page whose tags will be affected.</param>
        /// <param name="tagName">
        /// The name of the tag to be associated with the page (will be created if necessary).
        /// </param>
        /// <remarks>
        /// <para>
        /// This operation may call SaveChanges on this context--please ensure any queued
        /// changes are mananged accordingly.
        /// </para>
        /// </remarks>
        public static void AddTagToWebPageAndSave(this OrganizationServiceContext context, Guid pageId, string tagName)
        {
            if (context.MergeOption == MergeOption.NoTracking)
            {
                throw new ArgumentException("The OrganizationServiceContext.MergeOption cannot be MergeOption.NoTracking.", "context");
            }

            if (string.IsNullOrEmpty(tagName))
            {
                throw new ArgumentException("Can't be null or empty.", "tagName");
            }

            if (pageId == Guid.Empty)
            {
                throw new ArgumentException("Argument must be a non-empty GUID.", "pageId");
            }

            var page = context.CreateQuery("adx_webpage").Single(p => p.GetAttributeValue <Guid>("adx_webpageid") == pageId);

            var tag = context.GetPageTagByName(tagName);

            // If the tag doesn't exist, create it
            if (tag == null)
            {
                tag             = new Entity("adx_pagetag");
                tag["adx_name"] = tagName;

                context.AddObject(tag);
                context.SaveChanges();
                context.ReAttach(page);
                context.ReAttach(tag);
            }

            if (!page.GetRelatedEntities(context, "adx_pagetag_webpage").Any(t => t.GetAttributeValue <Guid>("adx_pagetagid") == tag.Id))
            {
                context.AddLink(page, new Relationship("adx_pagetag_webpage"), tag);

                context.SaveChanges();
            }
        }
Exemple #4
0
        public EntityReferenceCollection CreateAContact(Guid _accountId, Entity account)
        {
            Contact contact = new Contact()
            {
                FirstName                = fName,
                LastName                 = lName,
                Address1_Line1           = "23 Market St.",
                Address1_City            = "Sammamish",
                Address1_StateOrProvince = "MT",
                Address1_PostalCode      = "99999",
                Telephone1               = "12345678",
                EMailAddress1            = fName + "." + lName + "@" + accountName + ".com",
                Id = Guid.NewGuid()
            };

            _contactId = contact.Id;
            _orgContext.AddObject(contact);

            Console.WriteLine("Service created with First Name {0} and Last Name {1}", contact.FirstName, contact.LastName);

            //Create a collection of the entity id(s) that will be associated to the contact.
            EntityReferenceCollection relatedEntities = new EntityReferenceCollection();

            relatedEntities.Add(new EntityReference("account", _accountId));

            _orgContext.Attach(account);
            //_orgContext.Attach(contact);
            _orgContext.AddLink(
                account,
                new Relationship("contact_customer_accounts"),
                contact);
            //SaveChangesHelper(contact, account);
            Console.WriteLine("and adding contact to account's contact list.");

            return(relatedEntities);
        }
        internal static void AssociateEntity(OrganizationServiceContext context, Entity entityform, Guid sourceEntityId)
        {
            var setEntityReference = entityform.GetAttributeValue <bool?>("adx_setentityreference") ?? false;

            if (!setEntityReference)
            {
                return;
            }

            var targetEntityId         = Guid.Empty;
            var targetEntityPrimaryKey = string.Empty;
            var sourceEntityName       = entityform.GetAttributeValue <string>("adx_entityname");
            var sourceEntityPrimaryKey = entityform.GetAttributeValue <string>("adx_primarykeyname");
            var targetEntityName       = entityform.GetAttributeValue <string>("adx_referenceentitylogicalname");
            var relationshipName       = entityform.GetAttributeValue <string>("adx_referenceentityrelationshipname") ?? string.Empty;

            if (string.IsNullOrWhiteSpace(relationshipName))
            {
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Entity Relationship Name not provided. Entity Association not required.");
                return;
            }

            try
            {
                var referenceQueryStringName  = entityform.GetAttributeValue <string>("adx_referencequerystringname") ?? string.Empty;
                var referenceQueryStringValue = HttpContext.Current.Request[referenceQueryStringName];
                var querystringIsPrimaryKey   = entityform.GetAttributeValue <bool?>("adx_referencequerystringisprimarykey") ?? false;

                if (!querystringIsPrimaryKey)
                {
                    var referenceQueryAttributeName = entityform.GetAttributeValue <string>("adx_referencequeryattributelogicalname");
                    var entity =
                        context.CreateQuery(targetEntityName).FirstOrDefault(
                            o => o.GetAttributeValue <string>(referenceQueryAttributeName) == referenceQueryStringValue);

                    if (entity != null)
                    {
                        targetEntityId = entity.Id;
                    }
                }
                else
                {
                    Guid.TryParse(referenceQueryStringValue, out targetEntityId);
                }

                if (sourceEntityId == Guid.Empty || targetEntityId == Guid.Empty)
                {
                    ADXTrace.Instance.TraceError(TraceCategory.Application, "Source and Target entity ids must not be null or empty.");
                    return;
                }

                // get the source entity

                if (string.IsNullOrWhiteSpace(sourceEntityName))
                {
                    ADXTrace.Instance.TraceError(TraceCategory.Application, "adx_entityform.adx_targetentitylogicalname must not be null.");
                    return;
                }

                if (string.IsNullOrWhiteSpace(sourceEntityPrimaryKey))
                {
                    sourceEntityPrimaryKey = MetadataHelper.GetEntityPrimaryKeyAttributeLogicalName(context, sourceEntityName);
                }

                if (string.IsNullOrWhiteSpace(sourceEntityPrimaryKey))
                {
                    ADXTrace.Instance.TraceError(TraceCategory.Application, "Failed to determine source entity primary key logical name.");
                    return;
                }

                var sourceEntity = context.CreateQuery(sourceEntityName).FirstOrDefault(o => o.GetAttributeValue <Guid>(sourceEntityPrimaryKey) == sourceEntityId);

                if (sourceEntity == null)
                {
                    ADXTrace.Instance.TraceError(TraceCategory.Application, "Source entity is null.");
                    return;
                }

                // Get the target entity

                if (string.IsNullOrWhiteSpace(targetEntityName))
                {
                    ADXTrace.Instance.TraceError(TraceCategory.Application, "Target entity name must not be null or empty.");
                    return;
                }

                if (string.IsNullOrWhiteSpace(targetEntityPrimaryKey))
                {
                    targetEntityPrimaryKey = MetadataHelper.GetEntityPrimaryKeyAttributeLogicalName(context, targetEntityName);
                }

                if (string.IsNullOrWhiteSpace(targetEntityPrimaryKey))
                {
                    ADXTrace.Instance.TraceError(TraceCategory.Application, "Failed to determine target entity primary key logical name.");
                    return;
                }

                var targetEntity = context.CreateQuery(targetEntityName).FirstOrDefault(o => o.GetAttributeValue <Guid>(targetEntityPrimaryKey) == targetEntityId);

                if (targetEntity == null)
                {
                    ADXTrace.Instance.TraceError(TraceCategory.Application, "Target entity is null.");
                    return;
                }

                context.AddLink(sourceEntity, relationshipName, targetEntity);
            }
            catch (Exception ex)
            {
                ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("{0}", ex.ToString()));
            }
        }
        protected override void ProcessRequest(HttpContext context, ICmsEntityServiceProvider serviceProvider, Guid portalScopeId, IPortalContext portal, OrganizationServiceContext serviceContext, Entity entity, CmsEntityMetadata entityMetadata, ICrmEntitySecurityProvider security)
        {
            var relationshipSchemaName = string.IsNullOrWhiteSpace(RelationshipSchemaName) ? context.Request.Params["relationshipSchemaName"] : RelationshipSchemaName;

            if (string.IsNullOrWhiteSpace(relationshipSchemaName))
            {
                throw new CmsEntityServiceException(HttpStatusCode.BadRequest, "Unable to determine entity relationship schema name from request.");
            }

            var match = _relationshipSchemaNameRegex.Match(relationshipSchemaName);

            if (!match.Success)
            {
                throw new CmsEntityServiceException(HttpStatusCode.BadRequest, "Unable to determine entity relationship schema name from request.");
            }

            var schemaName = match.Groups["schemaName"].Value;

            if (string.IsNullOrWhiteSpace(schemaName))
            {
                throw new CmsEntityServiceException(HttpStatusCode.BadRequest, "Unable to determine entity relationship schema name from request.");
            }

            var entityRole = match.Groups["entityRole"].Value;

            EntityRole parsedRole;

            var relationship = new Relationship(schemaName)
            {
                PrimaryEntityRole = Enum.TryParse(entityRole, true, out parsedRole) ? new EntityRole?(parsedRole) : null
            };

            CmsEntityRelationshipInfo relationshipInfo;

            if (!entityMetadata.TryGetRelationshipInfo(relationship, out relationshipInfo))
            {
                throw new CmsEntityServiceException(HttpStatusCode.NotFound, "Entity relationship not found.");
            }

            // If the current request entity is the current website, do security handling here, since we skipped it earlier.
            if (entity.ToEntityReference().Equals(portal.Website.ToEntityReference()))
            {
                AssertRequestEntitySecurity(portal, serviceContext, entity, security, CreateWebsiteAccessPermissionProvider(portal), relationshipInfo);
            }

            if (IsRequestMethod(context.Request, "GET"))
            {
                if (relationshipInfo.IsCollection)
                {
                    var readableRelatedEntities = entity.GetRelatedEntities(serviceContext, relationship)
                                                  .Where(e => security.TryAssert(serviceContext, e, CrmEntityRight.Read));

                    var entityMetadataLookup = new Dictionary <string, CmsEntityMetadata>();

                    var entityJsonObjects = readableRelatedEntities.Select(e =>
                    {
                        CmsEntityMetadata relatedEntityMetadata;

                        if (!entityMetadataLookup.TryGetValue(e.LogicalName, out relatedEntityMetadata))
                        {
                            relatedEntityMetadata = new CmsEntityMetadata(serviceContext, e.LogicalName);

                            entityMetadataLookup[e.LogicalName] = relatedEntityMetadata;
                        }

                        return(GetEntityJson(context, serviceProvider, portalScopeId, portal, serviceContext, e, relatedEntityMetadata));
                    });

                    WriteResponse(context.Response, new JObject
                    {
                        { "d", new JArray(entityJsonObjects) }
                    });
                }
                else
                {
                    var relatedEntity = entity.GetRelatedEntity(serviceContext, relationship);

                    if (relatedEntity == null)
                    {
                        throw new CmsEntityServiceException(HttpStatusCode.NotFound, "Related entity not found.");
                    }

                    if (!security.TryAssert(serviceContext, relatedEntity, CrmEntityRight.Read))
                    {
                        throw new CmsEntityServiceException(HttpStatusCode.Forbidden, "Related entity access denied.");
                    }

                    WriteResponse(context.Response, new JObject
                    {
                        { "d", GetEntityJson(context, serviceProvider, portalScopeId, portal, serviceContext, relatedEntity, new CmsEntityMetadata(serviceContext, relatedEntity.LogicalName)) }
                    });
                }

                return;
            }

            if (IsRequestMethod(context.Request, "POST"))
            {
                if (relationshipInfo.IsCollection)
                {
                    OneToManyRelationshipMetadata relationshipMetadata;

                    if (!entityMetadata.TryGetOneToManyRelationshipMetadata(relationship, out relationshipMetadata))
                    {
                        throw new CmsEntityServiceException(HttpStatusCode.BadRequest, "Unable to retrieve the one-to-many relationship metadata for relationship {0} on entity type".FormatWith(relationship.ToSchemaName("."), entity.LogicalName));
                    }

                    var relatedEntity         = CreateEntityOfType(serviceContext, relationshipMetadata.ReferencingEntity);
                    var relatedEntityMetadata = new CmsEntityMetadata(serviceContext, relatedEntity.LogicalName);

                    var extensions = UpdateEntityFromJsonRequestBody(context.Request, serviceContext, relatedEntity, relatedEntityMetadata);

                    var preImage = relatedEntity.Clone(false);

                    // Ensure the reference to the target entity is set.
                    relatedEntity.SetAttributeValue(relationshipMetadata.ReferencingAttribute, new EntityReference(entity.LogicalName, entity.GetAttributeValue <Guid>(relationshipMetadata.ReferencedAttribute)));

                    serviceProvider.InterceptChange(context, portal, serviceContext, relatedEntity, relatedEntityMetadata, CmsEntityOperation.Create, preImage);

                    serviceContext.AddObject(relatedEntity);

                    serviceProvider.InterceptExtensionChange(context, portal, serviceContext, relatedEntity, relatedEntityMetadata, extensions, CmsEntityOperation.Create);

                    serviceContext.SaveChanges();

                    var refetchedEntity = serviceContext.CreateQuery(relatedEntity.LogicalName)
                                          .FirstOrDefault(e => e.GetAttributeValue <Guid>(relatedEntityMetadata.PrimaryIdAttribute) == relatedEntity.Id);

                    if (refetchedEntity == null)
                    {
                        throw new CmsEntityServiceException(HttpStatusCode.InternalServerError, "Unable to retrieve the created entity.");
                    }

                    WriteResponse(context.Response, new JObject
                    {
                        { "d", GetEntityJson(context, serviceProvider, portalScopeId, portal, serviceContext, refetchedEntity, relatedEntityMetadata) }
                    }, HttpStatusCode.Created);
                }
                else
                {
                    OneToManyRelationshipMetadata relationshipMetadata;

                    if (!entityMetadata.TryGetManyToOneRelationshipMetadata(relationship, out relationshipMetadata))
                    {
                        throw new CmsEntityServiceException(HttpStatusCode.BadRequest, "Unable to retrieve the many-to-one relationship metadata for relationship {0} on entity type".FormatWith(relationship.ToSchemaName("."), entity.LogicalName));
                    }

                    var relatedEntity         = CreateEntityOfType(serviceContext, relationshipMetadata.ReferencedEntity);
                    var relatedEntityMetadata = new CmsEntityMetadata(serviceContext, relatedEntity.LogicalName);

                    var extensions = UpdateEntityFromJsonRequestBody(context.Request, serviceContext, relatedEntity, relatedEntityMetadata);

                    serviceProvider.InterceptChange(context, portal, serviceContext, relatedEntity, relatedEntityMetadata, CmsEntityOperation.Create);

                    serviceContext.AddObject(relatedEntity);
                    serviceContext.AddLink(relatedEntity, relationship, entity);

                    serviceProvider.InterceptExtensionChange(context, portal, serviceContext, relatedEntity, relatedEntityMetadata, extensions, CmsEntityOperation.Create);

                    serviceContext.SaveChanges();

                    var refetchedEntity = serviceContext.CreateQuery(relatedEntity.LogicalName)
                                          .FirstOrDefault(e => e.GetAttributeValue <Guid>(relatedEntityMetadata.PrimaryIdAttribute) == relatedEntity.Id);

                    if (refetchedEntity == null)
                    {
                        throw new CmsEntityServiceException(HttpStatusCode.InternalServerError, "Unable to retrieve the created entity.");
                    }

                    WriteResponse(context.Response, new JObject
                    {
                        { "d", GetEntityJson(context, serviceProvider, portalScopeId, portal, serviceContext, refetchedEntity, relatedEntityMetadata) }
                    }, HttpStatusCode.Created);
                }

                return;
            }

            throw new CmsEntityServiceException(HttpStatusCode.MethodNotAllowed, "Request method {0} not allowed for this resource.".FormatWith(context.Request.HttpMethod));
        }
Exemple #7
0
 public void AddLink(Entity source, Relationship relationship, Entity target, OrganizationServiceContext context)
 {
     context.AddLink(source, relationship, target);
 }
Exemple #8
0
        /// <summary>
        /// This method first connects to the Organization service and creates the
        /// OrganizationServiceContext. Then, several entity creation and relationship
        /// operations are performed.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetBasicContextExamples1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,
                                                                    serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    _service = (IOrganizationService)_serviceProxy;

                    CreateRequiredRecords();

                    // The OrganizationServiceContext is an object that wraps the service
                    // proxy and allows creating/updating multiple records simultaneously.
                    _orgContext = new OrganizationServiceContext(_service);

                    // Create a new contact called Mary Kay Andersen.
                    var contact = new Contact()
                    {
                        FirstName                = "Mary Kay",
                        LastName                 = "Andersen",
                        Address1_Line1           = "23 Market St.",
                        Address1_City            = "Sammamish",
                        Address1_StateOrProvince = "MT",
                        Address1_PostalCode      = "99999",
                        Telephone1               = "12345678",
                        EMailAddress1            = "*****@*****.**",
                        Id = Guid.NewGuid()
                    };
                    _contactId = contact.Id;
                    _orgContext.AddObject(contact);
                    Console.Write("Instantiating contact, ");

                    // Create an account called Contoso.
                    var account = new Account()
                    {
                        Name          = "Contoso",
                        Address1_City = "Redmond",
                        // set the account category to 'Preferred Customer'
                        AccountCategoryCode = new OptionSetValue(1),
                        LastUsedInCampaign  = DateTime.Now,
                        MarketCap           = new Money(120000),
                        DoNotEMail          = true,
                        Description         = "Contoso is a fictional company!",
                        Id = Guid.NewGuid(),
                    };
                    _accountId = account.Id;
                    Console.Write("instantiating account, ");

                    // Set Mary Kay Andersen as the primary contact
                    _orgContext.AddRelatedObject(
                        contact,
                        new Relationship("account_primary_contact"),
                        account);
                    SaveChangesHelper(contact, account);
                    Console.WriteLine("and creating both records in CRM.");

                    // Remove the primary contact value from Mary Kay Andersen
                    _orgContext.Attach(contact);
                    _orgContext.DeleteLink(
                        contact,
                        new Relationship("account_primary_contact"),
                        account);
                    SaveChangesHelper(contact, account);
                    Console.Write("Removing primary contact status, ");

                    // Add Mary Kay Andersen to the contact list for the account Contoso.
                    _orgContext.Attach(account);
                    _orgContext.Attach(contact);
                    _orgContext.AddLink(
                        account,
                        new Relationship("contact_customer_accounts"),
                        contact);
                    SaveChangesHelper(contact, account);
                    Console.WriteLine("and adding contact to account's contact list.");

                    // Add a note with a document attachment to the contact's record.
                    var attachment = File.OpenRead("sample.txt");
                    var data       = new byte[attachment.Length];
                    attachment.Read(data, 0, (int)attachment.Length);

                    var note = new Annotation()
                    {
                        Subject      = "Note subject...",
                        NoteText     = "Note Details....",
                        DocumentBody = Convert.ToBase64String(data),
                        FileName     = Path.GetFileName(attachment.Name),
                        MimeType     = "text/plain",
                        Id           = Guid.NewGuid(),
                        // Associate the note to the contact.
                        ObjectId       = contact.ToEntityReference(),
                        ObjectTypeCode = Contact.EntityLogicalName
                    };
                    _annotationId = note.Id;
                    Console.Write("Instantiating a note, ");
                    _orgContext.AddObject(note);
                    _orgContext.Attach(contact);
                    // Set the contact as the Regarding attribute of the note.
                    _orgContext.AddLink(
                        contact,
                        new Relationship("Contact_Annotation"),
                        note);
                    SaveChangesHelper(note, contact);
                    Console.WriteLine("creating the note in CRM and linking to contact.");

                    // Change the owning user of the contact Mary Kay Andersen
                    // Find a user with an email address of "*****@*****.**"
                    var newOwner = (from u in _orgContext.CreateQuery <SystemUser>()
                                    where u.InternalEMailAddress == "*****@*****.**"
                                    select u).Single();
                    AssignRequest assignRequest = new AssignRequest()
                    {
                        Target   = contact.ToEntityReference(),
                        Assignee = newOwner.ToEntityReference()
                    };
                    _orgContext.Execute(assignRequest);
                    Console.WriteLine("Changing ownership of contact record.");

                    // Create a new price list called Retail Price List.
                    var priceList = new PriceLevel()
                    {
                        Name        = "Retail Price List",
                        BeginDate   = DateTime.Now,
                        EndDate     = DateTime.Now,
                        Description = "Contoso's primary pricelist.",
                        Id          = Guid.NewGuid()
                    };
                    _priceLevelId = priceList.Id;
                    _orgContext.AddObject(priceList);
                    Console.Write("Instantiating price list ");

                    // Create a new product called Widget A.
                    var newProduct = new Product()
                    {
                        Name             = "Widget A",
                        Description      = "Industrial widget for hi-tech industries",
                        ProductStructure = new OptionSetValue(1), // 1 = Product
                        QuantityOnHand   = 2,
                        ProductNumber    = "WIDG-A",
                        Price            = new Money(decimal.Parse("12.50")),
                        QuantityDecimal  = 2, // Sets the Decimals Supported value
                        Id = Guid.NewGuid(),
                        DefaultUoMScheduleId = new EntityReference(
                            UoMSchedule.EntityLogicalName,
                            _orgContext.CreateQuery <UoMSchedule>().First().Id),
                        DefaultUoMId = new EntityReference(
                            UoM.EntityLogicalName,
                            _orgContext.CreateQuery <UoM>().First().Id)
                    };
                    _productId = newProduct.Id;
                    _orgContext.AddObject(newProduct);
                    Console.WriteLine("and product.");
                    SaveChangesHelper(priceList, newProduct);

                    // Add Widget A to the Retail Price List.
                    var priceLevelProduct = new ProductPriceLevel()
                    {
                        ProductId    = newProduct.ToEntityReference(),
                        UoMId        = newProduct.DefaultUoMId,
                        Amount       = new Money(decimal.Parse("12.50")),
                        PriceLevelId = priceList.ToEntityReference(),
                        Id           = Guid.NewGuid()
                    };
                    _productPriceLevelId = priceLevelProduct.Id;
                    _orgContext.AddObject(priceLevelProduct);
                    Console.Write("Associating product to price list, ");

                    // Publish the product
                    SetStateRequest publishRequest = new SetStateRequest
                    {
                        EntityMoniker = newProduct.ToEntityReference(),
                        State         = new OptionSetValue((int)ProductState.Active),
                        Status        = new OptionSetValue(1)
                    };
                    _serviceProxy.Execute(publishRequest);
                    Console.WriteLine("and publishing the product.");


                    // Create a new quote for Contoso.
                    var newQuote = new Quote()
                    {
                        Name = "Quotation for Contoso",
                        // Sets the pricelist to the one we've just created
                        PriceLevelId = priceList.ToEntityReference(),
                        Id           = Guid.NewGuid(),
                        CustomerId   = account.ToEntityReference()
                    };
                    _quoteId = newQuote.Id;
                    _orgContext.AddObject(newQuote);
                    _orgContext.Attach(account);
                    _orgContext.AddLink(
                        newQuote,
                        new Relationship("quote_customer_accounts"),
                        account);
                    Console.Write("Instantiating a quote, ");

                    // Add a quote product to this quote.
                    var quoteProduct = new QuoteDetail()
                    {
                        ProductId = newProduct.ToEntityReference(),
                        Quantity  = 1,
                        QuoteId   = newQuote.ToEntityReference(),
                        UoMId     = newProduct.DefaultUoMId,
                        Id        = Guid.NewGuid()
                    };
                    _quoteDetailId = quoteProduct.Id;
                    _orgContext.AddObject(quoteProduct);
                    Console.WriteLine("and adding product to quote.");

                    // Create a sales opportunity with Contoso.
                    var oppty = new Opportunity()
                    {
                        Name = "Interested in Widget A",
                        EstimatedCloseDate        = DateTime.Now.AddDays(30.0),
                        EstimatedValue            = new Money(decimal.Parse("300000.00")),
                        CloseProbability          = 25,                    // 25% probability of closing this deal
                        IsRevenueSystemCalculated = false,                 // user-calculated revenue
                        OpportunityRatingCode     = new OptionSetValue(2), // warm
                        CustomerId = account.ToEntityReference(),
                        Id         = Guid.NewGuid()
                    };
                    _opportunityId = oppty.Id;
                    _orgContext.AddObject(oppty);
                    Console.Write("Instantiating opportunity, ");
                    //_orgContext.AddLink(
                    //    oppty,
                    //    new Relationship("opportunity_customer_accounts"),
                    //    account);
                    SaveChangesHelper(priceList, newQuote, newProduct, priceLevelProduct,
                                      quoteProduct, oppty, account);
                    Console.WriteLine("and creating all records in CRM.");

                    // Associate quote to contact, which adds the Contact record in the
                    // "Other Contacts" section of a Quote record.
                    _orgContext.Attach(contact);
                    _orgContext.Attach(newQuote);
                    _orgContext.AddLink(
                        contact,
                        new Relationship("contactquotes_association"),
                        newQuote);
                    SaveChangesHelper(contact, newQuote);
                    Console.WriteLine("Associating contact and quote.");

                    // Create a case for Mary Kay Andersen.
                    var serviceRequest = new Incident()
                    {
                        Title          = "Problem with Widget B",
                        PriorityCode   = new OptionSetValue(1), // 1 = High
                        CaseOriginCode = new OptionSetValue(1), // 1 = Phone
                        CaseTypeCode   = new OptionSetValue(2), // 2 = Problem
                        SubjectId      =
                            new EntityReference(
                                Subject.EntityLogicalName,
                                _orgContext.CreateQuery <Subject>()
                                .First().Id),                     // use the default subject
                        Description = "Customer can't switch the product on.",
                        FollowupBy  = DateTime.Now.AddHours(3.0), // follow-up in 3 hours
                        CustomerId  = contact.ToEntityReference(),
                        Id          = Guid.NewGuid()
                    };
                    _incidentId = serviceRequest.Id;
                    _orgContext.AddObject(serviceRequest);
                    _orgContext.Attach(contact);
                    _orgContext.AddLink(
                        serviceRequest,
                        new Relationship("incident_customer_contacts"),
                        contact);
                    SaveChangesHelper(serviceRequest, contact);
                    Console.WriteLine("Creating service case for contact.");

                    // Deactivate the Mary Kay Andersen contact record.
                    SetStateRequest setInactiveRequest = new SetStateRequest
                    {
                        EntityMoniker = contact.ToEntityReference(),
                        State         = new OptionSetValue((int)ContactState.Inactive),
                        Status        = new OptionSetValue(2)
                    };
                    _orgContext.Execute(setInactiveRequest);
                    Console.WriteLine("Deactivating the contact record.");

                    DeleteRequiredRecords(promptforDelete);
                }
                //</snippetBasicContextExamples1>
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        /// <summary>
        /// This method first connects to the Organization service and creates the
        /// OrganizationServiceContext. Then, several entity creation and relationship
        /// operations are performed.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetBasicContextExamples1>
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,
                                                                     serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    _service = (IOrganizationService)_serviceProxy;
                    
                    CreateRequiredRecords();

                    // The OrganizationServiceContext is an object that wraps the service
                    // proxy and allows creating/updating multiple records simultaneously.
                    _orgContext = new OrganizationServiceContext(_service);

                    // Create a new contact called Mary Kay Andersen.
                    var contact = new Contact()
                    {
                        FirstName = "Mary Kay",
                        LastName = "Andersen",
                        Address1_Line1 = "23 Market St.",
                        Address1_City = "Sammamish",
                        Address1_StateOrProvince = "MT",
                        Address1_PostalCode = "99999",
                        Telephone1 = "12345678",
                        EMailAddress1 = "*****@*****.**",
                        Id = Guid.NewGuid()
                    };
                    _contactId = contact.Id;
                    _orgContext.AddObject(contact);
                    Console.Write("Instantiating contact, ");

                    // Create an account called Contoso.
                    var account = new Account()
                    {
                        Name = "Contoso",
                        Address1_City = "Redmond",
                        // set the account category to 'Preferred Customer'
                        AccountCategoryCode = new OptionSetValue(1), 
                        LastUsedInCampaign = DateTime.Now,
                        MarketCap = new Money(120000),
                        DoNotEMail = true,
                        Description = "Contoso is a fictional company!",
                        Id = Guid.NewGuid(),
                    };
                    _accountId = account.Id;
                    Console.Write("instantiating account, ");

                    // Set Mary Kay Andersen as the primary contact
                    _orgContext.AddRelatedObject(
                        contact,
                        new Relationship("account_primary_contact"),
                        account);
                    SaveChangesHelper(contact, account);
                    Console.WriteLine("and creating both records in CRM.");

                    // Remove the primary contact value from Mary Kay Andersen
                    _orgContext.Attach(contact);
                    _orgContext.DeleteLink(
                        contact,
                        new Relationship("account_primary_contact"),
                        account);
                    SaveChangesHelper(contact, account);
                    Console.Write("Removing primary contact status, ");

                    // Add Mary Kay Andersen to the contact list for the account Contoso.
                    _orgContext.Attach(account);
                    _orgContext.Attach(contact);
                    _orgContext.AddLink(
                        account,
                        new Relationship("contact_customer_accounts"),
                        contact);
                    SaveChangesHelper(contact, account);
                    Console.WriteLine("and adding contact to account's contact list.");

                    // Add a note with a document attachment to the contact's record.
                    var attachment = File.OpenRead("sample.txt");
                    var data = new byte[attachment.Length];
                    attachment.Read(data, 0, (int)attachment.Length);

                    var note = new Annotation()
                    {
                        Subject = "Note subject...",
                        NoteText = "Note Details....",
                        DocumentBody = Convert.ToBase64String(data),
                        FileName = Path.GetFileName(attachment.Name),
                        MimeType = "text/plain",
                        Id = Guid.NewGuid(),
                        // Associate the note to the contact.
                        ObjectId = contact.ToEntityReference(),
                        ObjectTypeCode = Contact.EntityLogicalName
                    };
                    _annotationId = note.Id;
                    Console.Write("Instantiating a note, ");
                    _orgContext.AddObject(note);
                    _orgContext.Attach(contact);
                    // Set the contact as the Regarding attribute of the note.
                    _orgContext.AddLink(
                        contact,
                        new Relationship("Contact_Annotation"),
                        note);
                    SaveChangesHelper(note, contact);
                    Console.WriteLine("creating the note in CRM and linking to contact.");

                    // Change the owning user of the contact Mary Kay Andersen
                    // Find a user with an email address of "*****@*****.**"
                    var newOwner = (from u in _orgContext.CreateQuery<SystemUser>()
                                    where u.InternalEMailAddress == "*****@*****.**"
                                    select u).Single();
                    AssignRequest assignRequest = new AssignRequest()
                    {
                        Target = contact.ToEntityReference(),
                        Assignee = newOwner.ToEntityReference()
                    };
                    _orgContext.Execute(assignRequest);
                    Console.WriteLine("Changing ownership of contact record.");

                    // Create a new price list called Retail Price List.
                    var priceList = new PriceLevel()
                    {
                        Name = "Retail Price List",
                        BeginDate = DateTime.Now,
                        EndDate = DateTime.Now,
                        Description = "Contoso's primary pricelist.",
                        Id = Guid.NewGuid()
                    };
                    _priceLevelId = priceList.Id;
                    _orgContext.AddObject(priceList);
                    Console.Write("Instantiating price list ");
                    
                    // Create a new product called Widget A.
                    var newProduct = new Product()
                    {
                        Name = "Widget A",
                        Description = "Industrial widget for hi-tech industries",
                        ProductStructure = new OptionSetValue(1), // 1 = Product
                        QuantityOnHand = 2,
                        ProductNumber = "WIDG-A",
                        Price = new Money(decimal.Parse("12.50")),
                        QuantityDecimal = 2, // Sets the Decimals Supported value
                        Id = Guid.NewGuid(),
                        DefaultUoMScheduleId = new EntityReference(
                                UoMSchedule.EntityLogicalName,
                                _orgContext.CreateQuery<UoMSchedule>().First().Id),
                        DefaultUoMId = new EntityReference(
                                UoM.EntityLogicalName,
                                _orgContext.CreateQuery<UoM>().First().Id)
                    };
                    _productId = newProduct.Id;
                    _orgContext.AddObject(newProduct);
                    Console.WriteLine("and product.");
                    SaveChangesHelper(priceList, newProduct);

                    // Add Widget A to the Retail Price List.
                    var priceLevelProduct = new ProductPriceLevel()
                    {
                        ProductId = newProduct.ToEntityReference(),
                        UoMId = newProduct.DefaultUoMId,
                        Amount = new Money(decimal.Parse("12.50")),
                        PriceLevelId = priceList.ToEntityReference(),
                        Id = Guid.NewGuid()
                    };
                    _productPriceLevelId = priceLevelProduct.Id;
                    _orgContext.AddObject(priceLevelProduct);
                    Console.Write("Associating product to price list, ");

                    // Publish the product
                    SetStateRequest publishRequest = new SetStateRequest
                    {
                        EntityMoniker = newProduct.ToEntityReference(),
                        State = new OptionSetValue((int)ProductState.Active),
                        Status = new OptionSetValue(1)
                    };
                    _serviceProxy.Execute(publishRequest);
                    Console.WriteLine("and publishing the product.");
                    

                    // Create a new quote for Contoso.
                    var newQuote = new Quote()
                    {
                        Name = "Quotation for Contoso",
                        // Sets the pricelist to the one we've just created
                        PriceLevelId = priceList.ToEntityReference(),
                        Id = Guid.NewGuid(),
                        CustomerId = account.ToEntityReference()
                    };
                    _quoteId = newQuote.Id;
                    _orgContext.AddObject(newQuote);
                    _orgContext.Attach(account);
                    _orgContext.AddLink(
                        newQuote,
                        new Relationship("quote_customer_accounts"),
                        account);
                    Console.Write("Instantiating a quote, ");

                    // Add a quote product to this quote.
                    var quoteProduct = new QuoteDetail()
                    {
                        ProductId = newProduct.ToEntityReference(),
                        Quantity = 1,
                        QuoteId = newQuote.ToEntityReference(),
                        UoMId = newProduct.DefaultUoMId,
                        Id = Guid.NewGuid()
                    };
                    _quoteDetailId = quoteProduct.Id;
                    _orgContext.AddObject(quoteProduct);
                    Console.WriteLine("and adding product to quote.");

                    // Create a sales opportunity with Contoso.
                    var oppty = new Opportunity()
                    {
                        Name = "Interested in Widget A",
                        EstimatedCloseDate = DateTime.Now.AddDays(30.0),
                        EstimatedValue = new Money(decimal.Parse("300000.00")),
                        CloseProbability = 25, // 25% probability of closing this deal
                        IsRevenueSystemCalculated = false, // user-calculated revenue
                        OpportunityRatingCode = new OptionSetValue(2), // warm
                        CustomerId = account.ToEntityReference(),
                        Id = Guid.NewGuid()
                    };
                    _opportunityId = oppty.Id;
                    _orgContext.AddObject(oppty);
                    Console.Write("Instantiating opportunity, ");
                    //_orgContext.AddLink(
                    //    oppty,
                    //    new Relationship("opportunity_customer_accounts"),
                    //    account);
                    SaveChangesHelper(priceList, newQuote, newProduct, priceLevelProduct,
                        quoteProduct, oppty, account);
                    Console.WriteLine("and creating all records in CRM.");

                    // Associate quote to contact, which adds the Contact record in the
                    // "Other Contacts" section of a Quote record.
                    _orgContext.Attach(contact);
                    _orgContext.Attach(newQuote);
                    _orgContext.AddLink(
                        contact,
                        new Relationship("contactquotes_association"),
                        newQuote);
                    SaveChangesHelper(contact, newQuote);
                    Console.WriteLine("Associating contact and quote.");

                    // Create a case for Mary Kay Andersen.                     
                    var serviceRequest = new Incident()
                    {
                        Title = "Problem with Widget B",
                        PriorityCode = new OptionSetValue(1), // 1 = High
                        CaseOriginCode = new OptionSetValue(1), // 1 = Phone
                        CaseTypeCode = new OptionSetValue(2), // 2 = Problem
                        SubjectId =
                            new EntityReference(
                                Subject.EntityLogicalName,
                                _orgContext.CreateQuery<Subject>()
                                    .First().Id),  // use the default subject
                        Description = "Customer can't switch the product on.",
                        FollowupBy = DateTime.Now.AddHours(3.0), // follow-up in 3 hours
                        CustomerId = contact.ToEntityReference(),
                        Id = Guid.NewGuid()
                    };
                    _incidentId = serviceRequest.Id;
                    _orgContext.AddObject(serviceRequest);
                    _orgContext.Attach(contact);
                    _orgContext.AddLink(
                        serviceRequest,
                        new Relationship("incident_customer_contacts"),
                        contact);
                    SaveChangesHelper(serviceRequest, contact);
                    Console.WriteLine("Creating service case for contact.");

                    // Deactivate the Mary Kay Andersen contact record.
                    SetStateRequest setInactiveRequest = new SetStateRequest
                    {
                        EntityMoniker = contact.ToEntityReference(),
                        State = new OptionSetValue((int)ContactState.Inactive),
                        Status = new OptionSetValue(2)
                    };
                    _orgContext.Execute(setInactiveRequest);
                    Console.WriteLine("Deactivating the contact record.");

                    DeleteRequiredRecords(promptforDelete);
                }
                //</snippetBasicContextExamples1>
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }