Ejemplo n.º 1
0
        protected string GetUrlFromSettingsByName(string serviceUrl, IOrganizationService service)
        {
            string          url     = string.Empty;
            QueryExpression query   = new QueryExpression("new_parameter");
            ColumnSet       columns = new ColumnSet();

            columns.AddColumns("new_description",
                               "new_name",
                               "new_value");

            query.ColumnSet = columns;
            query.Criteria  = new FilterExpression();
            query.Criteria.FilterOperator = LogicalOperator.And;
            ConditionExpression conditionIdByName = new ConditionExpression("new_name", ConditionOperator.Equal, serviceUrl);

            query.Criteria.Conditions.AddRange(conditionIdByName);
            EntityCollection col = service.RetrieveMultiple(query);

            if (col.Entities.Count > 0)
            {
                if (col.Entities[0].Contains("new_value"))
                {
                    return(url = col.Entities[0].GetAttributeValue <string>("new_value"));
                }
            }

            return(url);
        }
Ejemplo n.º 2
0
        private Entity GetCurrencyDetail(Guid id, string[] Columns)
        {
            ConditionExpression conditionExpression = new ConditionExpression();

            conditionExpression.AttributeName = "transactioncurrencyid";
            conditionExpression.Operator      = ConditionOperator.Equal;
            conditionExpression.Values.Add((object)id);
            FilterExpression filterExpression = new FilterExpression();

            filterExpression.Conditions.Add(conditionExpression);
            filterExpression.FilterOperator = LogicalOperator.And;
            ColumnSet columnSet = new ColumnSet();

            columnSet.AddColumns(Columns);
            RetrieveMultipleResponse multipleResponse = (RetrieveMultipleResponse)this.service.Execute((OrganizationRequest) new RetrieveMultipleRequest()
            {
                Query = (QueryBase) new QueryExpression()
                {
                    ColumnSet  = columnSet,
                    Criteria   = filterExpression,
                    EntityName = "transactioncurrency"
                }
            });

            if (multipleResponse.EntityCollection.Entities != null && multipleResponse.EntityCollection.Entities.Count > 0)
            {
                return(Enumerable.First <Entity>((IEnumerable <Entity>)multipleResponse.EntityCollection.Entities));
            }
            else
            {
                return((Entity)null);
            }
        }
Ejemplo n.º 3
0
        private void AddRole(IOrganizationService service, string ObjectName, string solutionName)
        {
            ///Define fields to query
            string fieldQuery  = "name";
            string fieldReturn = "roleid";
            string entity      = "role";

            //Build query expression
            QueryExpression query  = new QueryExpression(entity);
            ColumnSet       column = new ColumnSet();

            column.AddColumns(new string[] { fieldReturn });
            query.ColumnSet = column;
            query.Criteria.AddCondition(new ConditionExpression(fieldQuery, ConditionOperator.Equal, ObjectName));

            //Retrieve records
            EntityCollection response = service.RetrieveMultiple(query);

            if (response == null || response.Entities.Count == 0)
            {
                AppendTextBox("Error: could not retrieve " + ObjectName);
                return;
            }

            Guid componentid   = (Guid)(response.Entities[0].Attributes[fieldReturn]);
            int  componentType = 20;

            AddComponent(service, solutionName, componentType, componentid);
            return;
        }
Ejemplo n.º 4
0
        private static void LabContactQuery(IOrganizationService service)
        {
            var qe = new QueryExpression("contact");
            var cs = new ColumnSet();
            var fe = new FilterExpression();
            var ce = new ConditionExpression();

            cs.AddColumns("fullname", "parentcustomerid");

            ce.AttributeName = "jobtitle";
            ce.Operator      = ConditionOperator.Equal;
            ce.Values.Add("Purchasing Manager");

            fe.AddCondition(ce);

            qe.ColumnSet = cs;
            qe.Criteria.AddFilter(fe);

            var contacts = service.RetrieveMultiple(qe);

            foreach (var a in contacts.Entities)
            {
                Console.WriteLine(a.Attributes["fullname"]);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Get a collection of Business Entities where the specified attribute(s) have the specified value(s)
        /// </summary>
        /// <param name="service">IOrganizationService to execute CRM requests.</param>
        /// <param name="entityName">Entity type to return e.g. "contact"</param>
        /// <param name="attributeNames">string array of attribute names e.g. {"field","field"}</param>
        /// <param name="attributeValues">object array of attribute values e.g. {"John", "Smith"}</param>
        /// <param name="columnsToReturn">Optional string array of columns to return. If null or empty, all columns are returned.</param>
        /// <param name="sortAttributeName">string of sorting attribute name</param>
        /// <param name="sortOrder">OrderType to order returned results either Ascending or Descending</param>
        /// <returns>EntityCollection of entities with attribute values that match the ones specified</returns>
        /// <example>GetEntityCollectionByAttributes(service, "contact", {"field","field"},{"John","Smith"},{"column"}) returns all contact entity instances where field=john and field=smith. Returns contactIDs only.</example>
        public static EntityCollection GetEntityCollectionByAttributes(IOrganizationService service, string entityName, string[] attributeNames, object[] attributeValues, string[] columnsToReturn, string sortAttributeName, OrderType sortOrder)
        {
            if (service != null && attributeNames != null && attributeValues != null)
            {
                if (attributeNames.Length != attributeValues.Length)
                {
                    throw new ArgumentException("Number of attribute names is not the same as number of attribute values");
                }

                QueryByAttribute attributeQuery = new QueryByAttribute();
                attributeQuery.EntityName = entityName;
                attributeQuery.Attributes.AddRange(attributeNames);
                if (columnsToReturn != null && columnsToReturn.Length > 0)
                {
                    ColumnSet columnSet = new ColumnSet();
                    columnSet.AddColumns(columnsToReturn);
                    attributeQuery.ColumnSet = columnSet;
                }

                attributeQuery.Values.AddRange(attributeValues);
                attributeQuery.AddOrder(sortAttributeName, sortOrder);
                RetrieveMultipleRequest request = new RetrieveMultipleRequest();
                request.Query = attributeQuery;

                RetrieveMultipleResponse response         = (RetrieveMultipleResponse)service.Execute(request);
                EntityCollection         returnedEntities = response.EntityCollection;

                return(returnedEntities);
            }

            return(null);
        }
Ejemplo n.º 6
0
        private static void LabAccountQuery(IOrganizationService service)
        {
            var qe = new QueryExpression();
            var cs = new ColumnSet();
            var fe = new FilterExpression();
            var ce = new ConditionExpression();

            cs.AddColumns("name", "accountid");

            ce.AttributeName = "statecode";
            ce.Operator      = ConditionOperator.Equal;
            ce.Values.Add("Active");

            fe.AddCondition(ce);

            qe.ColumnSet  = cs;
            qe.Criteria   = fe;
            qe.EntityName = "account";
            qe.AddOrder("name", OrderType.Ascending);

            var accountList = service.RetrieveMultiple(qe);

            foreach (var act in accountList.Entities)
            {
                Console.WriteLine("Name: {0}, Account Id: {1}", act.Attributes["name"], act.Attributes["accountid"]);
            }
        }
Ejemplo n.º 7
0
        public static Entity GetAutoNumberConfig(IOrganizationService oService, string strObjectType, string entityName)
        {
            EntityCollection ec = null;

            try
            {
                QueryExpression query = new QueryExpression();

                ColumnSet qpColSet      = new ColumnSet();
                string[]  strColumnList = { "pnp_autonumberid", "pnp_prefix", "pnp_counter", "pnp_suffix", "pnp_autonumberattribute" };
                qpColSet.AddColumns(strColumnList);
                query.ColumnSet  = qpColSet;
                query.EntityName = strObjectType;

                ConditionExpression ce = new ConditionExpression("pnp_name", ConditionOperator.Equal, entityName.Trim());
                query.Criteria.AddCondition(ce);

                RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
                retrieve.Query = query;

                ec = oService.RetrieveMultiple(query);
            }
            catch (SoapException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return((Entity)ec.Entities[0]);
        }
        private void RetrieveData()
        {
            var columns = this.attributes.Select(a => a.LogicalName).ToList();

            if (!columns.Contains(this.entity.PrimaryNameAttribute))
            {
                columns.Add(this.entity.PrimaryNameAttribute);
            }

            // Check if the record already exists on target organization
            var sourceqry = BuildFetchXml(entity.LogicalName, columns.ToArray(), Filter);

            var targetcolumnset = new ColumnSet(this.entity.PrimaryNameAttribute);

            // Make sure we have a state on the entity
            if (this.entity.Attributes.Any(a => a != null && !string.IsNullOrEmpty(a.LogicalName) && a.LogicalName.Equals("statecode")))
            {
                targetcolumnset.AddColumns("statecode", "statuscode");
            }
            var targetqry = new QueryExpression(entity.LogicalName)
            {
                ColumnSet = targetcolumnset
            };


            SetProgress(0, "Retrieving records...");
            var sourceRetrieveTask = Task.Factory.StartNew <EntityCollection>(() => { return(RetrieveAll(sourceService, sourceqry)); });
            var targetRetrieveTask = Task.Factory.StartNew <EntityCollection>(() => { return(RetrieveAll(targetService, targetqry)); });

            Task.WaitAll(sourceRetrieveTask, targetRetrieveTask);

            sourceRecords = sourceRetrieveTask.Result;
            targetRecords = targetRetrieveTask.Result;
        }
Ejemplo n.º 9
0
        private EntityCollection getExisitingAccountDetails(Guid _accountId)
        {
            ColumnSet accountColumns = new ColumnSet("name", "fdx_goldmineaccountnumber", "fdx_gonogo", "address1_line1", "address1_line2", "address1_city", "fdx_stateprovinceid", "fdx_zippostalcodeid", "telephone1");

            accountColumns.AddColumns("fdx_prospectgroup", "defaultpricelevelid", "fdx_prospectpriority", "fdx_prospectscore", "fdx_prospectpercentile", "fdx_ratesource", "fdx_pprrate", "fdx_subrate", "fdx_prospectradius", "fdx_prospectdatalastupdated", "fdx_prospectscoreblankmessage");
            QueryExpression  accountQuery      = CRMQueryExpression.getQueryExpression("account", accountColumns, new CRMQueryExpression[] { new CRMQueryExpression("accountid", ConditionOperator.Equal, _accountId) });
            EntityCollection accountCollection = service.RetrieveMultiple(accountQuery);

            return(accountCollection);
        }
Ejemplo n.º 10
0
        public JsonResult ContactReassignmentEmail(dynamic data)
        {
            log.Info("DuplicateContactEmailToSupport");

            string    hdcSupportEmail = ConfigurationManager.AppSettings["HDCSupportEmail"];
            ColumnSet columns         = new ColumnSet();

            columns.AddColumns(new string[] { "firstname", "lastname", "emailaddress1", "concap_loggedinuser" });
            Entity duplicateContact = EntityApiUtils.ReadContactByEmail(ServiceProxy, data.duplicateContactEmail.Value, columns);
            Entity rep       = EntityApiUtils.ReadContactById(ServiceProxy, Guid.Parse(data.repId.Value), new ColumnSet(true));
            Entity owningRep = null;

            string contactFirstName = EntityApiUtils.GetStringValue(duplicateContact, "firstname");
            string contactLastName  = EntityApiUtils.GetStringValue(duplicateContact, "lastname");
            string submitedRepName  = EntityApiUtils.GetStringValue(rep, "fullname");
            string owningRepName    = "";
            string repEmail         = EntityApiUtils.GetStringValue(rep, "emailaddress1");

            if (duplicateContact.Contains("concap_loggedinuser"))
            {
                owningRepName = ((EntityReference)duplicateContact["concap_loggedinuser"]).Name;
                owningRep     = EntityApiUtils.ReadContactById(ServiceProxy, ((EntityReference)duplicateContact["concap_loggedinuser"]).Id, new ColumnSet(true));
            }

            string emailDescription = "<p>HDC App Admin,</p>";

            emailDescription += "<p>I am requesting that the contact below gets reassigned to me:</p>";
            emailDescription += "<ul><li>" + contactFirstName + " " + contactLastName + "</li>";
            emailDescription += "<li>" + data.duplicateContactEmail.Value + "</li></ul>";
            emailDescription += "<p>Please contact me for details.</p>";

            emailDescription += "<p><strong>TTI Rep requesting contact reassignment: </strong></p>";
            emailDescription += "<ul><li>" + submitedRepName + "</li>";
            emailDescription += "<li>" + EntityApiUtils.GetStringValue(rep, "store.concap_name") + ", " + EntityApiUtils.GetStringValue(rep, "store.concap_city") + ", " + EntityApiUtils.GetStringValue(rep, "store.concap_stateprovince") + "</li>";
            emailDescription += "<li>" + EntityApiUtils.GetStringValue(rep, "telephone1") + "</li>";
            emailDescription += "<li>" + EntityApiUtils.GetStringValue(rep, "emailaddress1") + "</li></ul>";

            emailDescription += "<p><strong>TTI Rep who owns existing contact: </strong></p>";
            emailDescription += "<ul><li>" + owningRepName + "</li>";
            emailDescription += "<li>" + EntityApiUtils.GetStringValue(owningRep, "store.concap_name") + ", " + EntityApiUtils.GetStringValue(rep, "store.concap_city") + ", " + EntityApiUtils.GetStringValue(rep, "store.concap_stateprovince") + "</li>";
            emailDescription += "<li>" + EntityApiUtils.GetStringValue(owningRep, "telephone1") + "</li>";
            emailDescription += "<li>" + EntityApiUtils.GetStringValue(owningRep, "emailaddress1") + "</li></ul>";

            emailDescription += "<p><strong>TTI Manager of existing contact owner: </strong></p>";
            emailDescription += "<ul><li>" + EntityApiUtils.GetStringValue(owningRep, "manager.concap_name") + "</li>";
            emailDescription += "<li>" + EntityApiUtils.GetStringValue(owningRep, "manager.emailaddress") + "</li></ul>";

            log.Info("Sending reassignment email...");
            var task = SendEmailAsync(repEmail, hdcSupportEmail, repEmail, "HDC Contact Reassignment Request", emailDescription, null);

            return(new JsonResult()
            {
                Data = "An email has been submitted for contact reassignment.  An Administrator will be in contact with you regarding this request"
            });
        }
        // Method to calculate price in an invoice
        private static void CalculateInvoice(EntityReference entity, IOrganizationService service)
        {
            Entity         e         = service.Retrieve(entity.LogicalName, entity.Id, new ColumnSet("statecode"));
            OptionSetValue statecode = (OptionSetValue)e["statecode"];

            if (statecode.Value == 0)
            {
                ColumnSet columns = new ColumnSet();
                columns.AddColumns("totaltax", "totallineitemamount", "totalamountlessfreight", "discountamount");

                Entity invoice = service.Retrieve(entity.LogicalName, entity.Id, columns);

                QueryExpression query = new QueryExpression("invoicedetail");
                query.ColumnSet.AddColumns("quantity", "invoiceispricelocked", "priceperunit");
                query.Criteria.AddCondition("invoiceid", ConditionOperator.Equal, entity.Id);

                QueryExpression query1 = new QueryExpression("invoicedetail");
                query1.ColumnSet.AddColumns("quantity", "invoiceispricelocked");
                query1.Criteria.AddCondition("invoiceid", ConditionOperator.Equal, entity.Id);

                EntityCollection ec  = service.RetrieveMultiple(query);
                EntityCollection ec1 = service.RetrieveMultiple(query1);

                invoice["totallineitemamount"] = 0;

                decimal total    = 0;
                decimal discount = 0;
                decimal tax      = 0;

                for (int i = 0; i < ec.Entities.Count; i++)
                {
                    total = total + ((decimal)ec.Entities[i]["quantity"] * ((Money)ec.Entities[i]["priceperunit"]).Value);
                    (ec1.Entities[i])["extendedamount"] = new Money(((decimal)ec.Entities[i]["quantity"] * ((Money)ec.Entities[i]["priceperunit"]).Value));
                    service.Update(ec1.Entities[i]);
                }

                invoice["totallineitemamount"] = new Money(total);

                // Calculate discount based on the total amount
                discount = CalculateDiscount(total);
                total    = total - discount;
                invoice["discountamount"]         = new Money(discount);
                invoice["totalamountlessfreight"] = new Money(total);
                service.Update(invoice);

                // Calculate tax after the discount is applied
                tax   = CalculateTax(total);
                total = total + tax;
                invoice["totaltax"]    = new Money(tax);
                invoice["totalamount"] = new Money(total);
                service.Update(invoice);
            }
            return;
        }
Ejemplo n.º 12
0
 private byte[] GetAnnotationBody(IOrganizationService orgService, Annotation annotation)
 {
     if (annotation != null)
     {
         ColumnSet columnSet = new ColumnSet();
         columnSet.AddColumns(Annotation.Fields.AnnotationId, Annotation.Fields.DocumentBody);
         Entity annotationEntity = orgService.Retrieve(Annotation.EntityLogicalName, annotation.Id, columnSet);
         object documentBody     = annotationEntity[Annotation.Fields.DocumentBody];
         return(documentBody == null || string.IsNullOrEmpty((string)documentBody) ? null : Convert.FromBase64String((string)documentBody));
     }
     return(null);
 }
Ejemplo n.º 13
0
        public void Can_add_attributes()
        {
            var       strongTypeColumnSet = new ColumnSet <xts_entity>();
            ColumnSet columnSet           = strongTypeColumnSet;

            strongTypeColumnSet.AddColumns(
                e => e.xts_attribute,
                e => e.xts_withcolumnattribute
                );
            Assert.Equal(2, strongTypeColumnSet.Columns.Count());
            Assert.Equal(2, columnSet.Columns.Count);
            Assert.Equal("xts_attribute", columnSet.Columns[0]);
            Assert.Equal("xts_column", columnSet.Columns[1]);
        }
Ejemplo n.º 14
0
        public void Extensions_ColumnSet_AddColumns()
        {
            var cs = new ColumnSet();

            cs.AddColumns <TestColumnSetEntity>(c => new { c.TestColumnSetEntity1 });
            Assert.AreEqual("testcolumnsetentity", cs.Columns.Single());

            cs = new ColumnSet();
            cs.AddColumns <TestColumnSetEntity>(c => new { c.Id });
            Assert.AreEqual("testcolumnsetentityid", cs.Columns.Single());

            cs = new ColumnSet();
            cs.AddColumns <TestColumnSetEntity>(c => new { c.CreatedOn });
            Assert.AreEqual("createdon", cs.Columns.Single());
        }
Ejemplo n.º 15
0
        public void AddColumns_Test()
        {
            // Setup
            ColumnSet <TestEntity> columnSet = new ColumnSet <TestEntity>();
            string expected1 = nameof(TestEntity.ReferenceTypeProperty).ToLower();
            string expected2 = nameof(TestEntity.ValueTypeProperty).ToLower();

            // Act
            columnSet.AddColumns(t => t.ReferenceTypeProperty, t => t.ValueTypeProperty);
            var actual = columnSet.Columns;

            // Assert
            Assert.AreEqual(2, actual.Count);
            Assert.AreEqual(expected1, actual[0]);
            Assert.AreEqual(expected2, actual[1]);
        }
Ejemplo n.º 16
0
        public void AddColumnsTest()
        {
            // Setup
            string expectedColumn1 = nameof(TestEntity.ReferenceTypeProperty).ToLower();
            string expectedColumn2 = nameof(TestEntity.ValueTypeProperty).ToLower();

            // Act
            ColumnSet columnSet = new ColumnSet();

            columnSet.AddColumns <TestEntity>(t => t.ReferenceTypeProperty, t => t.ValueTypeProperty);

            // Assert
            Assert.AreEqual(2, columnSet.Columns.Count);
            Assert.AreEqual(expectedColumn1, columnSet.Columns[0]);
            Assert.AreEqual(expectedColumn2, columnSet.Columns[1]);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Reloads the attributes from CRM
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="service"></param>
        /// <returns></returns>
        public static T Reload <T>(this T entity, IOrganizationService service) where T : Entity
        {
            foreach (var aliased in entity.Attributes.Where(a => a.Key.Contains('.') || a.Value is AliasedValue).ToList())
            {
                entity.Attributes.Remove(aliased.Key);
            }

            var columns = new ColumnSet(false);

            columns.AddColumns(entity.Attributes.Keys.ToArray());
            var value = service.GetEntity <T>(entity.Id, columns);

            entity.Attributes = value.Attributes;

            return(entity);
        }
Ejemplo n.º 18
0
        private static QueryExpression GetContactsQuery(string[] fields)
        {
            if (fields.Length == 0) //Returnerar en query med bestämda attributes eller samtliga
            {
                return(new QueryExpression {
                    EntityName = "contact", ColumnSet = new ColumnSet(true)
                });
            }

            var columnSet = new ColumnSet();

            fields = fields.Select(s => s.ToLowerInvariant()).ToArray();
            columnSet.AddColumns(fields);

            return(new QueryExpression {
                EntityName = "contact", ColumnSet = columnSet
            });
        }
        /// <summary>
        /// This method returns Translator API settings object
        /// </summary>
        /// <param name="service">IOrganizationService object</param>
        /// <param name="tracingService">ITracingService object</param>
        /// <returns>TranslateApiSettings object</returns>
        internal static TranslateApiSettings GetTranslatorAPISettings(IOrganizationService service, ITracingService tracingService)
        {
            EntityCollection     retrieved;
            TranslateApiSettings apiSettings = new TranslateApiSettings();
            var cols = new ColumnSet();

            cols.AddColumns(new string[] { "msdyn_apikey", "msdyn_name", "msdyn_isautotranslationenabled" });
            try
            {
                var query = new QueryExpression
                {
                    ColumnSet  = cols,
                    EntityName = "msdyn_automatickmtranslationsetting",
                };
                retrieved = service.RetrieveMultiple(query);
                if (retrieved.Entities.Count == 1)
                {
                    if (retrieved.Entities[0].Attributes.Contains("msdyn_apikey"))
                    {
                        apiSettings.ClientSecret = (string)retrieved.Entities[0].Attributes["msdyn_apikey"];
                    }

                    if (retrieved.Entities[0].Attributes.Contains("msdyn_name"))
                    {
                        apiSettings.ClientID = (string)retrieved.Entities[0].Attributes["msdyn_name"];
                    }

                    if (retrieved.Entities[0].Attributes.Contains("msdyn_isautotranslationenabled"))
                    {
                        apiSettings.Isautotranslationenabled = (bool)retrieved.Entities[0].Attributes["msdyn_isautotranslationenabled"];
                    }
                }
            }
            catch (Exception ex)
            {
                tracingService.Trace("GetTranslatorAPISettings: {0}", ex.Message);
            }
            return(apiSettings);
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            QueryExpression  qe = new QueryExpression("contact");
            ColumnSet        cs = new ColumnSet();
            FilterExpression fe = new FilterExpression();

            //ConditionExpression ce = new ConditionExpression();
            cs.AddColumns("fullname", "parentcustomerid");
            //ce.AttributeName = "jobtitle";
            //ce.Operator = ConditionOperator.Equal;
            //ce.Values.Add("Менеджер по закупкам");
            //fe.AddCondition(ce);
            qe.ColumnSet = cs;
            qe.Criteria.AddFilter(fe);
            EntityCollection contacts = Service.Service.GetOrganization().RetrieveMultiple(qe);

            foreach (var item in contacts.Entities)
            {
                Console.WriteLine(item.Attributes["fullname"].ToString());
            }
            Console.Read();
        }
        /// <summary>
        /// This method returns record of automatickmtranslationsetting custom entity
        /// </summary>
        /// <param name="service">IOrganizationService object</param>
        /// <param name="tracingService">ITracingService object</param>
        /// <returns>returns count of records</returns>
        internal static int GetTranslatorAPISettingsRecordsCount(IOrganizationService service, ITracingService tracingService)
        {
            EntityCollection retrieved;
            int recordsCount = 0;
            var cols         = new ColumnSet();

            cols.AddColumns(new string[] { "msdyn_apikey", "msdyn_name", "msdyn_isautotranslationenabled" });
            try
            {
                var query = new QueryExpression
                {
                    ColumnSet  = cols,
                    EntityName = "msdyn_automatickmtranslationsetting",
                };
                retrieved    = service.RetrieveMultiple(query);
                recordsCount = retrieved.Entities.Count;
            }
            catch (Exception ex)
            {
                tracingService.Trace("GetTranslatorAPISettingsRecordsCount: {0}", ex.Message);
            }
            return(recordsCount);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// This method saves the record
        /// </summary>
        /// <returns></returns>
        public async System.Threading.Tasks.Task <Entity> Save()
        {
            Entity modifiedRecord;

            // If it is regarding, then pass all the record information which contains mapped data to modifiedrecord.
            if (isRegarding)
            {
                modifiedRecord = Record;
            }
            // Otherwise, create blank record
            else
            {
                modifiedRecord = new Entity();
            }
            modifiedRecord.LogicalName = EntityMetadataEx.EntityMetadata.LogicalName;

            // If update, then assign Id
            if (isUpdate)
            {
                modifiedRecord.Id = Record.Id;
            }

            // Only update modified fields
            foreach (var field in Fields)
            {
                // If no data changed, then no need to pass the value.
                if (isUpdate && field.FieldData == Record[field.FieldMetadata.LogicalName])
                {
                    continue;
                }
                // If required fields have no value, then show error message.
                if ((bool)field.FieldMetadata.IsValidForCreate && (field.FieldMetadata.RequiredLevel.Value == AttributeRequiredLevel.ApplicationRequired ||
                                                                   field.FieldMetadata.RequiredLevel.Value == AttributeRequiredLevel.SystemRequired) &&
                    field.FieldData == null)
                {
                    MessageDialog dialog = new MessageDialog(string.Format(loader.GetString("RequiredField"), field.FieldMetadata.DisplayName.UserLocalizedLabel.Label));
                    await dialog.ShowAsync();

                    lvFields.SelectedItem = ((lvFields.FindName("lbl" + field.FieldMetadata.LogicalName) as TextBlock).Parent as StackPanel).Parent;
                    lvFields.UpdateLayout();
                    lvFields.ScrollIntoView(lvFields.SelectedItem);
                    return(null);
                }
                // If value has been changed, then pass the data to modified record.
                modifiedRecord[field.FieldMetadata.LogicalName] = field.FieldData;
            }

            progressRing.IsActive = true;

            // Create/Update record.
            Entity result = await CRMHelper.UpsertRecord(modifiedRecord);

            // If this is update then retrieve latest data again from server after update and return.
            if (isUpdate)
            {
                ColumnSet columnSet = new ColumnSet();
                columnSet.AddColumns(Fields.Select(x => x.FieldMetadata.LogicalName).ToArray());

                return(await CRMHelper.RetrieveRecord(EntityMetadataEx.EntityMetadata, result.Id, columnSet));
            }
            // If this is new record, then simply return result.
            else
            {
                return(result);
            }
        }
Ejemplo n.º 23
0
        public void Execute(IServiceProvider serviceProvider)
        {
            //  throw new InvalidPluginExecutionException("proceedInReservation " + proceedInReservation);
            //throw new InvalidPluginExecutionException("ghada ^_^");

            #region definitionAttributes
            string          entityName  = "new_contracting";
            EntityReference destination = null;
            #endregion

            //Extract the tracing service for use in debugging sandboxed plug-ins.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                if (context.Depth > 1)
                {
                    return;
                }


                // The InputParameters collection contains all the data passed in the message request.
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    // Obtain the target entity from the input parameters.
                    Entity entity = (Entity)context.InputParameters["Target"];

                    // Verify that the target entity represents an sale.
                    // If not, this plug-in was not registered correctly.
                    if (entity.LogicalName != entityName)
                    {
                        return;
                    }

                    var proceedInReservation = new OptionSetValue();
                    if (entity.Attributes.Contains("ohd_proceedinreservationos"))
                    {
                        proceedInReservation = entity.GetAttributeValue <OptionSetValue>("ohd_proceedinreservationos");
                    }

                    //Update
                    if (context.MessageName.ToLower() == "update")
                    {
                        #region Retrieve All Blob Storage
                        // Instantiate QueryExpression QEohd_blobstorage
                        var QEohd_blobstorage = new QueryExpression("ohd_blobstorage");

                        // Add columns to QEohd_blobstorage.ColumnSet
                        QEohd_blobstorage.ColumnSet.AddColumns("createdon", "ohd_uri", "ohd_url", "ohd_blobstorageid");
                        QEohd_blobstorage.AddOrder("ohd_uri", OrderType.Ascending);

                        // Define filter QEohd_blobstorage.Criteria
                        QEohd_blobstorage.Criteria.AddCondition("ohd_blobazurestorageid", ConditionOperator.Equal, context.PrimaryEntityId);

                        // Add link-entity QEohd_blobstorage_new_contracting
                        var QEohd_blobstorage_new_contracting = QEohd_blobstorage.AddLink("new_contracting", "ohd_blobazurestorageid", "new_contractingid");
                        QEohd_blobstorage_new_contracting.EntityAlias = "al";

                        // Add link-entity QEohd_blobstorage_new_contracting_ohd_destination
                        var QEohd_blobstorage_new_contracting_ohd_destination = QEohd_blobstorage_new_contracting.AddLink("ohd_destination", "ohd_destination", "ohd_destinationid");
                        QEohd_blobstorage_new_contracting_ohd_destination.EntityAlias = "am";

                        // Define filter QEohd_blobstorage_new_contracting_ohd_destination.LinkCriteria
                        QEohd_blobstorage_new_contracting_ohd_destination.LinkCriteria.AddCondition("ohd_name", ConditionOperator.Equal, "Owest");

                        var blobStorageResult = service.RetrieveMultiple(QEohd_blobstorage);
                        #endregion

                        #region Retrieve Sale Recod to Get Destination

                        //retrieve contact record
                        ColumnSet fields = new ColumnSet()
                        {
                            AllColumns = false
                        };
                        fields.AddColumns("ohd_destination");
                        Entity saleEntity = service.Retrieve(entityName, context.PrimaryEntityId, fields);
                        #endregion

                        if (saleEntity != null)
                        {
                            destination = saleEntity.Contains("ohd_destination") ? (EntityReference)saleEntity.Attributes["ohd_destination"] : new EntityReference();

                            if ((blobStorageResult == null || blobStorageResult.Entities.Count < 1) &&
                                (int)(proceedInReservation.Value) == 1 &&
                                (destination != null && destination.Name.ToLower() == "Owest".ToLower()))
                            {
                                //throw new InvalidPluginExecutionException("Sorry!! You must choose at least one attachment related to the sale");
                                throw new InvalidPluginExecutionException("Please attach required file(s) to proceed in reservation");
                            }
                            else
                            {
                                return;
                            }
                        }
                    }

                    //Create
                    else if (context.MessageName.ToLower() == "create")
                    {
                        // throw new InvalidPluginExecutionException("ghada 1");

                        destination = entity.Attributes.Contains("ohd_destination") ? (Microsoft.Xrm.Sdk.EntityReference)entity.Attributes["ohd_destination"] : new EntityReference();

                        #region Retrieve Sale Recod to Get Destination

                        //retrieve contact record
                        ColumnSet fields = new ColumnSet()
                        {
                            AllColumns = false
                        };
                        fields.AddColumns("ohd_name");
                        Entity saleEntity = service.Retrieve("ohd_destination", destination.Id, fields);
                        #endregion

                        if (saleEntity != null)
                        {
                            if ((int)(proceedInReservation.Value) == 1 && (destination != null && saleEntity["ohd_name"].ToString().ToLower() == "Owest".ToLower()))
                            {
                                entity.Attributes["ohd_proceedinreservationos"] = new OptionSetValue(0);
                            }
                        }
                        else
                        {
                            return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message, ex);
            }
        }
Ejemplo n.º 24
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);

                    #region Demonstrate
                    // TODO Add demonstration code here
                    //<snippetCreateandublishProducts1>
                    // Create a product family
                    Product newProductFamily = new Product
                    {
                        Name             = "Example Product Family",
                        ProductNumber    = "PF001",
                        ProductStructure = new OptionSetValue(2)
                    };
                    _productFamilyId = _serviceProxy.Create(newProductFamily);
                    Console.WriteLine("\nCreated '{0}'", newProductFamily.Name);

                    // Create a product property
                    DynamicProperty newProperty = new DynamicProperty
                    {
                        Name = "Example Property",
                        RegardingObjectId = new EntityReference(Product.EntityLogicalName,
                                                                _productFamilyId),
                        IsReadOnly         = true,
                        IsRequired         = true,
                        IsHidden           = false,
                        DataType           = new OptionSetValue(3), //Single line of text
                        DefaultValueString = "Default Value"
                    };
                    _productPropertyId = _serviceProxy.Create(newProperty);
                    Console.WriteLine("\nCreated '{0}' for the product family", newProperty.Name);

                    // Create couple of product records under the product family
                    Product newProduct1 = new Product
                    {
                        Name                 = "Example Product 1",
                        ProductNumber        = "P001",
                        ProductStructure     = new OptionSetValue(1),
                        ParentProductId      = new EntityReference(Product.EntityLogicalName, _productFamilyId),
                        QuantityDecimal      = 2,
                        DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId),
                        DefaultUoMId         = new EntityReference(UoM.EntityLogicalName, _unit.Id)
                    };
                    _product1Id = _serviceProxy.Create(newProduct1);

                    Console.WriteLine("\nCreated '{0}' under the product family", newProduct1.Name);

                    Product newProduct2 = new Product
                    {
                        Name                 = "Example Product 2",
                        ProductNumber        = "P002",
                        ProductStructure     = new OptionSetValue(1),
                        ParentProductId      = new EntityReference(Product.EntityLogicalName, _productFamilyId),
                        QuantityDecimal      = 2,
                        DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId),
                        DefaultUoMId         = new EntityReference(UoM.EntityLogicalName, _unit.Id)
                    };
                    _product2Id = _serviceProxy.Create(newProduct2);

                    Console.WriteLine("Created '{0}' under the product family", newProduct2.Name);

                    // Create a price list items for the products
                    ProductPriceLevel newPriceListItem1 = new ProductPriceLevel
                    {
                        PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                        ProductId    = new EntityReference(Product.EntityLogicalName, _product1Id),
                        UoMId        = new EntityReference(UoM.EntityLogicalName, _unit.Id),
                        Amount       = new Money(20)
                    };
                    _priceListItem1Id = _serviceProxy.Create(newPriceListItem1);

                    Console.WriteLine("\nCreated price list for '{0}'", newProduct1.Name);

                    ProductPriceLevel newPriceListItem2 = new ProductPriceLevel
                    {
                        PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                        ProductId    = new EntityReference(Product.EntityLogicalName, _product2Id),
                        UoMId        = new EntityReference(UoM.EntityLogicalName, _unit.Id),
                        Amount       = new Money(20)
                    };
                    _priceListItem2Id = _serviceProxy.Create(newPriceListItem2);

                    Console.WriteLine("Created price list for '{0}'", newProduct2.Name);

                    // Set the product relationship
                    // Set Example Product 1 and Example Product 2 as substitute of each other (bi-directional)
                    ProductSubstitute newProductRelation = new ProductSubstitute
                    {
                        SalesRelationshipType = new OptionSetValue(3),
                        Direction             = new OptionSetValue(1),
                        ProductId             = new EntityReference(Product.EntityLogicalName, _product1Id),
                        SubstitutedProductId  = new EntityReference(Product.EntityLogicalName, _product2Id)
                    };
                    _productRelationId = _serviceProxy.Create(newProductRelation);

                    Console.WriteLine("\nCreated a substitute relation between the two products.");
                    //</snippetCreateandublishProducts1>

                    // Override a product property at the product level
                    // In this case we will override the property for 'Example Product 1'
                    DynamicProperty newOverrideProperty = new DynamicProperty();
                    newOverrideProperty.BaseDynamicPropertyId = new EntityReference(DynamicProperty.EntityLogicalName,
                                                                                    _productPropertyId);
                    newOverrideProperty.RegardingObjectId = new EntityReference(Product.EntityLogicalName, _product1Id);
                    _productOverridenPropertyId           = _serviceProxy.Create(newOverrideProperty);

                    // Retrieve the attributes of the cloned property you want to update
                    ColumnSet columns = new ColumnSet();
                    columns.AddColumns("name", "isreadonly", "isrequired");
                    DynamicProperty retrievedOverridenProperty = (DynamicProperty)_serviceProxy.Retrieve(
                        DynamicProperty.EntityLogicalName, _productOverridenPropertyId,
                        columns);

                    // Update the attributes
                    retrievedOverridenProperty.Name       = "Overridden Example Property";
                    retrievedOverridenProperty.IsReadOnly = true;
                    retrievedOverridenProperty.IsRequired = false;
                    _serviceProxy.Update(retrievedOverridenProperty);
                    Console.WriteLine("\nOverridden the product property for 'Example Product 1'.");

                    // Prompt the user whether to publish the product family and products
                    bool publishRecords = true;
                    Console.WriteLine("\nDo you want the product records published? (y/n)");
                    String answer = Console.ReadLine();
                    publishRecords = (answer.StartsWith("y") || answer.StartsWith("Y"));

                    if (publishRecords)
                    {
                        PublishProductHierarchyRequest publishReq = new PublishProductHierarchyRequest
                        {
                            Target = new EntityReference(Product.EntityLogicalName, _productFamilyId)
                        };
                        PublishProductHierarchyResponse published = (PublishProductHierarchyResponse)_serviceProxy.Execute(publishReq);
                        if (published.Results != null)
                        {
                            Console.WriteLine("Published the product records");
                        }

                        // Overwrite a product property
                        Console.WriteLine("\nRevising 'Example Product 1' to demonstrate product property overwrite.");

                        // Retrieve the StateCode of Product that you want to revise
                        ColumnSet cols = new ColumnSet();
                        cols.AddColumns("name", "statecode");
                        Product retrievedPublishedProduct = (Product)_serviceProxy.Retrieve(
                            Product.EntityLogicalName, _product1Id,
                            cols);

                        // Update the state of the Product to "Under Revision"
                        retrievedPublishedProduct.StateCode = ProductState.UnderRevision;
                        UpdateRequest updatePropertyState = new UpdateRequest
                        {
                            Target = retrievedPublishedProduct
                        };
                        _serviceProxy.Execute(updatePropertyState);
                        Console.WriteLine("\nChanged '{0}' to 'Under Revision' state.", retrievedPublishedProduct.Name);

                        DynamicProperty newOverwriteProperty = new DynamicProperty();
                        newOverwriteProperty.BaseDynamicPropertyId = new EntityReference(DynamicProperty.EntityLogicalName,
                                                                                         _productOverridenPropertyId);
                        newOverwriteProperty.RegardingObjectId = new EntityReference(Product.EntityLogicalName,
                                                                                     _product1Id);
                        _productOverwrittenPropertyId = _serviceProxy.Create(newOverwriteProperty);

                        // Retrieve the attributes of the cloned property you want to update
                        ColumnSet myCols = new ColumnSet();
                        myCols.AddColumns("name", "isreadonly", "isrequired");
                        DynamicProperty retrievedOverwrittenProperty = (DynamicProperty)_serviceProxy.Retrieve(
                            DynamicProperty.EntityLogicalName, _productOverwrittenPropertyId,
                            myCols);

                        // Update the attributes of the cloned property to complete the overwrite
                        retrievedOverwrittenProperty.Name       = "Overwritten Example Property";
                        retrievedOverwrittenProperty.IsReadOnly = true;
                        retrievedOverridenProperty.IsRequired   = false;
                        _serviceProxy.Update(retrievedOverwrittenProperty);
                        Console.WriteLine("\nOverwritten the product property for 'Example Product 1'.");

                        // Retrieve the StateCode of Product that you want to publish
                        ColumnSet prodCols = new ColumnSet();
                        prodCols.AddColumns("name", "statecode");
                        Product retrievedRevisedProduct = (Product)_serviceProxy.Retrieve(
                            Product.EntityLogicalName, _product1Id,
                            prodCols);

                        // Update the state of the Product to "Active"
                        retrievedRevisedProduct.StateCode = ProductState.Active;
                        UpdateRequest publishProduct1 = new UpdateRequest
                        {
                            Target = retrievedRevisedProduct
                        };
                        _serviceProxy.Execute(publishProduct1);
                        Console.WriteLine("\nPublished '{0}'.", retrievedRevisedProduct.Name);
                    }
                    #endregion Demonstrate
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Ejemplo n.º 25
0
        // Method to calculate price in an invoice
        private static void CalculateInvoice(EntityReference entity, IOrganizationService service)
        {
            Entity e = service.Retrieve(entity.LogicalName, entity.Id, new ColumnSet("statecode"));
            OptionSetValue statecode = (OptionSetValue)e["statecode"];
            if (statecode.Value == 0)
            {
                ColumnSet columns = new ColumnSet();
                columns.AddColumns("totaltax", "totallineitemamount", "totalamountlessfreight", "discountamount");

                Entity invoice = service.Retrieve(entity.LogicalName, entity.Id, columns);

                QueryExpression query = new QueryExpression("invoicedetail");
                query.ColumnSet.AddColumns("quantity", "invoiceispricelocked", "priceperunit");
                query.Criteria.AddCondition("invoiceid", ConditionOperator.Equal, entity.Id);

                QueryExpression query1 = new QueryExpression("invoicedetail");
                query1.ColumnSet.AddColumns("quantity", "invoiceispricelocked");
                query1.Criteria.AddCondition("invoiceid", ConditionOperator.Equal, entity.Id);

                EntityCollection ec = service.RetrieveMultiple(query);
                EntityCollection ec1 = service.RetrieveMultiple(query1);
                
                invoice["totallineitemamount"] = 0;

                decimal total = 0;
                decimal discount = 0;
                decimal tax = 0;

                for (int i = 0; i < ec.Entities.Count; i++)
                {
                    total = total + ((decimal)ec.Entities[i]["quantity"] * ((Money)ec.Entities[i]["priceperunit"]).Value);
                    (ec1.Entities[i])["extendedamount"] = new Money(((decimal)ec.Entities[i]["quantity"] * ((Money)ec.Entities[i]["priceperunit"]).Value));
                    service.Update(ec1.Entities[i]);
                }

                invoice["totallineitemamount"] = new Money(total);

                // Calculate discount based on the total amount
                discount = CalculateDiscount(total);
                total = total - discount;
                invoice["discountamount"] = new Money(discount);
                invoice["totalamountlessfreight"] = new Money(total);
                service.Update(invoice);

                // Calculate tax after the discount is applied
                tax = CalculateTax(total);
                total = total + tax;
                invoice["totaltax"] = new Money(tax);
                invoice["totalamount"] = new Money(total);                
                service.Update(invoice);
            }
            return;
        }        
Ejemplo n.º 26
0
        /// <summary>
        /// Retrieve the Id for each entityName that has a filterAttribute value in the filterIdList.
        /// </summary>
        private static List <Guid> RetrieveReferenceAttributeIds(CrmOrganization org, string entityName,
                                                                 string retrieveAttribute, string filterAttribute, IList <Guid> filterIdList)
        {
            #region Argument Validation

            if (org == null)
            {
                throw new ArgumentNullException("org");
            }
            else if (entityName == null)
            {
                throw new ArgumentNullException("entityName");
            }
            else if (retrieveAttribute == null)
            {
                throw new ArgumentNullException("retrieveAttribute");
            }
            else if (filterAttribute == null)
            {
                throw new ArgumentNullException("filterAttribute");
            }
            else if (retrieveAttribute == filterAttribute)
            {
                throw new ArgumentException("Attributes must be different");
            }

            #endregion Argument Validation

            if (filterIdList.Count == 0)
            {
                return(new List <Guid>());
            }

            //Generate the query
            var cols = new ColumnSet();
            cols.AddColumns(retrieveAttribute);

            var idCondition = new ConditionExpression();
            idCondition.AttributeName = filterAttribute;
            idCondition.Operator      = ConditionOperator.In;
            idCondition.Values.Clear();
            idCondition.Values.AddRange(ConvertIdArrayToObjectArray(filterIdList));

            var query = new QueryExpression();
            query.ColumnSet = cols;
            query.Criteria.AddCondition(idCondition);
            query.EntityName = entityName;

            //Loop through the results
            var resultList = new List <Guid>();
            foreach (var entity in org.OrganizationService.RetrieveMultipleAllPages(query).Entities)
            {
                foreach (KeyValuePair <string, object> prop in entity.Attributes)
                {
                    if (prop.Key == retrieveAttribute)
                    {
                        Type propType = prop.Value.GetType();
                        if (propType == typeof(Guid))
                        {
                            resultList.Add((Guid)prop.Value);
                        }
                        else if (propType == typeof(EntityReference))
                        {
                            resultList.Add(((EntityReference)prop.Value).Id);
                        }
                        else
                        {
                            throw new ArgumentException("Unknown property returned " + prop.GetType().FullName);
                        }
                    }
                }
            }

            return(resultList);
        }
Ejemplo n.º 27
0
        protected string GetUrlFromSettingsByName(string serviceUrl, IOrganizationService service)
        {
            string url = string.Empty;
            QueryExpression query = new QueryExpression("new_parameter");
            ColumnSet columns = new ColumnSet();
            columns.AddColumns("new_description",
                    "new_name",
                    "new_value");

            query.ColumnSet = columns;
            query.Criteria = new FilterExpression();
            query.Criteria.FilterOperator = LogicalOperator.And;
            ConditionExpression conditionIdByName = new ConditionExpression("new_name", ConditionOperator.Equal, serviceUrl);
            query.Criteria.Conditions.AddRange(conditionIdByName);
            EntityCollection col = service.RetrieveMultiple(query);
            if (col.Entities.Count > 0)
            {
                if (col.Entities[0].Contains("new_value"))
                {
                    return url = col.Entities[0].GetAttributeValue<string>("new_value");
                }

            }

            return url;
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate creating all entity records that this sample requires.
        /// Create a product family with a product property and two child product records.
        /// Create a substitute relation between the two products.
        /// Override the product property for one of the child products.
        /// Publish the product family hierarchy, including the child records.
        /// Revise a child product to overwrite the overridden property.
        /// Publish the child product.
        /// Optionally delete any entity records that were created for this sample.
        /// </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
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();

                    //<snippetCreateandublishProducts1>
                    // Create a product family
                    Product newProductFamily = new Product
                    {
                        Name             = "Example Product Family",
                        ProductNumber    = "PF001",
                        ProductStructure = new OptionSetValue(2)
                    };
                    _productFamilyId = _serviceProxy.Create(newProductFamily);
                    Console.WriteLine("\nCreated '{0}'", newProductFamily.Name);

                    // Create a product property
                    DynamicProperty newProperty = new DynamicProperty
                    {
                        Name = "Example Property",
                        RegardingObjectId = new EntityReference(Product.EntityLogicalName,
                                                                _productFamilyId),
                        IsReadOnly         = true,
                        IsRequired         = true,
                        IsHidden           = false,
                        DataType           = new OptionSetValue(3), //Single line of text
                        DefaultValueString = "Default Value"
                    };
                    _productPropertyId = _serviceProxy.Create(newProperty);
                    Console.WriteLine("\nCreated '{0}' for the product family", newProperty.Name);

                    // Create couple of product records under the product family
                    Product newProduct1 = new Product
                    {
                        Name                 = "Example Product 1",
                        ProductNumber        = "P001",
                        ProductStructure     = new OptionSetValue(1),
                        ParentProductId      = new EntityReference(Product.EntityLogicalName, _productFamilyId),
                        QuantityDecimal      = 2,
                        DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId),
                        DefaultUoMId         = new EntityReference(UoM.EntityLogicalName, _unit.Id)
                    };
                    _product1Id = _serviceProxy.Create(newProduct1);

                    Console.WriteLine("\nCreated '{0}' under the product family", newProduct1.Name);

                    Product newProduct2 = new Product
                    {
                        Name                 = "Example Product 2",
                        ProductNumber        = "P002",
                        ProductStructure     = new OptionSetValue(1),
                        ParentProductId      = new EntityReference(Product.EntityLogicalName, _productFamilyId),
                        QuantityDecimal      = 2,
                        DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId),
                        DefaultUoMId         = new EntityReference(UoM.EntityLogicalName, _unit.Id)
                    };
                    _product2Id = _serviceProxy.Create(newProduct2);

                    Console.WriteLine("Created '{0}' under the product family", newProduct2.Name);



                    // Create a price list items for the products
                    ProductPriceLevel newPriceListItem1 = new ProductPriceLevel
                    {
                        PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                        ProductId    = new EntityReference(Product.EntityLogicalName, _product1Id),
                        UoMId        = new EntityReference(UoM.EntityLogicalName, _unit.Id),
                        Amount       = new Money(20)
                    };
                    _priceListItem1Id = _serviceProxy.Create(newPriceListItem1);

                    Console.WriteLine("\nCreated price list for '{0}'", newProduct1.Name);

                    ProductPriceLevel newPriceListItem2 = new ProductPriceLevel
                    {
                        PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                        ProductId    = new EntityReference(Product.EntityLogicalName, _product2Id),
                        UoMId        = new EntityReference(UoM.EntityLogicalName, _unit.Id),
                        Amount       = new Money(20)
                    };
                    _priceListItem2Id = _serviceProxy.Create(newPriceListItem2);

                    Console.WriteLine("Created price list for '{0}'", newProduct2.Name);

                    // Set the product relationship
                    // Set Example Product 1 and Example Product 2 as substitute of each other (bi-directional)
                    ProductSubstitute newProductRelation = new ProductSubstitute
                    {
                        SalesRelationshipType = new OptionSetValue(3),
                        Direction             = new OptionSetValue(1),
                        ProductId             = new EntityReference(Product.EntityLogicalName, _product1Id),
                        SubstitutedProductId  = new EntityReference(Product.EntityLogicalName, _product2Id)
                    };
                    _productRelationId = _serviceProxy.Create(newProductRelation);

                    Console.WriteLine("\nCreated a substitute relation between the two products.");
                    //</snippetCreateandublishProducts1>

                    // Override a product property at the product level
                    // In this case we will override the property for 'Example Product 1'
                    DynamicProperty newOverrideProperty = new DynamicProperty();
                    newOverrideProperty.BaseDynamicPropertyId = new EntityReference(DynamicProperty.EntityLogicalName,
                                                                                    _productPropertyId);
                    newOverrideProperty.RegardingObjectId = new EntityReference(Product.EntityLogicalName, _product1Id);
                    _productOverridenPropertyId           = _serviceProxy.Create(newOverrideProperty);

                    // Retrieve the attributes of the cloned property you want to update
                    ColumnSet columns = new ColumnSet();
                    columns.AddColumns("name", "isreadonly", "isrequired");
                    DynamicProperty retrievedOverridenProperty = (DynamicProperty)_serviceProxy.Retrieve(
                        DynamicProperty.EntityLogicalName, _productOverridenPropertyId,
                        columns);

                    // Update the attributes
                    retrievedOverridenProperty.Name       = "Overridden Example Property";
                    retrievedOverridenProperty.IsReadOnly = true;
                    retrievedOverridenProperty.IsRequired = false;
                    _serviceProxy.Update(retrievedOverridenProperty);
                    Console.WriteLine("\nOverridden the product property for 'Example Product 1'.");

                    // Prompt the user whether to publish the product family and products
                    bool publishRecords = true;
                    Console.WriteLine("\nDo you want the product records published? (y/n)");
                    String answer = Console.ReadLine();
                    publishRecords = (answer.StartsWith("y") || answer.StartsWith("Y"));

                    if (publishRecords)
                    {
                        PublishProductHierarchyRequest publishReq = new PublishProductHierarchyRequest
                        {
                            Target = new EntityReference(Product.EntityLogicalName, _productFamilyId)
                        };
                        PublishProductHierarchyResponse published = (PublishProductHierarchyResponse)_serviceProxy.Execute(publishReq);
                        if (published.Results != null)
                        {
                            Console.WriteLine("Published the product records");
                        }

                        // Overwrite a product property
                        Console.WriteLine("\nRevising 'Example Product 1' to demonstrate product property overwrite.");

                        // Retrieve the StateCode of Product that you want to revise
                        ColumnSet cols = new ColumnSet();
                        cols.AddColumns("name", "statecode");
                        Product retrievedPublishedProduct = (Product)_serviceProxy.Retrieve(
                            Product.EntityLogicalName, _product1Id,
                            cols);

                        // Update the state of the Product to "Under Revision"
                        retrievedPublishedProduct.StateCode = ProductState.UnderRevision;
                        UpdateRequest updatePropertyState = new UpdateRequest
                        {
                            Target = retrievedPublishedProduct
                        };
                        _serviceProxy.Execute(updatePropertyState);
                        Console.WriteLine("\nChanged '{0}' to 'Under Revision' state.", retrievedPublishedProduct.Name);

                        DynamicProperty newOverwriteProperty = new DynamicProperty();
                        newOverwriteProperty.BaseDynamicPropertyId = new EntityReference(DynamicProperty.EntityLogicalName,
                                                                                         _productOverridenPropertyId);
                        newOverwriteProperty.RegardingObjectId = new EntityReference(Product.EntityLogicalName,
                                                                                     _product1Id);
                        _productOverwrittenPropertyId = _serviceProxy.Create(newOverwriteProperty);

                        // Retrieve the attributes of the cloned property you want to update
                        ColumnSet myCols = new ColumnSet();
                        myCols.AddColumns("name", "isreadonly", "isrequired");
                        DynamicProperty retrievedOverwrittenProperty = (DynamicProperty)_serviceProxy.Retrieve(
                            DynamicProperty.EntityLogicalName, _productOverwrittenPropertyId,
                            myCols);


                        // Update the attributes of the cloned property to complete the overwrite
                        retrievedOverwrittenProperty.Name       = "Overwritten Example Property";
                        retrievedOverwrittenProperty.IsReadOnly = true;
                        retrievedOverridenProperty.IsRequired   = false;
                        _serviceProxy.Update(retrievedOverwrittenProperty);
                        Console.WriteLine("\nOverwritten the product property for 'Example Product 1'.");

                        // Retrieve the StateCode of Product that you want to publish
                        ColumnSet prodCols = new ColumnSet();
                        prodCols.AddColumns("name", "statecode");
                        Product retrievedRevisedProduct = (Product)_serviceProxy.Retrieve(
                            Product.EntityLogicalName, _product1Id,
                            prodCols);

                        // Update the state of the Product to "Active"
                        retrievedRevisedProduct.StateCode = ProductState.Active;
                        UpdateRequest publishProduct1 = new UpdateRequest
                        {
                            Target = retrievedRevisedProduct
                        };
                        _serviceProxy.Execute(publishProduct1);
                        Console.WriteLine("\nPublished '{0}'.", retrievedRevisedProduct.Name);
                    }

                    DeleteRequiredRecords(promptForDelete);
                }
            }
            catch
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }