Example #1
2
        /// <summary>
        /// Pre-Validation method will default the values of contact preference fields
        /// </summary>
        private static void PreValidateContactCreate(IPluginExecutionContext context, IOrganizationService service)
        {
            Entity contactEntity = (Entity)context.InputParameters["Target"];
            OptionSetValue doNotAllow = new OptionSetValue(1);

            contactEntity.SetAttribute("donotemail", doNotAllow);
            contactEntity.SetAttribute("donotpostalmail", doNotAllow);
            contactEntity.SetAttribute("donotbulkemail", doNotAllow);
            contactEntity.SetAttribute("donotfax", doNotAllow);

            // Get a count of child phone call entities associated with this Contact
            QueryExpression query = new QueryExpression();
            query.EntityName = "phonecall";
            query.ColumnSet = new ColumnSet(allColumns: true);
            query.Criteria = new FilterExpression();
            query.Criteria.AddCondition(new ConditionExpression("regardingobjectid", ConditionOperator.Equal, context.PrimaryEntityId));

            RetrieveMultipleRequest request = new RetrieveMultipleRequest();
            request.Query = query;
            IEnumerable<Entity> results = ((RetrieveMultipleResponse)service.Execute(request)).EntityCollection.Entities;
            if (results.Any())
            {
                // Do not default contact preference for phone if there are already some associated phone calls
                // Why? Because! Testing!
                contactEntity.SetAttribute("donotphone", doNotAllow);
            }
        }
        private EntityCollection GenerateRandomAccountCollection()
        {
            var collection = new List<Entity>();
            for (var i = 0; i < 10; i++)
            {
                var rgn = new Random((int)DateTime.Now.Ticks);
                var entity = new Entity("account");
                entity["accountid"] = entity.Id = Guid.NewGuid();
                entity["address1_addressid"] = Guid.NewGuid();
                entity["modifiedon"] = DateTime.Now;
                entity["lastusedincampaign"] = DateTime.Now;
                entity["donotfax"] = rgn.NextBoolean();
                entity["new_verybignumber"] = rgn.NextInt64();
                entity["exchangerate"] = rgn.NextDecimal();
                entity["address1_latitude"] = rgn.NextDouble();
                entity["numberofemployees"] = rgn.NextInt32();
                entity["primarycontactid"] = new EntityReference("contact", Guid.NewGuid());
                entity["revenue"] = new Money(rgn.NextDecimal());
                entity["ownerid"] = new EntityReference("systemuser", Guid.NewGuid());
                entity["industrycode"] = new OptionSetValue(rgn.NextInt32());
                entity["name"] = rgn.NextString(15);
                entity["description"] = rgn.NextString(300);
                entity["statecode"] = new OptionSetValue(rgn.NextInt32());
                entity["statuscode"] = new OptionSetValue(rgn.NextInt32());
                collection.Add(entity);
            }

            return new EntityCollection(collection);
        }
Example #3
1
        public void Update(IOrganizationService service, List<Entity> profiles)
        {
            foreach (var profile in profiles)
            {
                var field = Fields.FirstOrDefault(
                        f => f.GetAttributeValue<EntityReference>("fieldsecurityprofileid").Id == profile.Id);

                if (field == null)
                {
                    field = new Entity("fieldpermission");
                    field["fieldsecurityprofileid"] = profile.ToEntityReference();
                    field["canread"] = new OptionSetValue(0);
                    field["cancreate"] = new OptionSetValue(0);
                    field["canupdate"] = new OptionSetValue(0);
                    field["entityname"] = Entity;
                    field["attributelogicalname"] = Attribute;
                }

                if (CanRead.HasValue)
                {
                    field["canread"] = new OptionSetValue(CanRead.Value ? 4 : 0);
                }

                if (CanCreate.HasValue)
                {
                    field["cancreate"] = new OptionSetValue(CanCreate.Value ? 4 : 0);
                }

                if (CanUpdate.HasValue)
                {
                    field["canupdate"] = new OptionSetValue(CanUpdate.Value ? 4 : 0);
                }

                if (field.Id == Guid.Empty)
                {
                    field.Id = service.Create(field);
                    Fields.Add(field);
                }
                else
                {
                    service.Update(field);
                }
            }
        }
        public void UpdateSettings(Guid userId, UserSettings settings)
        {
            var currentUserId = detail.ServiceClient.OrganizationServiceProxy.CallerId;
            detail.ServiceClient.OrganizationServiceProxy.CallerId = userId;

            var records = detail.ServiceClient.OrganizationServiceProxy.RetrieveMultiple(new QueryByAttribute("usersettings")
            {
                Attributes = { "systemuserid" },
                Values = { userId },
            });

            var record = records.Entities.First();

            if (settings.AdvancedFindStartupMode >= 1)
                record["advancedfindstartupmode"] = settings.AdvancedFindStartupMode;
            if (settings.AutoCreateContactOnPromote >= 0)
                record["autocreatecontactonpromote"] = settings.AutoCreateContactOnPromote;
            if (settings.DefaultCalendarView >= 0)
                record["defaultcalendarview"] = settings.DefaultCalendarView;
            if (settings.HomePageArea.Length > 0 && settings.HomePageArea != "No change")
                record["homepagearea"] = settings.HomePageArea;
            if (settings.HomePageSubArea.Length > 0 && settings.HomePageSubArea != "No change")
                record["homepagesubarea"] = settings.HomePageSubArea;
            if (settings.IncomingEmailFilteringMethod >= 0)
                record["incomingemailfilteringmethod"] = new OptionSetValue(settings.IncomingEmailFilteringMethod);
            if (settings.PagingLimit.HasValue)
                record["paginglimit"] = settings.PagingLimit.Value;
            if (settings.TimeZoneCode >= 0)
                record["timezonecode"] = settings.TimeZoneCode;
            if (settings.WorkdayStartTime.Length > 0 && settings.WorkdayStartTime != "No change")
                record["workdaystarttime"] = settings.WorkdayStartTime;
            if (settings.WorkdayStopTime.Length > 0 && settings.WorkdayStopTime != "No change")
                record["workdaystoptime"] = settings.WorkdayStopTime;
            if (settings.ReportScriptErrors >= 1)
                record["reportscripterrors"] = new OptionSetValue(settings.ReportScriptErrors);
            if (settings.IsSendAsAllowed.HasValue)
                record["issendasallowed"] = settings.IsSendAsAllowed.Value;
            if (settings.UiLanguage.HasValue)
                record["uilanguageid"] = settings.UiLanguage.Value;
            if (settings.HelpLanguage.HasValue)
                record["helplanguageid"] = settings.HelpLanguage.Value;
            if (settings.Currency != null)
                record["transactioncurrencyid"] = settings.Currency;
            if (settings.StartupPaneEnabled.HasValue)
                record["getstartedpanecontentenabled"] = settings.StartupPaneEnabled.Value;
            if (settings.UseCrmFormForAppointment.HasValue)
                record["usecrmformforappointment"] = settings.UseCrmFormForAppointment.Value;
            if (settings.UseCrmFormForContact.HasValue)
                record["usecrmformforcontact"] = settings.UseCrmFormForContact.Value;
            if (settings.UseCrmFormForEmail.HasValue)
                record["usecrmformforemail"] = settings.UseCrmFormForEmail.Value;
            if (settings.UseCrmFormForTask.HasValue)
                record["usecrmformfortask"] = settings.UseCrmFormForTask.Value;

            service.Update(record);

            detail.ServiceClient.OrganizationServiceProxy.CallerId = currentUserId;
        }
        public string GetOptionSetText(string optionSetName, OptionSetValue value, string etn, int def = 0)
        {
            if (string.IsNullOrEmpty(optionSetName))
                throw new ArgumentNullException(nameof(optionSetName));

            if (value == null)
                throw new ArgumentNullException(nameof(value));

            if (value.Value == def)
            {
                return string.Empty;
            }
            var key = etn + optionSetName;
            if (!ValuesDictionary.ContainsKey(key) || !ValuesDictionary[key].ContainsKey(value.Value))
            {
                ValuesDictionary[key] = RetrieveOptionSet(etn, optionSetName);
            }

            return !ValuesDictionary[key].ContainsKey(value.Value) ? string.Empty : ValuesDictionary[key][value.Value];
        }
        public void Should_not_override_a_statecode_already_initialized()
        {
            var context = new XrmFakedContext();
            context.ProxyTypesAssembly = Assembly.GetExecutingAssembly();
            var service = context.GetFakedOrganizationService();

            var c = new Contact()
            {
                Id = Guid.NewGuid(),
            };

            c["statecode"] = new OptionSetValue(69); //As the StateCode is read only in the early bound entity, this is the only way of updating it
             
            context.Initialize(new[] { c });

            //Retrieve record after update
            var contact = (from con in context.CreateQuery<Contact>()
                           where con.Id == c.Id
                           select con).FirstOrDefault();

            Assert.Equal((int)contact.StateCode.Value, 69); //Set
        }
        public void DefaultContactPreferencesSet()
        {
            // Arrange
            ContactPlugin plugin = new ContactPlugin();
            Entity contact = new Entity("contact");
            ParameterCollection parameterCollection = new ParameterCollection();
            parameterCollection.Add("Target", contact);
            _pluginExecutionContext.InputParametersGet = () => { return parameterCollection; };
            _pluginExecutionContext.MessageNameGet = () => { return "Create"; }; // Fake a 'Create' message
            _pluginExecutionContext.StageGet = () => { return 10; }; // Fake the 'Pre-Validation' execution stage

            // Act
            plugin.Execute(_serviceProvider);

            // Assert that default contact preferences have been set
            OptionSetValue doNotAllow = new OptionSetValue(1);
            contact.Attributes["donotemail"].Should().Equal(doNotAllow);
            contact.Attributes["donotphone"].Should().Equal(doNotAllow);
            contact.Attributes["donotpostalmail"].Should().Equal(doNotAllow);
            contact.Attributes["donotbulkemail"].Should().Equal(doNotAllow);
            contact.Attributes["donotfax"].Should().Equal(doNotAllow);
        }
Example #8
0
        private EntityCollection GetContactos(PluginContext ctx, Entity cliente, int customTypeInt)
        {
            ctx.TracingService.Trace("[BEGIN] GetContactos");
            EntityCollection result = null;

            OptionSetValue customTypeOpSet = GetCustomTypeOpSet(ctx, customTypeInt);

            QueryExpression query = new QueryExpression("contact");

            query.ColumnSet = new ColumnSet("info_qualification");
            query.Criteria.AddCondition("parentcustomerid", ConditionOperator.Equal, cliente.ToEntityReference().Id);
            query.Criteria.AddCondition("info_customtype", ConditionOperator.Equal, customTypeOpSet.Value);
            EntityCollection contactos = ctx.Service.RetrieveMultiple(query);

            if (contactos.Entities.Count == 0)
            {
                return(result);
            }

            result = contactos;
            ctx.TracingService.Trace("[END] GetContactos");
            return(result);
        }
Example #9
0
        public string Create(string Company, int sector, string Description, string phone, int who = 1)
        {
            // select new_nationalityid,new_districtid,new_profrequiredid,new_cityid from lead
            //


            Entity Lead = new Entity("lead");

            Lead["new_sector"]  = new OptionSetValue(1);
            Lead["companyname"] = Company;
            Lead["firstname"]   = " طلب قطاع اعمال لشركة" + Company;

            Lead["new_company_busienss"] = OptionsController.GetName("account", "industrycode", 1025, sector.ToString());
            // Lead["new_companysector"] = new OptionSetValue(sector);
            Lead["mobilephone"] = phone;
            Lead["description"] = Description;


            Guid id = GlobalCode.Service.Create(Lead);


            return(id.ToString());
        }
Example #10
0
        private static void SetState(CrmServiceClient service, EntityReference caseReference)
        {
            // Updating the incident state
            var state = new Entity("incident");

            state["incidentid"] = _caseIncidentId;
            state["statecode"]  = new OptionSetValue((int)IncidentState.Active);
            state["statuscode"] = new OptionSetValue((int)incident_statuscode.WaitingforDetails);
            service.Update(state);

            // Check if the state was successfully set
            Incident incident = service.Retrieve(Incident.EntityLogicalName,
                                                 _caseIncidentId, new ColumnSet(allColumns: true)).ToEntity <Incident>();

            if (incident.StatusCode.Value == (int)incident_statuscode.WaitingforDetails)
            {
                Console.WriteLine("Record state set successfully.");
            }
            else
            {
                Console.WriteLine("The request to set the record state failed.");
            }
        }
Example #11
0
        public void CreatePickupReport()
        {
            Entity report = new Entity("drn_cartransferreport");

            report["drn_name"] = "Pickup_" + DateTime.Now.ToString("dd/MM - HH:mm:ss");

            EntityReference carRef = new EntityReference("drn_car", ((EntityReference)entity["drn_car"]).Id);

            report["drn_car"]     = carRef;
            report["drn_type"]    = new OptionSetValue(172620000);
            report["drn_date"]    = entity["drn_reservedpickup"];
            report["drn_damages"] = false;

            if ((new Random().NextDouble()) < 0.05)
            {
                report["drn_damages"]           = true;
                report["drn_damagedescription"] = "Damage";
            }
            Guid            pickupReportGuid = svc.Create(report);
            EntityReference rentingRef       = new EntityReference("drn_cartransferreport", pickupReportGuid);

            entity["drn_pickupreport"] = rentingRef;
        }
Example #12
0
        /// <summary>
        /// Creates a new Finance Activity object in CRM for an account
        /// </summary>
        /// <param name="accountId">Guid Id for Account in CRM</param>
        /// <param name="activity">AtcActivity object to save in CRM</param>
        public void CreateNewActivity(string accountId, AtcActivity activity)
        {
            _log.Info($"Creating new activity for account: {accountId} from: {activity.ActivityDate}");
            var newActivity = new Entity("new_financeactivity");

            newActivity["subject"]                 = activity.Subject;
            newActivity["new_actiontype"]          = activity.Type == "Email" ? new OptionSetValue(100000000) : new OptionSetValue(100000001);
            newActivity["new_contactdate"]         = activity.ActivityDate;
            newActivity["new_contactperson"]       = activity.Contact;
            newActivity["new_financeactivitytype"] = new OptionSetValue(100000000);
            newActivity["new_note"]                = activity.Note;
            newActivity["new_atcactivityid"]       = activity.ActivityId;
            newActivity["regardingobjectid"]       = new EntityReference("account", new Guid(accountId));

            Guid activityId = _crmServiceClient.Create(newActivity);

            SetStateRequest setStateRequest = new SetStateRequest();

            setStateRequest.EntityMoniker = new EntityReference("new_financeactivity", activityId);
            setStateRequest.State         = new OptionSetValue(1);
            setStateRequest.Status        = new OptionSetValue(2);
            SetStateResponse setStateResponse = (SetStateResponse)_crmServiceClient.Execute(setStateRequest);
        }
        private static List <UnitInfo> Deduct(ref List <UnitInfo> latestCount, EntityCollection currentRequests, Entity wonRequest)
        {
            var             result      = latestCount;
            EntityReference wonCustomer = new EntityReference();
            EntityReference wonUnit     = new EntityReference();
            OptionSetValue  priority    = new OptionSetValue();

            if (wonRequest.Attributes.Contains("ldv_customerid") && wonRequest.Attributes.Contains("ldv_unitid"))
            {
                wonCustomer = (EntityReference)wonRequest.Attributes["ldv_customerid"];
                wonUnit     = (EntityReference)wonRequest.Attributes["ldv_unitid"];
                result.Where(x => x.Unit.Id == wonUnit.Id).ToList().ForEach(x => { x.Count = 0; x.HighestPriority = 0; });

                var         otherOptions        = currentRequests.Entities.ToList().Where(req => ((EntityReference)req.Attributes["ldv_customerid"]).Id == wonCustomer.Id && req.Id != wonRequest.Id).ToList();
                List <Guid> otherOptionsUnitIds = otherOptions.Select(i => ((EntityReference)i.Attributes["ldv_unitid"]).Id).ToList();
                for (int i = 0; i < otherOptionsUnitIds.Count; i++)
                {
                    result.Where(x => x.Unit.Id == otherOptionsUnitIds[i]).ToList().ForEach(x => x.Count--);
                    currentRequests.Entities.Where(x => ((EntityReference)x["ldv_unitid"]).Id == otherOptionsUnitIds[i] && ((OptionSetValue)x["ldv_statuscode"]).Value == 1).OrderBy(x => ((OptionSetValue)x["ldv_prioritycode"]).Value).ToList();
                }
            }
            return(result);
        }
        public void OptionSetValueCanBeSerializedAndDeserialized()
        {
            object         optionSetValue = new OptionSetValue(1);
            JsonSerializer serializer     = new JsonSerializer();

            serializer.Converters.Add(new OptionSetValueConverter());
            MemoryStream memoryStream = new MemoryStream(new byte[9000], true);

            using (StreamWriter writer = new StreamWriter(memoryStream))
            {
                serializer.Serialize(new JsonTextWriter(writer), optionSetValue);
            }

            object deserializedOptionSetValue;

            memoryStream = new MemoryStream(memoryStream.ToArray());
            using (StreamReader reader = new StreamReader(memoryStream))
            {
                deserializedOptionSetValue = serializer.Deserialize(new JsonTextReader(reader), typeof(OptionSetValue));
            }

            Assert.Equal(optionSetValue, deserializedOptionSetValue);
        }
        public void Should_not_override_a_statecode_already_initialized()
        {
            var context = new XrmFakedContext();

            context.ProxyTypesAssembly = Assembly.GetExecutingAssembly();
            var service = context.GetFakedOrganizationService();

            var c = new Contact()
            {
                Id = Guid.NewGuid(),
            };

            c["statecode"] = new OptionSetValue(69); //As the StateCode is read only in the early bound entity, this is the only way of updating it

            context.Initialize(new[] { c });

            //Retrieve record after update
            var contact = (from con in context.CreateQuery <Contact>()
                           where con.Id == c.Id
                           select con).FirstOrDefault();

            Assert.Equal((int)contact.StateCode.Value, 69); //Set
        }
Example #16
0
        public static MsCrmResult CreateScore(Score score, IOrganizationService service)
        {
            MsCrmResult returnValue = new MsCrmResult();

            try
            {
                Entity ent = new Entity("new_score");
                ent["new_name"] = score.ScoreType.ToString() + "-" + score.User.Name + "-" + DateTime.Now.ToString("dd.MM.yyyy HH:mm");
                ent["new_portalid"] = score.Portal;
                ent["new_userid"] = score.User;
                ent["new_point"] = score.Point;
                ent["new_scoretype"] = new OptionSetValue((int)score.ScoreType);

                returnValue.CrmId = service.Create(ent);
                returnValue.Success = true;
            }
            catch (Exception ex)
            {
                returnValue.Result = ex.Message;
            }

            return returnValue;
        }
Example #17
0
        private object ProcessValue(object value, IPlannedValue plannedValueX = null)
        {
            if (plannedValueX != null)
            {
                valueMap[plannedValueX.Id] = value is AliasedValue aliased ? aliased.Value : value;
            }

            return(value switch {
                OrganizationRequest e => ProcessMappedValue(e.Parameters, plannedValueX as PlannedMapBase, e),
                OrganizationResponse e => ProcessMappedValue(e.Results, plannedValueX as PlannedMapBase, e),
                Entity e => ProcessMappedValue(e.Attributes, plannedValueX as PlannedMapBase, e),
                EntityReference e => ProcessProperties(e, plannedValueX as PlannedMapBase),
                EntityCollection e => ProcessCollection(e.Entities, plannedValueX as PlannedMapBase, e),
                OptionSetValue e => ProcessProperties(e, plannedValueX as PlannedMapBase),
                DataCollection <string, object> e => ProcessMappedValue(e, plannedValueX as PlannedMapBase, e),
                DataCollection <Entity> e => ProcessCollection(e, plannedValueX as PlannedMapBase, e),
                DataCollection <EntityReference> e => ProcessCollection(e, plannedValueX as PlannedMapBase, e),
                DataCollection <OptionSetValue> e => ProcessCollection(e, plannedValueX as PlannedMapBase, e),
                DataCollection <object> e => ProcessCollection(e, plannedValueX as PlannedMapBase, e),
                IPlannedValue e => valueMap.TryGetValue(e.Id, out var mappedValue) ? mappedValue : e,
                _ => value != null && Guid.TryParse(value.ToString(), out var id)
                                        ? (valueMap.TryGetValue(id, out var mappedId) ? mappedId : value) : value
            });
Example #18
0
        public static MsCrmResult CreateScore(Score score, IOrganizationService service)
        {
            MsCrmResult returnValue = new MsCrmResult();

            try
            {
                Entity ent = new Entity("new_score");
                ent["new_name"]      = score.ScoreType.ToString() + "-" + score.User.Name + "-" + DateTime.Now.ToString("dd.MM.yyyy HH:mm");
                ent["new_portalid"]  = score.Portal;
                ent["new_userid"]    = score.User;
                ent["new_point"]     = score.Point;
                ent["new_scoretype"] = new OptionSetValue((int)score.ScoreType);

                returnValue.CrmId   = service.Create(ent);
                returnValue.Success = true;
            }
            catch (Exception ex)
            {
                returnValue.Result = ex.Message;
            }

            return(returnValue);
        }
Example #19
0
        /// <summary>
        /// Find a matching Membership in CRM based on the contact id, membership number, and associated "unpaid" invoice
        /// NOTE: UNUSED METHOD
        /// </summary>
        //private Membership MatchMembership(Membership membership, MatchController mc)
        //{
        //    Guid contactId = membership.Member.ContactId;
        //    string membershipNumber = membership.MembershipNumber;

        //    List<Membership> memberships = this.GetMemberships(contactId, membershipNumber);
        //    Membership match = mc.MatchToExistingMembership(memberships);

        //    membership.MatchCode = match.MatchCode; // set the match code

        //    // create a membership
        //    if (membership.MembershipId == default(Guid))
        //    {
        //        membership.MembershipId = this.CreateMembership(membership);
        //    }

        //    return membership;
        //}

        /// <summary>
        /// Creates a new Membership in CRM for the associated Contact. Note - an Invoice will automatically be created from a plugin
        /// </summary>
        private Guid CreateMembership(Membership membership, Guid unitId)
        {
            this._tracer.Trace("Method: MembershipController.CreateMembership");
            this._tracer.Trace("Parameters: unitId={0}", unitId);

            Entity mShip = new Entity("mag_membership");

            mShip["mag_idnumber"]             = membership.MembershipNumber;
            mShip["mag_contactid"]            = MappingController.MapToEntityReference("contact", membership.Member.ContactId);
            mShip["mag_membershiptypeid"]     = MappingController.MapToEntityReference("product", membership.MembershipType.MembershipTypeId);
            mShip["mag_startdate"]            = DateTime.Now;
            mShip["mag_regionid"]             = MappingController.MapToEntityReference("businessunit", membership.RegionCodeId);
            mShip["mag_unitid"]               = MappingController.MapToEntityReference("mag_coastguardunit", unitId);
            mShip["mag_transactionid"]        = membership.DpsTransactionReference;
            mShip["mag_membershipsourcecode"] = new OptionSetValue((int)MembershipSourceCode.Online); // online
            mShip["mag_paymentmethodcode"]    = new OptionSetValue((int)PaymentMethodCode.CreditCard);
            mShip["mag_creditcardexpirydate"] = base.GetCCExpiryDate(membership.CCExpiry);
            mShip["mag_membershipsupportsid"] = MappingController.MapToEntityReference("mag_tag", membership.UnitCodeId);

            Guid membershipId = this._sdk.Create(mShip);

            // Plugin triggers to generate and link the invoice with the new membership

            // Get the new membership with the invoice ID and pay the invoice
            Entity newMembership = this._sdk.Retrieve("mag_membership", membershipId, new ColumnSet("mag_invoiceid"));
            Guid   invoiceId     = newMembership.Get <Guid>("mag_invoiceid");

            if (invoiceId != null && invoiceId != Guid.Empty)
            {
                this.UpdateInvoicePaid(invoiceId);

                // Create a payment item for the invoice
                this.ProcessPaymentItem(invoiceId, membership.Member.ContactId, membership.MembershipType.Price);
            }

            return(membershipId);
        }
Example #20
0
        /*
         *  Lead create Process allow end user to choose which name they want to use
         *  The purpose of we want the name as a parameter is that it can be easily track and create.
         */
        private static Guid CreateLeadWithName(OrganizationServiceProxy service, String name)
        {
            var leadSource = GetLeadSourceName(service, leadSourceName);
            var newLead    = new Entity("lead");

            var user = GetUser(service);

            newLead["companyname"]      = name;
            newLead["log_leadsourceid"] = leadSource.ToEntityReference();
            //newLead["ownerid"] = user.ToEntityReference();
            newLead["log_direction"]       = new OptionSetValue(182400001); //moved out
            newLead["log_contracttermsid"] = GetContractTerms(service).ToEntityReference();
            newLead["telephone2"]          = "45512131";
            newLead["log_dateofbirth"]     = DateTime.Now.AddYears(-19);
            //Date cannot be in the future
            newLead["log_solddate"]   = DateTime.Now;
            newLead["log_movingdate"] = DateTime.Now;

            newLead["log_salespersonid"] = GetSalesPerson(service).ToEntityReference();
            //street 1
            //newLead["address2_line1"] = "address2 vitaminveien 1, oslo";
            //     newLead["log_address2_postalcode"] = GetPostCode(service).ToEntityReference();
            //newLead["log_postalcode"] = GetPostCode(service).ToEntityReference();
            newLead["address1_line1"] = "address1 vitaminveien 1, oslo";
            newLead["log_canoverwritecreditcheck"] = true;

            //GetTakdOverCASE
            //     newLead["log_takeovercase"] = GetTakdOverCASE(service).ToEntityReference();
            //home
            newLead["log_typeoflead"]           = new OptionSetValue(182400000);
            newLead["log_movefrominstallation"] = GetInstallation(service).ToEntityReference();
            newLead["log_movetoinstallation"]   = GetInstallation(service).ToEntityReference();

            //ireland eller spain spesifikk
            // newLead["sa_salestype"] = GetSaleTYPE(service).ToEntityReference();
            return(service.Create(newLead));
        }
Example #21
0
        public Boolean generateRiskAssessment(Entity fundingCase, OptionSetValue riskAssessmentType)
        {
            //get current entity data

            try
            {
                var fc             = _service.Retrieve("gcbase_fundingcase", fundingCase.Id, new ColumnSet("gcbase_program"));
                var fundingCaseRef = new EntityReference("gcbase_fundingcase", fundingCase.Id);

                var             fundCentreRef = fc.GetAttributeValue <EntityReference>("gcbase_program");
                QueryExpression qe            = new QueryExpression("gcbase_risktemplatefundcentre");
                qe.Criteria.AddCondition("gcbase_fundcentre", ConditionOperator.Equal, fundCentreRef.Id);
                qe.ColumnSet.AddColumns("gcbase_risktemplate", "gcbase_name");
                //var optHelper = new helpers.OptionSetHelper();
                //int indexOfStatus = optHelper.getIndexOfLabel("gcbase_risktemplate", "statuscode", "Completed", _service);
                //qe.Criteria.AddCondition("statuscode", ConditionOperator.Equal, indexOfStatus);

                var rtfc            = _service.RetrieveMultiple(qe).Entities.First();
                var riskTemplateRef = rtfc.GetAttributeValue <EntityReference>("gcbase_risktemplate");

                Entity newFundingCaseRiskAssessment = new Entity("gcbase_fundingcaseriskassessment");
                newFundingCaseRiskAssessment["gcbase_fundcentre"]   = fundCentreRef;
                newFundingCaseRiskAssessment["gcbase_risktemplate"] = riskTemplateRef;
                newFundingCaseRiskAssessment["gcbase_fundingcase"]  = fundingCaseRef;
                newFundingCaseRiskAssessment["gcbase_fundingcaseriskassessmenttype"] = riskAssessmentType;
                //newFundingCaseRiskAssessment["gcbase_name"] = rtfc.GetAttributeValue<EntityReference>("gcbase_risktemplate").Name;
                var newFCRA = _service.Create(newFundingCaseRiskAssessment);

                //the method below already happens when the plugin is called
                //generateRiskFactorsForTemplate(riskTemplateRef, newFCRA);
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Example #22
0
        internal string UpdateCrmTask(TaskEntity newTask)
        {
            Trace.TraceInformation("UpdateCrmTask");

            try
            {
                Entity updCrmTask = new Entity(newTask.CrmEntityLogicalName);
                updCrmTask.Id = newTask.CrmId;
                if (newTask.TaskStatus != null)
                {
                    updCrmTask["statecode"] = new OptionSetValue((int)newTask.TaskStatus);
                }
                if (!string.IsNullOrEmpty(newTask.Subject))
                {
                    updCrmTask["subject"] = newTask.Subject;
                }
                if (!string.IsNullOrEmpty(newTask.Body))
                {
                    updCrmTask["description"] = GetStringWithoutTags(newTask.Body);
                }
                if (newTask.DuoDate != null)
                {
                    updCrmTask["scheduledend"] = newTask.DuoDate;
                }
                if (!string.IsNullOrEmpty(newTask.OutlookId))
                {
                    updCrmTask["ylv_outlookid"] = newTask.OutlookId;
                }

                organizationService.Update(updCrmTask);
                return("Success update");
            }
            catch (Exception ex)
            {
                return("Update fail\n" + ex.Message);
            }
        }
Example #23
0
        public Boolean generateRiskAssessment(Entity fundingCase, OptionSetValue riskAssessmentType)
        {
            //get current entity data

            try
            {
                var fc = _service.Retrieve("gcbase_fundingcase", fundingCase.Id, new ColumnSet("gcbase_program"));
                var fundingCaseRef = new EntityReference("gcbase_fundingcase", fundingCase.Id);

                var fundCentreRef = fc.GetAttributeValue<EntityReference>("gcbase_program");
                QueryExpression qe = new QueryExpression("gcbase_risktemplatefundcentre");
                qe.Criteria.AddCondition("gcbase_fundcentre", ConditionOperator.Equal, fundCentreRef.Id);
                qe.ColumnSet.AddColumns("gcbase_risktemplate", "gcbase_name");
                //var optHelper = new helpers.OptionSetHelper();
                //int indexOfStatus = optHelper.getIndexOfLabel("gcbase_risktemplate", "statuscode", "Completed", _service);
                //qe.Criteria.AddCondition("statuscode", ConditionOperator.Equal, indexOfStatus);

                var rtfc = _service.RetrieveMultiple(qe).Entities.First();
                var riskTemplateRef = rtfc.GetAttributeValue<EntityReference>("gcbase_risktemplate");

                Entity newFundingCaseRiskAssessment = new Entity("gcbase_fundingcaseriskassessment");
                newFundingCaseRiskAssessment["gcbase_fundcentre"] = fundCentreRef;
                newFundingCaseRiskAssessment["gcbase_risktemplate"] = riskTemplateRef;
                newFundingCaseRiskAssessment["gcbase_fundingcase"] = fundingCaseRef;
                newFundingCaseRiskAssessment["gcbase_fundingcaseriskassessmenttype"] = riskAssessmentType;
                //newFundingCaseRiskAssessment["gcbase_name"] = rtfc.GetAttributeValue<EntityReference>("gcbase_risktemplate").Name;
                var newFCRA = _service.Create(newFundingCaseRiskAssessment);

                //the method below already happens when the plugin is called
                //generateRiskFactorsForTemplate(riskTemplateRef, newFCRA);
                return true;
            }
            catch
            {
                return false;
            }
        }
        public void PickupReturnLocationsAssign()
        {
            var pickupRequest = new RetrieveAttributeRequest
            {
                EntityLogicalName     = "drn_rent",
                LogicalName           = "drn_pickuplocation",
                RetrieveAsIfPublished = true
            };

            var pickupResponse = (RetrieveAttributeResponse)svc.Execute(pickupRequest);
            var pickupMetadata = (EnumAttributeMetadata)pickupResponse.AttributeMetadata;

            var optionList = (from o in pickupMetadata.OptionSet.Options
                              select new { Value = o.Value })
                             .ToList();
            var pickupRandomOptionsetValue = (optionList.ElementAt(new Random().Next(0, optionList.Count))).Value;

            entity["drn_pickuplocation"] = new OptionSetValue(pickupRandomOptionsetValue.Value);


            var handoverRequest = new RetrieveAttributeRequest
            {
                EntityLogicalName     = "drn_rent",
                LogicalName           = "drn_pickuplocation",
                RetrieveAsIfPublished = true
            };

            var handoverResponse = (RetrieveAttributeResponse)svc.Execute(handoverRequest);
            var handoverMetadata = (EnumAttributeMetadata)handoverResponse.AttributeMetadata;

            var handoverOptionList = (from o in handoverMetadata.OptionSet.Options
                                      select new { Value = o.Value })
                                     .ToList();
            var handoverRandomOptionsetValue = (handoverOptionList.ElementAt(new Random().Next(0, optionList.Count))).Value;

            entity["drn_pickuplocation"] = new OptionSetValue(handoverRandomOptionsetValue.Value);
        }
Example #25
0
        public UpdateTradeRegistrationResponse UpdateTradeRegistration(String accountId)
        {
            log.Info("CMS-->Approved:" + accountId);
            UpdateTradeRegistrationResponse response = new UpdateTradeRegistrationResponse();
            CrmUtil cu = new CrmUtil();
            OrganizationServiceProxy organizationProxy = cu.getCrmService();

            try
            {
                //Update Account TradeRegistration
                //Entity account = new Entity("account");
                //ColumnSet attributes = new ColumnSet(new string[] { "new_check" });

                //account = organizationProxy.Retrieve(account.LogicalName, new Guid(accountId), attributes);
                //log.Info("Retrieved new_check: " + account["new_check"]);

                Entity account = RetriveAccountByEmail(organizationProxy, accountId);

                OptionSetValue register = new OptionSetValue(1);

                //account.Attributes.Add("new_check",  register);
                account["new_check"] = true;


                organizationProxy.Update(account);



                response.ErrCode = "0";
                return(response);
            }
            catch (Exception ex)
            {
                log.Info(ex.Message + "--" + ex.ToString());
            }
            return(null);
        }
        private async void bCreateClick(object sender, EventArgs e)
        {
            var name = tbName.Text;
            if(String.IsNullOrEmpty(name))
            {
                MessageBox.Show("Name can not be empty", "Error",MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var prefix = tbPrefix.Text;
            if (String.IsNullOrEmpty(prefix))
            {
                MessageBox.Show("Prefix can not be empty", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (cbType.SelectedIndex < 0)
            {
                MessageBox.Show("Please select web resource type", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var webresourceName = prefix + "_" + name;

            var webResource = new Entity();
            webResource["name"] = webresourceName;
            webResource["displayname"] = tbDisplayName.Text;
            webResource["description"] = tbDescription.Text;
            webResource["content"] = FileHelper.GetEncodedFileContent(ProjectItemPath);
            webResource["webresourcetype"] = new OptionSetValue(cbType.SelectedIndex + 1);
            webResource.LogicalName = "webresource";
            bCreate.Enabled = false;
            Cursor.Current = Cursors.WaitCursor;
            await OnCreate(webResource);
            Cursor.Current = Cursors.Default;
            bCreate.Enabled = true;
        }
Example #27
0
        public void CreateInterviewer(ITracingService tracer, IOrganizationService service, string name, int criteriaType, Guid systemuserID, Guid candidateID)
        {
            try
            {
                Entity newInterviewer = new Entity(dxc_interviewer);
                newInterviewer[dxc_name]            = name;
                newInterviewer[dxc_interviewername] = new EntityReference(systemuser, systemuserID);
                newInterviewer[dxc_candidate]       = new EntityReference(contact, candidateID);
                // 1 = initial interview
                newInterviewer[dxc_type] = new OptionSetValue(1);

                service.Create(newInterviewer);
                tracer.Trace(help.SuccessfulTraceMsg("CreateInterviewer, " + name));
            }
            catch (Exception e)
            {
                tracer.Trace(help.UnsuccessfulTraceMsg("CreateInterviewer, " + name));
                throw new InvalidPluginExecutionException(e.Message);
            }
            finally
            {
                tracer.Trace(help.SuccessfulTraceMsg("CreateInterviewer, " + name));
            }
        }
Example #28
0
        public void Constructor_WithEntityThatHasAnInvalidFieldAttributeValue_NullifiesValue()
        {
            var entity = new Entity("mock")
            {
                Id = Guid.NewGuid()
            };

            entity["dfe_field2"] = new OptionSetValue {
                Value = 123
            };
            entity["dfe_field3"] = "an-invalid-value";

            var mockValidator    = new Mock <IValidator>();
            var validationResult = new ValidationResult();

            _mockValidatorFactory.Setup(m => m.GetValidator(It.IsAny <Type>())).Returns(mockValidator.Object);
            mockValidator.Setup(m => m.Validate(It.IsAny <BaseModel>())).Returns(validationResult);
            validationResult.Errors.Add(new ValidationFailure("Field3", "this value is not valid!"));

            var mock = new MockModel(entity, _crm, _mockValidatorFactory.Object);

            mock.Field2.Should().Be(123);
            mock.Field3.Should().BeNull();
        }
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Create an appointment.
        /// </summary>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetMarketingAutomation1>
                // 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();

                    var extracurricularparticipant = new Entity("mshied_extracurricularparticipant");

                    extracurricularparticipant["mshied_extracurricularactivityid"] = new EntityReference("mshied_extracurricularactivities", new Guid("3584427f-f2cb-e811-a99b-000d3a161089"));
                    extracurricularparticipant["mshied_source"]    = new OptionSetValue(494280001);                 // Self-Reported
                    extracurricularparticipant["mshied_state"]     = new OptionSetValue(494280000);                 // Active
                    extracurricularparticipant["mshied_contactid"] = new EntityReference("contact", new Guid("8644c9e3-6ac6-e811-a984-000d3a1618d5"));
                    extracurricularparticipant["mshied_name"]      = "Adam Becker - Athletics";

                    var id = _serviceProxy.Create(extracurricularparticipant);

                    // Verify that the record has been created.
                    if (id != Guid.Empty)
                    {
                        Console.WriteLine($"Successfully created {id}.");
                    }
                }
            }
            // 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>
        /// Vote for the knowledge article this adapter applies to.
        /// </summary>
        /// <param name="rating">Rating value.</param>
        /// <param name="maxRating">Maximum rating value.</param>
        /// <param name="minRating">Minimum rating value.</param>
        private void CreateRating(int rating, int maxRating, int minRating, string visitorID = null)
        {
            var article         = Select();
            var author          = Dependencies.GetPortalUser();
            var context         = Dependencies.GetServiceContextForWrite();
            var articleMetadata = GetArticleEntityMetadata();

            var displayName = articleMetadata != null ? articleMetadata.DisplayName.UserLocalizedLabel.Label : string.Empty;

            var feedback = new Entity("feedback");

            feedback["title"]             = ResourceManager.GetString("Feedback_Default_Title").FormatWith(displayName, article.Title);
            feedback["rating"]            = rating;
            feedback["minrating"]         = minRating;
            feedback["maxrating"]         = maxRating;
            feedback["regardingobjectid"] = article.EntityReference;
            feedback["adx_approved"]      = true;
            feedback["source"]            = new OptionSetValue((int)FeedbackSource.Portal);

            if (author != null)
            {
                feedback["createdbycontact"] = author;
            }
            else if (!string.IsNullOrEmpty(visitorID))
            {
                feedback.Attributes[FeedbackMetadataAttributes.VisitorAttributeName] = visitorID;
            }

            context.AddObject(feedback);
            context.SaveChanges();

            if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
            {
                PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.KnowledgeArticle, HttpContext.Current, "create_rating_article", 1, feedback.ToEntityReference(), "create");
            }
        }
Example #31
0
        /// <summary>
        /// 启用
        /// </summary>
        /// <param name="service"></param>
        /// <param name="entity"></param>
        public static void Enable(this IOrganizationService service, Entity entity)
        {
            if (entity == null || entity.Id == Guid.Empty)
            {
                return;
            }
            OptionSetValue state  = new OptionSetValue();
            OptionSetValue status = new OptionSetValue();

            state.Value  = 0;
            status.Value = 1;

            EntityReference moniker = new EntityReference(entity.LogicalName, entity.Id);

            OrganizationRequest request = new OrganizationRequest()
            {
                RequestName = "SetState"
            };

            request["EntityMoniker"] = moniker;
            request["State"]         = state;
            request["Status"]        = status;
            service.Execute(request);
        }
Example #32
0
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext     context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
            ITracingService             tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            Entity obj = service.Retrieve(context.PrimaryEntityName, context.PrimaryEntityId, new ColumnSet(true));

            Entity update = new Entity();

            update.LogicalName                   = "account";
            update.Id                            = context.PrimaryEntityId;
            update["telephone1"]                 = "554545";
            update["websiteurl"]                 = "www.Test.com";
            update["customertypecode"]           = new OptionSetValue(3);
            update["address1_city"]              = "Ahmedabad";
            update["industrycode"]               = new OptionSetValue(1);
            update["preferredcontactmethodcode"] = new OptionSetValue(2);
            update["donotfax"]                   = true;
            update["creditlimit"]                = new Money(10000);

            service.Update(update);
        }
Example #33
0
        private Guid CreatePaymentRecord(int paymentType, decimal paymentAmount, List <Entity> relatedExpenses)
        {
            //Create Payment record
            Entity payment = new Entity("educ_payment");

            payment["educ_assignment"]  = new EntityReference("educ_assignment", assignmentId);
            payment["educ_paymenttype"] = new OptionSetValue(paymentType);
            payment["educ_amount"]      = new Money(paymentAmount);
            payment["statuscode"]       = new OptionSetValue(1);

            var paymentId = organizationService.Create(payment);

            //Update Expense Records with reference to payment record

            foreach (var expense in relatedExpenses)
            {
                expense["educ_payment"] = new EntityReference("educ_payment", paymentId);
                expense["statuscode"]   = new OptionSetValue(610410002);

                organizationService.Update(expense);
            }

            return(paymentId);
        }
Example #34
0
        private static void CreateStep(IOrganizationService service)
        {
            Guid messageId = new Guid("9EBDBB1B-EA3E-DB11-86A7-000A3A5473E8");

            Guid messageFitlerId = new Guid("C2C5BB1B-EA3E-DB11-86A7-000A3A5473E8");

            Entity step = new Entity("sdkmessageprocessingstep");

            step["name"]          = "Sdk Message track history test";
            step["configuration"] = "BPF history tracking";

            step["invocationsource"] = new OptionSetValue(0);
            step["sdkmessageid"]     = new EntityReference("sdkmessage", messageId);

            step["supporteddeployment"] = new OptionSetValue(0);
            step["plugintypeid"]        = new EntityReference("plugintype", new Guid("f41913ff-fa4d-43b0-afd7-098ca99427b5"));

            step["mode"]  = new OptionSetValue(0);
            step["rank"]  = 1;
            step["stage"] = new OptionSetValue(20);

            step["sdkmessagefilterid"] = new EntityReference("sdkmessagefilter", messageFitlerId);
            Guid stepId = service.Create(step);
        }
        private void StopProcess()
        {
            QueryExpression query = GetRunningProcessesQuery();

            foreach (var asyncOperation in _repository.Get(query))
            {
                OptionSetValue asyncOperationStatus = asyncOperation.GetAttributeValue <OptionSetValue>("statuscode");
                if (asyncOperationStatus.Value == 0 /* Wating for Resources */ || asyncOperationStatus.Value == 10 /* Waiting */ || asyncOperationStatus.Value == 20 /* In Process */)
                {
                    ExecuteAction(string.Format("{0}: {1}", asyncOperation.LogicalName, asyncOperation.Id), delegate
                    {
                        asyncOperation["statecode"]  = new OptionSetValue(3);
                        asyncOperation["statuscode"] = new OptionSetValue(32);

                        _repository.Update(asyncOperation);

                        if (PassThru)
                        {
                            WriteObject(_repository.Get("asyncoperation", asyncOperation.Id));
                        }
                    });
                }
            }
        }
Example #36
0
        public Entity GetEntity()
        {
            Entity i = new Entity(NombresCamposICS.EntityName);

            if (!Aen_ICSGUID.Equals(Guid.Empty))
            {
                i.Id = Aen_ICSGUID;
                i[NombresCamposICS.EntityId] = Aen_ICSGUID;
            }
            if (!Aen_Codigo_Ics.Equals(string.Empty))
            {
                i[NombresCamposICS.Aen_Codigo_IcsCRM] = Aen_Codigo_Ics;
            }
            if (!Aen_Descripcion_Ics.Equals(string.Empty))
            {
                i[NombresCamposICS.Aen_Descripcion_IcsCRM] = Aen_Descripcion_Ics;
            }
            if (!Aen_Descripcion_IcsEN.Equals(string.Empty))
            {
                i[NombresCamposICS.Aen_Descripcion_IcsENCRM] = Aen_Descripcion_IcsEN;
            }
            i[NombresCamposICS.Aen_Codigo_Ics_PadreCRM] = !Aen_Codigo_Ics_Padre.Equals(Guid.Empty) ? new EntityReference(NombresCamposICS.EntityName, Aen_Codigo_Ics_Padre) : null;

            if (Aen_Ics_Activo)
            {
                i[NombresCamposICS.Aen_Ics_ActivoCRM] = new OptionSetValue(0);
                i["statuscode"] = new OptionSetValue(1);
            }
            else
            {
                i[NombresCamposICS.Aen_Ics_ActivoCRM] = new OptionSetValue(1);
                //i["statuscode"] = new OptionSetValue(2);
            }

            return(i);
        }
Example #37
0
        /// <summary>
        /// Assigns the OptionSetProperty if the attribute name of the property is not already in the
        /// Attributes collection, and the enumValue is not null if set to Null is false
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="propertyExpression">In the form of e =&gt; e.OptionSetProperty</param>
        /// <param name="enumValue"></param>
        /// <param name="setToNull"></param>
        public static void SetValueIfNull <TEntity, TEnum>(this TEntity entity, Expression <Func <TEntity, OptionSetValue> > propertyExpression,
                                                           TEnum?enumValue, bool setToNull = false)
            where TEntity : Entity
            where TEnum : struct
        {
            if (enumValue == null && !setToNull)
            {
                return;
            }

            var name = propertyExpression.GetLowerCasePropertyName();

            if (!entity.Attributes.ContainsKey(name))
            {
                if (enumValue == null)
                {
                    entity[name] = null;
                }
                else
                {
                    entity[name] = new OptionSetValue((int)(object)enumValue.Value);
                }
            }
        }
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Create an appointment.
        /// </summary>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetMarketingAutomation1>
                // 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();

                    var course = new Entity("mshied_course");

                    course["mshied_startdate"]     = new DateTime(2018, 9, 4);
                    course["mshied_enddate"]       = new DateTime(2018, 12, 20);
                    course["mshied_coursenumber"]  = "343467897";
                    course["mshied_name"]          = "French 101";
                    course["mshied_academiclevel"] = new OptionSetValue(494280000);                     // 100

                    var id = _serviceProxy.Create(course);

                    // Verify that the record has been created.
                    if (id != Guid.Empty)
                    {
                        Console.WriteLine($"Successfully created {id}.");
                    }
                }
            }
            // 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;
            }
        }
Example #39
0
        /*
         *  Lead create Process allow end user to choose which name they want to use
         *  The purpose of we want the name as a parameter is that it can be easily track and create.
         */
        private static Guid CreateLeadWithSimpleinfor(OrganizationServiceProxy service, String name)
        {
            var leadSource = GetLeadSourceName(service, leadSourceName);
            var newLead    = new Entity("lead");

            var user = GetUser(service);

            newLead["companyname"]      = name;
            newLead["log_leadsourceid"] = leadSource.ToEntityReference();
            //newLead["ownerid"] = user.ToEntityReference();
            newLead["log_direction"]       = new OptionSetValue(182400001); //moved out
            newLead["log_contracttermsid"] = GetContractTerms(service).ToEntityReference();

            newLead["log_dateofbirth"] = DateTime.Now.AddYears(-19);
            //Date cannot be in the future
            newLead["log_solddate"]   = DateTime.Now;
            newLead["log_movingdate"] = DateTime.Now;

            newLead["log_salespersonid"] = GetSalesPerson(service).ToEntityReference();
            //street 1
            //newLead["log_takeovercase"] = GetTakdOverCASE(service).ToEntityReference();
            newLead["log_typeoflead"] = new OptionSetValue(182400002);
            return(service.Create(newLead));
        }
Example #40
0
        public static MsCrmResult AnswerNpsSurvey(Guid npsSurveyId, int suggest, int suggestPoint, IOrganizationService service)
        {
            MsCrmResult returnValue = new MsCrmResult();

            try
            {
                Entity ent = new Entity("new_npssurvey");
                ent.Id = npsSurveyId;
                ent["new_issuggest"] = new OptionSetValue(suggest);
                ent["new_suggestpoint"] = suggestPoint;
                ent["statuscode"] = new OptionSetValue((int)NpsSurveyStatus.Answered);

                service.Update(ent);
                returnValue.Success = true;
                returnValue.Result = "Nps Survey güncellendi.";
            }
            catch (Exception ex)
            {
                returnValue.HasException = true;
                returnValue.Result = ex.Message;
            }

            return returnValue;
        }
Example #41
0
        private void UpdateNpsSurveyEntityStatusCode(Guid surveyId, NpsSurveyStatus statusCode)
        {
            try
            {
                Entity ent = new Entity("new_npssurvey");
                ent.Id = surveyId;
                ent["statuscode"] = new OptionSetValue((int)statusCode);

                _service.Update(ent);
            }
            catch (Exception ex)
            {
                FileLogHelper.LogFunction(this.GetType().Name, "SendNpsSurvey_ServiceProcess_UpdateNpsSurveyEntityStatusCode_EXCEPTION:" + ex.Message, ERROR_LOG_PATH);
            }
        }
Example #42
0
        private void tvWebResources_DragDrop(object sender, DragEventArgs e)
        {
            var errorList = new List<string>();
            var tv = (TreeView)sender;
            Point location = tv.PointToScreen(Point.Empty);
            var currentNode = tvWebResources.GetNodeAt(e.X - location.X, e.Y - location.Y);

            var files = (string[])e.Data.GetData(DataFormats.FileDrop);

            foreach (var file in files)
            {
                var fi = new FileInfo(file);

                var tempNode = currentNode;
                string name = tempNode.Text;
                while (tempNode.Parent != null)
                {
                    name = string.Format("{0}/{1}", tempNode.Parent.Text, name);
                    tempNode = tempNode.Parent;
                }

                //Test valid characters
                if (WebResource.IsInvalidName(fi.Name))
                {
                    errorList.Add(file);
                }
                else
                {
                    var webResource = new Entity("webresource");
                    webResource["content"] = Convert.ToBase64String(File.ReadAllBytes(file));
                    webResource["webresourcetype"] = new OptionSetValue(WebResource.GetTypeFromExtension(fi.Extension.Remove(0, 1)));
                    webResource["name"] = string.Format("{0}/{1}", name, fi.Name);
                    webResource["displayname"] = string.Format("{0}/{1}", name, fi.Name);
                    var wr = new WebResource(webResource, file);

                    var node = new TreeNode(fi.Name)
                    {
                        ImageIndex = WebResource.GetImageIndexFromExtension(fi.Extension.Remove(0, 1))
                    };
                    node.SelectedImageIndex = node.ImageIndex;
                    node.Tag = wr;

                    currentNode.Nodes.Add(node);

                    currentNode.Expand();
                }
            }

            if (errorList.Count > 0)
            {
                MessageBox.Show("Some file have not been added since their name does not match naming policy\r\n"
                                + string.Join("\r\n", errorList));
            }
        }
        private bool CreateReport(Guid solutionId, string uniqueName, string name, string filePath, string relativePath, int viewableIndex)
        {
            try
            {
                CrmConnection connection = CrmConnection.Parse(_connection.ConnectionString);

                using (_orgService = new OrganizationService(connection))
                {
                    Entity report = new Entity("report");
                    report["name"] = name;
                    report["bodytext"] = File.ReadAllText(filePath);
                    report["reporttypecode"] = new OptionSetValue(1); //ReportingServicesReport
                    report["filename"] = Path.GetFileName(filePath);
                    report["languagecode"] = 1033; //TODO: handle multiple 
                    report["ispersonal"] = (viewableIndex == 0);

                    Guid id = _orgService.Create(report);

                    _logger.WriteToOutputWindow("Report Created: " + id, Logger.MessageType.Info);

                    //Add to the choosen solution (not default)
                    if (solutionId != new Guid("FD140AAF-4DF4-11DD-BD17-0019B9312238"))
                    {
                        AddSolutionComponentRequest scRequest = new AddSolutionComponentRequest
                        {
                            ComponentType = 31,
                            SolutionUniqueName = uniqueName,
                            ComponentId = id
                        };
                        AddSolutionComponentResponse response =
                            (AddSolutionComponentResponse)_orgService.Execute(scRequest);

                        _logger.WriteToOutputWindow("New Report Added To Solution: " + response.id, Logger.MessageType.Info);
                    }

                    NewId = id;
                    NewName = name;
                    NewBoudndFile = relativePath;

                    return true;
                }
            }
            catch (FaultException<OrganizationServiceFault> crmEx)
            {
                _logger.WriteToOutputWindow("Error Creating Report: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error);
                return false;
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error Creating Report: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error);
                return false;
            }
        }
        public void When_filtering_by_an_enum_attribute_and_using_proxy_types_right_result_is_returned()
        {
            var fakedContext = new XrmFakedContext { };

            var entityAccount = new Account { Id = Guid.NewGuid(), Name = "Test Account", LogicalName = "account" };
            var entityContact = new Contact { Id = Guid.NewGuid(), ParentCustomerId = entityAccount.ToEntityReference(), EMailAddress1 = "*****@*****.**" };

            var entityCase = new Incident
            {
                Id = Guid.NewGuid(),
                PrimaryContactId = entityContact.ToEntityReference(),
                CustomerId = entityAccount.ToEntityReference(),
                Title = "Unit Test Case"
            };

            entityCase["statecode"] = new OptionSetValue((int) IncidentState.Active);

            fakedContext.Initialize(new List<Entity>() {
               entityAccount,entityContact, entityCase
            });


            var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' >
              <entity name='incident' >
                <attribute name='incidentid' />
                <attribute name='statecode' /> 
                <order attribute='createdon' descending='true' /> 
                 <filter type='and' > 
                  <condition attribute='statecode' operator='neq' value='2' /> 
                </filter>
              </entity>
            </fetch>";

            var rows = fakedContext.GetFakedOrganizationService().RetrieveMultiple(new FetchExpression(fetchXml));
            Assert.Equal(rows.Entities.Count, 1);

        }
 private void UpdateRecords()
 {
     if (working)
     {
         return;
     }
     if (!(cmbAttribute.SelectedItem is AttributeItem))
     {
         MessageBox.Show("Select an attribute to update from the list.");
         return;
     }
     if (MessageBox.Show("All selected records will unconditionally be updated.\nUI defined rules will not be enforced.\n\nConfirm update!",
         "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) != DialogResult.OK)
     {
         return;
     }
     var attributeitem = (AttributeItem)cmbAttribute.SelectedItem;
     var onlychange = chkOnlyChange.Checked;
     var entity = records.EntityName;
     var attributes = new List<string>();
     attributes.Add(attributeitem.GetValue());
     if (attributes[0] == "statuscode")
     {
         attributes.Add("statecode");
     }
     var touch = rbSetTouch.Checked;
     var value = rbSetValue.Checked ? GetValue(attributeitem.Metadata.AttributeType) : null;
     OptionSetValue statevalue = null;
     if (attributeitem.Metadata is StatusAttributeMetadata && value is OptionSetValue)
     {
         var statusmeta = (StatusAttributeMetadata)attributeitem.Metadata;
         foreach (var statusoption in statusmeta.OptionSet.Options)
         {
             if (statusoption is StatusOptionMetadata && statusoption.Value == ((OptionSetValue)value).Value)
             {
                 statevalue = new OptionSetValue((int)((StatusOptionMetadata)statusoption).State);
                 break;
             }
         }
     }
     working = true;
     WorkAsync("Updating records",
         (bgworker, workargs) =>
         {
             var total = records.Entities.Count;
             var current = 0;
             var updated = 0;
             foreach (var record in records.Entities)
             {
                 current++;
                 var pct = 100 * current / total;
                 var attributesexists = true;
                 foreach (var attribute in attributes)
                 {
                     if (!record.Contains(attribute))
                     {
                         attributesexists = false;
                         break;
                     }
                 }
                 if ((onlychange || touch) && !attributesexists)
                 {
                     bgworker.ReportProgress(pct, "Reloading record " + current.ToString());
                     var newcols = new ColumnSet(attributes.ToArray());
                     var newrecord = Service.Retrieve(entity, record.Id, newcols);
                     foreach (var attribute in attributes)
                     {
                         if (newrecord.Contains(attribute) && !record.Contains(attribute))
                         {
                             record.Attributes.Add(attribute, newrecord[attribute]);
                         }
                     }
                 }
                 bgworker.ReportProgress(pct, "Updating record " + current.ToString());
                 if (attributeitem.Metadata is StatusAttributeMetadata)
                 {
                     UpdateState(touch, onlychange, (OptionSetValue)value, statevalue, record);
                 }
                 else
                 {
                     // This currently only supports ONE attribute being updated, can be expanded to set/touch several attributes in the future
                     var currentvalue = record.Contains(attributes[0]) ? record[attributes[0]] : null;
                     if (touch)
                     {
                         value = currentvalue;
                     }
                     UpdateAttributes(onlychange, entity, attributes, value, record, currentvalue);
                 }
                 updated++;
             }
             workargs.Result = updated;
         },
         (completedargs) =>
         {
             working = false;
             if (completedargs.Error != null)
             {
                 MessageBox.Show(completedargs.Error.Message, "Update", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
             else
             {
                 lblUpdateStatus.Text = completedargs.Result.ToString() + " records updated";
             }
         },
         (changeargs) =>
         {
             SetWorkingMessage(changeargs.UserState.ToString());
         });
 }
Example #46
0
        /// <summary>
        /// Executes the plug-in.
        /// </summary>
        /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        /// <see cref="IPluginExecutionContext"/>,
        /// <see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        /// </param>
        /// <remarks>
        /// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
        /// The plug-in's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the plug-in. Also, multiple system threads
        /// could execute the plug-in at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in plug-ins.
        /// </remarks>
        protected void ExecutePricingOrderCreate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            // TODO: Implement your custom Plug-in business logic.

            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService service = localContext.OrganizationService;

            Guid quoteDetailID = (Guid)((Entity)context.InputParameters["Target"]).Id;
            ColumnSet set = new ColumnSet();
            set.AllColumns = true;
            var orderDetail = service.Retrieve("salesorderdetail", quoteDetailID, set);
            const decimal minimumValue = 0;
            const decimal minimumRatio = 1;

            if (context.Depth > 1)
            {
                return;
            }
            else
            {
                var priceperunit = (Money)orderDetail["priceperunit"];
                orderDetail["new_specificdiscountpercentage"] = minimumValue;
                orderDetail["new_ratio"] = minimumRatio;
                orderDetail["new_grossannualincome"] = new Money(minimumValue);
                orderDetail["new_gaixratio"] = new Money(minimumValue);
                orderDetail["new_recommendedvalue"] = priceperunit;
                //orderDetail["new_fixedpriceplusratio"] = priceperunit;

                //This sets the current pricing type of the quote product, to the default pricing type of the quote
                var parentOrder = (EntityReference)orderDetail["salesorderid"];

                var quote = service.Retrieve(parentOrder.LogicalName, parentOrder.Id, new ColumnSet(true));

                var pricingType = (OptionSetValue)quote["new_pricingtype"];

                orderDetail["new_pricingtype"] = new OptionSetValue(pricingType.Value);

                service.Update(orderDetail);
            }
        }
Example #47
0
        internal static void CreateEmptyWebResource(string extension, TreeView tv, Control mainControl)
        {
            var callerNode = tv.SelectedNode;

            var nwrDialog = new NewWebResourceDialog(extension) { StartPosition = FormStartPosition.CenterParent };

            if (nwrDialog.ShowDialog(mainControl) == DialogResult.OK)
            {
                var tempNode = callerNode;
                string name = callerNode.Text;
                while (tempNode.Parent != null)
                {
                    name = string.Format("{0}/{1}", tempNode.Parent.Text, name);
                    tempNode = tempNode.Parent;
                }

                var webResource = new Entity("webresource");
                webResource["content"] = "";
                webResource["webresourcetype"] = new OptionSetValue(WebResource.GetTypeFromExtension(extension));
                webResource["name"] = string.Format("{0}/{1}", name, string.Format("{0}.{1}", nwrDialog.WebResourceName, extension));
                var wr = new WebResource(webResource, null);

                var parts = nwrDialog.WebResourceName.Split('/');

                for (int i = 0; i < parts.Length; i++)
                {
                    if (i != parts.Length - 1)
                    {
                        var folderNode = new TreeNode(parts[i]) { ImageIndex = 1, SelectedImageIndex = 1 };

                        callerNode.Nodes.Add(folderNode);
                        callerNode.Expand();
                        callerNode = folderNode;
                    }
                    else
                    {
                        var node = new TreeNode(string.Format("{0}.{1}", parts[i], extension))
                        {
                            ImageIndex =
                                WebResource.GetImageIndexFromExtension
                                (extension)
                        };
                        node.SelectedImageIndex = node.ImageIndex;
                        node.Tag = wr;

                        callerNode.Nodes.Add(node);
                        callerNode.Expand();
                    }
                }
            }
        }
Example #48
0
        internal static void AddExistingWebResource(TreeView tv, Control mainControl)
        {
            TreeNode selectedNode = tv.SelectedNode;
            TreeNode tempNode = selectedNode;

            string name = tempNode.Text;
            while (tempNode.Parent != null)
            {
                name = string.Format("{0}/{1}", tempNode.Parent.Text, name);
                tempNode = tempNode.Parent;
            }

            var ofd = new OpenFileDialog { Multiselect = true, Title = "Select file(s) for web resource(s)" };

            if (ofd.ShowDialog(mainControl) == DialogResult.OK)
            {
                var errorList = new List<string>();

                foreach (string fileName in ofd.FileNames)
                {
                    var fi = new FileInfo(fileName);

                    //Test valid characters
                    if (WebResource.IsInvalidName(fi.Name))
                    {
                        errorList.Add(fileName);
                    }
                    else
                    {
                        var webResource = new Entity("webresource");
                        webResource["content"] = Convert.ToBase64String(File.ReadAllBytes(fileName));
                        webResource["webresourcetype"] =
                            new OptionSetValue(WebResource.GetTypeFromExtension(fi.Extension.Remove(0, 1)));
                        webResource["name"] = string.Format("{0}/{1}", name, fi.Name);
                        webResource["displayname"] = string.Format("{0}/{1}", name, fi.Name);
                        var wr = new WebResource(webResource, fileName);

                        var node = new TreeNode(fi.Name)
                        {
                            ImageIndex =
                                WebResource.GetImageIndexFromExtension(fi.Extension.Remove(0,
                                                                               1))
                        };
                        node.SelectedImageIndex = node.ImageIndex;
                        node.Tag = wr;

                        selectedNode.Nodes.Add(node);

                        selectedNode.Expand();
                    }

                    if (errorList.Count > 0)
                    {
                        MessageBox.Show("Some file have not been added since their name does not match naming policy\r\n"
                                        + string.Join("\r\n", errorList));
                    }
                }
            }

            tv.TreeViewNodeSorter = new NodeSorter();
            tv.Sort();
        }
Example #49
0
        /// <summary>
        /// Create a TreeNode for the javascript file passed in parameter
        /// </summary>
        /// <param name="fiChild">Javascript FileInfo</param>
        /// <param name="parent">Parent element (TreeView or TreeNode)</param>
        public static void CreateWebResourceNode(FileInfo fiChild, object parent)
        {
            string scriptName = fiChild.Name;
            string fileName = scriptName;

            // Creating the script "name" attribute which depends on the current
            // TreeView structure
            var treeNode = parent as TreeNode;
            if (treeNode != null)
            {
                var parentNode = treeNode;

                while (parentNode != null && !parentNode.Text.EndsWith("_"))
                {
                    fileName = string.Format("{0}/{1}", parentNode.Text, fileName);
                    parentNode = parentNode.Parent;
                }

                if (parentNode != null)
                    fileName = string.Format("{0}/{1}", parentNode.Text, fileName);
            }

            int imageIndex = 0;

            switch (fiChild.Extension.ToLower().Remove(0, 1))
            {
                case "html":
                case "htm":
                    imageIndex = 2;
                    break;

                case "css":
                    imageIndex = 3;
                    break;

                case "js":
                    imageIndex = 4;
                    break;

                case "xml":
                    imageIndex = 5;
                    break;

                case "png":
                    imageIndex = 6;
                    break;

                case "jpg":
                    imageIndex = 7;
                    break;

                case "gif":
                    imageIndex = 8;
                    break;

                case "xap":
                    imageIndex = 9;
                    break;

                case "xsl":
                    imageIndex = 10;
                    break;

                case "ico":
                    imageIndex = 11;
                    break;
            }

            // Create new virtual web resource
            var script = new Entity("webresource");
            script["name"] = fileName;
            script["webresourcetype"] = new OptionSetValue(imageIndex - 1);

            // Add content
            script["content"] = Convert.ToBase64String(File.ReadAllBytes(fiChild.FullName));

            // Generate display name (Credit to badhabits)
            var lastSlash = fileName.LastIndexOf("/", StringComparison.Ordinal);
            var displayName = lastSlash > -1
                ? fileName.Substring(lastSlash + 1)
                : fileName;
            script["displayname"] = displayName;

            var scriptObject = new WebResource(script, fiChild.FullName);

            var node = new TreeNode
            {
                Text = scriptName,
                Name = scriptName,
                Tag = scriptObject,
                ImageIndex = imageIndex,
                SelectedImageIndex = imageIndex
            };

            var node1 = parent as TreeNode;
            if (node1 != null)
            {
                node1.Nodes.Add(node);
            }
            else
            {
                ((TreeView)parent).Nodes.Add(node);
            }
        }
 protected void btnSave_Click(object sender, EventArgs e)
 {
     if (txtPassword.Text != txtPassword1.Text)
     {
         MessageBox.Show("رمز عبور و تکرار رمز عبور، یکسان نمی باشد");
         return;
     }
     if (!CheckEmail())
     {
         MessageBox.Show("آدرس پست الکترونیک در سیستم وجود دارد");
         return;
     }
     Entity Contact = new Entity("contact");
     Contact["firstname"] = txtName.Text.Trim();
     Contact["lastname"] = txtFamily.Text.Trim();
     Contact["helpdesk_personnelcode"] = txtEmployeeNo.Text.Trim();
     Contact["helpdesk_salutaion"] = new OptionSetValue(Convert.ToInt32(Salutation.SelectedValue));
     Contact["parentcustomerid"] = new EntityReference("account", new Guid(Department.SelectedValue.ToString()));
     Contact["emailaddress1"] = txtEmail.Text.Trim();
     Contact["mobilephone"] = txtMobile.Text.Trim();
     Contact["helpdesk_password"] = txtPassword.Text;
     Contact["helpdesk_requestforuser"] = CheckBoxSms.Checked;
     Contact["helpdesk_usesms"] = CheckBoxCrm.Checked;
     crmService.Create(Contact);
     Response.Redirect("RegistrationConfirm.aspx");
 }
        /// <summary>
        /// Executes the plug-in.
        /// </summary>
        /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        /// <see cref="IPluginExecutionContext"/>,
        /// <see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        /// </param>
        /// <remarks>
        /// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
        /// The plug-in's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the plug-in. Also, multiple system threads
        /// could execute the plug-in at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in plug-ins.
        /// </remarks>
        protected void ExecutePostOrderProductUpdate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }
            // TODO: Implement your custom Plug-in business logic.

            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService service = localContext.OrganizationService;
            Guid orderProductID = (Guid)((Entity)context.InputParameters["Target"]).Id;
            ColumnSet set = new ColumnSet();
            set.AllColumns = true;
            var order = service.Retrieve("salesorder", orderProductID, set);


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

                //First I get the base values that I need for the calculations

                var pricingType = (OptionSetValue)order["new_pricingtype"];

                ConditionExpression condition = new ConditionExpression();
                condition.AttributeName = "salesorderid";
                condition.Operator = ConditionOperator.Equal;
                condition.Values.Add(orderProductID);

                FilterExpression filter = new FilterExpression();
                filter.AddCondition(condition);

                QueryExpression query = new QueryExpression();
                query.EntityName = "salesorderdetail";
                query.ColumnSet = new ColumnSet(true);
                query.Criteria = filter;

                EntityCollection salesorderDetail = service.RetrieveMultiple(query);

                foreach (var detail in salesorderDetail.Entities)
                {
                    detail["new_pricingtype"] = new OptionSetValue(pricingType.Value);
                    service.Update(detail);
                }
                service.Update(order);
            }
        }
 private void CreateJavascriptWebresource(string filePath, string fileName)
 {
     Log(tbLogJavascript, $"Attempting to create javascript webresource {fileName} in CRM");
     var jsWebResource = new Entity("webresource");
     jsWebResource["name"] = "scripts_/"+string.Join("\\", filePath.Split('\\').Skip(1)).Replace("\\","/");
     jsWebResource["displayname"] = fileName;
     jsWebResource["webresourcetype"] = new OptionSetValue(3);//javascript
     jsWebResource["content"] = Convert.ToBase64String(ReadFile(filePath));
     try
     {
         Service.Create(jsWebResource);
     }
     catch (FaultException<OrganizationServiceFault> fe)
     {
         Log(tbLogJavascript, $"Unable to create Javascript webresource {fileName}. {fe.Message}", MessageType.ERROR);
     }
     Log(tbLogJavascript, $"Created Javascript webresource {fileName} in CRM");
 }
        private void btnValidate_Click(object sender, EventArgs e)
        {
            try
            {
                Entity webR = new Entity("webresource");
                webR["displayname"] = txtDisplayName.Text;

                string ext = txtFile.Text.Split('.')[txtFile.Text.Split('.').Length - 1];

                switch (ext.ToLower())
                {
                    case "html":
                        webR["webresourcetype"] = new OptionSetValue(1);
                        break;

                    case "png":
                        webR["webresourcetype"] = new OptionSetValue(5);
                        break;

                    case "jpg":
                        webR["webresourcetype"] = new OptionSetValue(6);
                        break;

                    case "gif":
                        webR["webresourcetype"] = new OptionSetValue(7);
                        break;
                }

                webR["name"] = txtName.Text;
                webR["content"] = getEncodedFileContents(txtFile.Text);

                Guid wrId = service.Create(webR);

                webR["webresourceid"] = wrId;

                CreatedEntity = webR;
                DialogResult = DialogResult.OK;
                Close();
            }
            catch (Exception error)
            {
                MessageBox.Show("An error occured while creating the web resource: " + error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private bool CreateWebResource(Guid solutionId, string uniqueName, int type, string prefix, string name, string displayName, string filePath, string relativePath)
        {
            try
            {
                CrmConnection connection = CrmConnection.Parse(_connection.ConnectionString);

                using (_orgService = new OrganizationService(connection))
                {
                    Entity webResource = new Entity("webresource");
                    webResource["name"] = prefix + name;
                    webResource["webresourcetype"] = new OptionSetValue(type);
                    if (!string.IsNullOrEmpty(displayName))
                        webResource["displayname"] = displayName;

                    if (type == 8)
                        webResource["silverlightversion"] = "4.0";

                    string extension = Path.GetExtension(filePath);

                    List<string> imageExs = new List<string>() { ".ICO", ".PNG", ".GIF", ".JPG" };
                    string content;
                    //TypeScript
                    if (extension != null && (extension.ToUpper() == ".TS"))
                    {
                        content = File.ReadAllText(Path.ChangeExtension(filePath, ".js"));
                        webResource["content"] = EncodeString(content);
                    }
                    //Images
                    else if (extension != null && imageExs.Any(s => extension.ToUpper().EndsWith(s)))
                    {
                        content = EncodedImage(filePath, extension);
                        webResource["content"] = content;
                    }
                    //Everything else
                    else
                    {
                        content = File.ReadAllText(filePath);
                        webResource["content"] = EncodeString(content);
                    }

                    Guid id = _orgService.Create(webResource);

                    _logger.WriteToOutputWindow("New Web Resource Created: " + id, Logger.MessageType.Info);

                    //Add to the choosen solution (not default)
                    if (solutionId != new Guid("FD140AAF-4DF4-11DD-BD17-0019B9312238"))
                    {
                        AddSolutionComponentRequest scRequest = new AddSolutionComponentRequest
                        {
                            ComponentType = 61,
                            SolutionUniqueName = uniqueName,
                            ComponentId = id
                        };
                        AddSolutionComponentResponse response =
                            (AddSolutionComponentResponse)_orgService.Execute(scRequest);

                        _logger.WriteToOutputWindow("New Web Resource Added To Solution: " + response.id, Logger.MessageType.Info);
                    }

                    NewId = id;
                    NewType = type;
                    NewName = prefix + name;
                    if (!string.IsNullOrEmpty(displayName))
                        NewDisplayName = displayName;
                    NewBoundFile = relativePath;
                    NewSolutionId = solutionId;

                    return true;
                }
            }
            catch (FaultException<OrganizationServiceFault> crmEx)
            {
                _logger.WriteToOutputWindow("Error Creating Web Resource: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error);
                return false;
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error Creating Web Resource: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error);
                return false;
            }
        }
Example #55
0
        public static MsCrmResult CreateOrUpdateProfile(Contact contact, IOrganizationService service)
        {
            MsCrmResult returnValue = new MsCrmResult();
            try
            {
                Entity ent = new Entity("contact");

                if (!string.IsNullOrEmpty(contact.MobilePhone))
                {
                    ent["mobilephone"] = contact.MobilePhone;
                }

                if (!string.IsNullOrEmpty(contact.WorkPhone))
                {
                    ent["telephone1"] = contact.WorkPhone;
                }

                if (!string.IsNullOrEmpty(contact.IdentityNumber))
                {
                    ent["new_identitynumber"] = contact.IdentityNumber;
                }

                if (contact.Gender != null)
                {
                    ent["gendercode"] = new OptionSetValue((int)contact.Gender);
                }

                if (contact.BirthDate != null)
                {
                    ent["birthdate"] = contact.BirthDate;
                }

                if (!string.IsNullOrEmpty(contact.Description))
                {
                    ent["description"] = contact.Description;
                }

                if (!string.IsNullOrEmpty(contact.EmailAddress))
                {
                    ent["emailaddress1"] = contact.EmailAddress;
                }

                if (!string.IsNullOrEmpty(contact.FirstName))
                {
                    ent["firstname"] = contact.FirstName;
                }

                if (!string.IsNullOrEmpty(contact.LastName))
                {
                    ent["lastname"] = contact.LastName;
                }

                if (!string.IsNullOrEmpty(contact.Title))
                {
                    ent["jobtitle"] = contact.Title;
                }
                if (!string.IsNullOrEmpty(contact.FunctionName))
                {
                    ent["new_functionname"] = contact.FunctionName;
                }

                if (contact.ParentAccount != null)
                {
                    ent["parentaccountid"] = contact.ParentAccount;
                }

                if (contact.CityId != null)
                {
                    ent["new_cityid"] = contact.CityId;
                }

                if (contact.TownId != null)
                {
                    ent["new_townid"] = contact.TownId;
                }

                if (!string.IsNullOrEmpty(contact.AddressDetail))
                {
                    ent["new_addressdetail"] = contact.AddressDetail;
                }

                if (contact.MarkContact != null)
                {
                    ent["new_markcontact"] = contact.MarkContact;
                }

                if (contact.ContactId != Guid.Empty)
                {
                    ent["contactid"] = contact.ContactId;

                    service.Update(ent);
                    returnValue.Success = true;
                    returnValue.Result = "M009"; //"Profil güncellendi.";
                }
                else
                {
                    returnValue.CrmId = service.Create(ent);
                    returnValue.Success = true;
                    returnValue.Result = "M010"; //"Profil oluşturuldu.";
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            return returnValue;
        }
 private void UpdateState(bool touch, bool onlychange, OptionSetValue statusvalue, OptionSetValue statevalue, Entity record)
 {
     var currentstate = record.Contains("statecode") ? record["statecode"] : new OptionSetValue(-1);
     var currentstatus = record.Contains("statuscode") ? record["statuscode"] : new OptionSetValue(-1);
     if (touch)
     {
         statevalue = (OptionSetValue)currentstate;
         statusvalue = (OptionSetValue)currentstatus;
     }
     if (!onlychange || !ValuesEqual(currentstate, statevalue) || !ValuesEqual(currentstatus, statusvalue))
     {
         var req = new SetStateRequest()
         {
             EntityMoniker = record.ToEntityReference(),
             State = statevalue,
             Status = statusvalue
         };
         var resp = Service.Execute(req);
         if (record.Contains("statecode"))
         {
             record["statecode"] = statevalue;
         }
         else
         {
             record.Attributes.Add("statecode", statevalue);
         }
         if (record.Contains("statuscode"))
         {
             record["statuscode"] = statusvalue;
         }
         else
         {
             record.Attributes.Add("statuscode", statusvalue);
         }
     }
 }
 private Guid CreateAssembly(string filePath)
 {
     var assemblyId = Guid.Empty;
     Log(tbLogPlugin, $"Attempting to create assembly in {filePath} in CRM");
     var assembly = Assembly.LoadFrom(filePath);
     var assemblyName = assembly.GetName();
     var assemblyTokenBytes = assemblyName.GetPublicKeyToken();
     var crmAssembly = new Entity("pluginassembly");
     crmAssembly["name"] = assemblyName.Name;
     crmAssembly["sourcetype"] = new OptionSetValue(0); //database
     crmAssembly["content"] = Convert.ToBase64String(ReadFile(filePath));
     crmAssembly["culture"] = assemblyName.CultureInfo == System.Globalization.CultureInfo.InvariantCulture ? "neutral" : assemblyName.CultureInfo.Name;
     if(assemblyTokenBytes == null || assemblyTokenBytes.Length == 0)
     {
         crmAssembly["publickeytoken"] = null;
     }
     else
     {
         crmAssembly["publickeytoken"] = string.Join(string.Empty, assemblyTokenBytes.Select(b => b.ToString("X2")));
     }
     crmAssembly["version"] = assemblyName.Version.ToString();
     crmAssembly["name"] = assemblyName.Name;
     if (ConnectionDetail.UseOnline)
     {
         crmAssembly["isolationmode"] = new OptionSetValue((int)Common.SDK.IsolationMode.Sandbox);
     }
     else
     {
         crmAssembly["isolationmode"] = new OptionSetValue((int)Common.SDK.IsolationMode.None);
     }
     try
     {
         assemblyId = Service.Create(crmAssembly);
     }
     catch (FaultException<OrganizationServiceFault> fe)
     {
         Log(tbLogPlugin, $"Unable to create assembly {assemblyName.Name}. {fe.Message}", MessageType.ERROR);
     }
     Log(tbLogPlugin, $"Created assembly {assemblyName.Name} in CRM");
     return assemblyId;
 }
Example #58
0
        /// <summary>
        /// Executes the plug-in.
        /// </summary>
        /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        /// <see cref="IPluginExecutionContext"/>,
        /// <see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        /// </param>
        /// <remarks>
        /// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
        /// The plug-in's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the plug-in. Also, multiple system threads
        /// could execute the plug-in at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in plug-ins.
        /// </remarks>
        protected void ExecuteInvoiceVATer(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            // TODO: Implement your custom Plug-in business logic.

            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService service = localContext.OrganizationService;
            Guid invoiceID = (Guid)((Entity)context.InputParameters["Target"]).Id;
            ColumnSet set = new ColumnSet();
            set.AllColumns = true;
            var invoice = service.Retrieve("invoice", invoiceID, set);


            if (context.Depth > 1)
            {
                return;
            }
            else
            {
                var totalamount = (Money)invoice["totallineitemamount"];
                var discount = (Money)invoice["totaldiscountamount"];

                var VAT = (OptionSetValue)invoice["new_vat"];
                var tax = totalamount.Value * VAT.Value / 100;

                ConditionExpression condition = new ConditionExpression();
                condition.AttributeName = "invoiceid";
                condition.Operator = ConditionOperator.Equal;
                condition.Values.Add(invoiceID);

                FilterExpression filter = new FilterExpression();
                filter.AddCondition(condition);

                QueryExpression query = new QueryExpression();
                query.EntityName = "invoicedetail";
                query.ColumnSet = new ColumnSet(true);
                query.Criteria = filter;

                EntityCollection invoicedetails = service.RetrieveMultiple(query);

                foreach (var detail in invoicedetails.Entities)
                {
                    bool isLocked = (bool)detail.Attributes["invoiceispricelocked"];

                    if (isLocked)
                    {
                        //It is really important to unlock both the Invoice and the Order!
                        UnlockInvoicePricingRequest unlockInvoice = new UnlockInvoicePricingRequest();
                        unlockInvoice.InvoiceId = ((EntityReference)detail.Attributes["invoiceid"]).Id;
                        UnlockInvoicePricingResponse unlockInvoiceResponse = (UnlockInvoicePricingResponse)service.Execute(unlockInvoice);
                    }

                    var quantity = (decimal)detail["quantity"];
                    var priceperunit = (Money)detail["priceperunit"];
                    var teamleader = (OptionSetValue)detail["new_tldiscount"];

                    //Then I calculate the manual discount and baseamount, for the further calculations
                    detail.Attributes["manualdiscountamount"] = new Money((priceperunit.Value * teamleader.Value / 100) * quantity);
                    var manualdiscountamount = (Money)detail.Attributes["manualdiscountamount"];
                    detail.Attributes["baseamount"] = new Money(priceperunit.Value * quantity);
                    var baseamount = (Money)detail["baseamount"];

                    //finally I calculate the tax
                    detail["new_vat"] = new OptionSetValue(VAT.Value);
                    var taxDetail = (baseamount.Value - manualdiscountamount.Value) * VAT.Value / 100;
                    detail.Attributes["tax"] = new Money(taxDetail); //tax

                    service.Update(detail);
                }

                invoice["new_totalamountincludingvat"] = new Money((totalamount.Value - discount.Value) + tax);

                service.Update(invoice);
            }
        }
Example #59
0
        /// <summary>
        /// Executes the plug-in.
        /// </summary>
        /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        /// <see cref="IPluginExecutionContext"/>,
        /// <see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        /// </param>
        /// <remarks>
        /// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
        /// The plug-in's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the plug-in. Also, multiple system threads
        /// could execute the plug-in at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in plug-ins.
        /// </remarks>
        protected void ExecuteGetSiteMap(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            Entity output = new Entity("webresource");

            IOrganizationService service = localContext.OrganizationService;
            ITracingService trace = localContext.TracingService;

            // Exract the search criteria 
            QueryBase query = (QueryBase)localContext.PluginExecutionContext.InputParameters["Query"];
            Type queryType = query.GetType();
            if (queryType == typeof(QueryExpression))
            {
                trace.Trace("Found QueryExpression");
                // Get condition
                QueryExpression queryExpression = (QueryExpression)query;
                if (queryExpression.EntityName != "webresource")
                    return;

                if (queryExpression.Criteria == null || queryExpression.Criteria.Conditions.Count != 1 || queryExpression.Criteria.Conditions[0].AttributeName != "name")
                    return;

                string webresourceName = (string)queryExpression.Criteria.Conditions[0].Values[0];
                if ((webresourceName.Length > SiteMapResourceName.Length + 3) && webresourceName.StartsWith(SiteMapResourceName) && webresourceName.EndsWith(".js"))
                {

                    string lcid = webresourceName.Substring(16);
                    lcid = lcid.Substring(0, lcid.Length - 3);
                    trace.Trace("LCID={0}",lcid);
                    var outputCollection = (EntityCollection)localContext.PluginExecutionContext.OutputParameters["BusinessEntityCollection"];
                    SiteMapLoader siteMap = new SiteMapLoader(int.Parse(lcid));
                    StringWriter json = new StringWriter();

                    siteMap.ParseSiteMapToJson(service, trace, json);

                    var scriptBytes = System.Text.Encoding.UTF8.GetBytes(json.ToString());
                    trace.Trace("Parsed Sit Map OK");

                    output["name"] = webresourceName;
                    output["content"] = System.Convert.ToBase64String(scriptBytes);
                    output["webresourcetype"] = new OptionSetValue(3);
                    outputCollection.Entities.Clear();
                    outputCollection.Entities.Add(output);
                }
            }
        }
 public bool Equals(OptionSetValue x, OptionSetValue y)
 {
     if (x != null)
         return x.Value.Equals(y.Value);
     else
         return false;
 }