예제 #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 void AssignAdminRole(IOrganizationService service, Guid id)
        {
            string adminRoleName = "System Administrator";
            try
            {
                QueryExpression query = new QueryExpression
                {
                    EntityName = "role",
                    ColumnSet = new ColumnSet("name"),
                    Criteria = new FilterExpression
                {
                    Conditions =
                    {
                        new ConditionExpression
                        {
                                AttributeName = "name",
                                Operator = ConditionOperator.Equal,
                                Values = {adminRoleName}
                        }
                    }
                }
                };
                EntityCollection roles = service.RetrieveMultiple(query);
                EntityReferenceCollection entityRefCln = new EntityReferenceCollection();
                foreach (Entity entity in roles.Entities)
                {
                        entityRefCln.Add(entity.ToEntityReference());
                }
                service.Associate("team", id, new Relationship("teamroles_association"), entityRefCln);
            }
            catch (Exception ex)
            {

            }
        }
예제 #3
1
        /// <summary>
        /// Code to create account task for new accounts
        /// </summary>
        /// <param name="service">crm service</param>
        /// <param name="accountEntity">entity of the newly created account</param>
        public void CreateAccountTask(IOrganizationService service, Entity accountEntity)
        {
            try
            {

                //create new task for account set in 2 weeks in the future
                Microsoft.Xrm.Sdk.Entity contactAccountTask = new Entity("task");
                contactAccountTask["subject"] = "Check new account is happy";
                contactAccountTask["description"] =
                "Make contact with new customer. See if they are happy with service and resolve any issues.";
                contactAccountTask["scheduledstart"] = DateTime.Now.AddDays(14);
                contactAccountTask["scheduledend"] = DateTime.Now.AddDays(14);
                Microsoft.Xrm.Sdk.EntityReference entRef = new EntityReference("account", accountEntity.Id);
                contactAccountTask["regardingobjectid"] = entRef;

                // Create the task and this should be linked to the new account record
                service.Create(contactAccountTask);

            }

            catch (FaultException ex)
            {
                throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
            }
        }
예제 #4
0
 /// <summary>
 /// Creates a new account with a given name using the supplied organization service
 /// </summary>
 /// <param name="accountName">account name</param>
 /// <param name="service">organization service</param>
 /// <returns>id of the new account</returns>
 public static Guid CreateCrmAccount(string accountName, IOrganizationService service)
 {
     Entity account = new Entity("account");
     account["name"] = accountName;
     Guid newId = service.Create(account);
     return newId;
 }
        private string GetOptionsSetTextOnValue(IOrganizationService service, string entityName, string attributeName, int selectedValue, int LanCode)
        {
            RetrieveAttributeRequest retrieveAttributeRequest = new
            RetrieveAttributeRequest
            {

                EntityLogicalName = entityName,
                LogicalName = attributeName,
                RetrieveAsIfPublished = true
            };
            RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
            PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
            OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();

            string selectedOptionLabel = string.Empty;
            foreach (OptionMetadata oMD in optionList)
            {
                if (oMD.Value == selectedValue)
                {
                    foreach (var item in oMD.Label.LocalizedLabels)
                    {
                        if (item.LanguageCode == LanCode)
                        {
                            selectedOptionLabel = item.Label;
                        }
                    }
                }
            }
            return selectedOptionLabel;
        }
예제 #6
0
        public static int UpdateRank(IOrganizationService service, Entity workflow)
        {
            var wf = service.Retrieve("workflow", workflow.Id, new ColumnSet("statecode"));
            if (wf.GetAttributeValue<OptionSetValue>("statecode").Value != 0)
            {
                service.Execute(new SetStateRequest
                {
                    EntityMoniker = wf.ToEntityReference(),
                    State = new OptionSetValue(0),
                    Status = new OptionSetValue(-1)
                });
            }

            workflow.Attributes.Remove("statecode");
            workflow.Attributes.Remove("statuscode");
            service.Update(workflow);

            if (wf.GetAttributeValue<OptionSetValue>("statecode").Value != 0)
            {
                service.Execute(new SetStateRequest
                {
                    EntityMoniker = wf.ToEntityReference(),
                    State = new OptionSetValue(1),
                    Status = new OptionSetValue(-1)
                });
            }
            return workflow.GetAttributeValue<int>("rank");
        }
예제 #7
0
        public LookupSingle(string entityName, IOrganizationService service)
        {
            InitializeComponent();

            this.entityName = entityName;
            this.service = service;
        }
예제 #8
0
 public AttributePicker(EntityMetadata emd, IEnumerable<string> alreadySelectedAttributes, IOrganizationService service)
 {
     this.emd = emd;
     this.alreadySelectedAttributes = alreadySelectedAttributes;
     this.service = service;
     InitializeComponent();
 }
예제 #9
0
        public static MsCrmResult AnswerSurvey(SurveyAnswer answer, IOrganizationService service)
        {
            MsCrmResult returnValue = new MsCrmResult();

            try
            {
                Entity ent = new Entity("new_surveyanswer");
                ent["new_name"] = answer.PortalUser.Name + "-" + DateTime.Now.ToString("dd.MM.yyyy HH:mm");
                ent["new_portalid"] = answer.Portal;
                ent["new_userid"] = answer.PortalUser;
                ent["new_surveyid"] = answer.Survey;
                ent["new_surveychoiceid"] = answer.SurveyChoice;

                returnValue.CrmId = service.Create(ent);

                returnValue.Success = true;
                returnValue.Result = "M053"; //"Anket cevabınız alınmıştır. <br /> Katılımınız için teşekkür ederiz.";

            }
            catch (Exception ex)
            {
                returnValue.Result = ex.Message;
            }
            return returnValue;
        }
예제 #10
0
 public ScheduleWF(IOrganizationService service, new_incidentservice target,
     new_incidentserviceparameter paramters,
     new_flightoccurrence orginalFlightOccurrence,
     IEmailTemplate iEmailTemplate)
     : base(service, target, paramters, orginalFlightOccurrence, iEmailTemplate)
 {
 }
예제 #11
0
        public void getSecurityRoleGuidBySecurityRoleName(IOrganizationService securityRoleCrmWebservice)
        {
            var myQuery = new QueryExpression
            {
                EntityName = "role",
                ColumnSet = new ColumnSet("roleid"),
                Criteria = new FilterExpression
                {
                    Conditions =
                    {
                        new ConditionExpression
                        {
                          AttributeName  =  "name",
                          Operator = ConditionOperator.Equal,
                          Values = {"roleName"}
                        }
                    }
                }
            };

            //DataCollection<Entity> securityRoleResult = CrmWebservice.RetrieveMultiple(myQuery).Entities;
            DataCollection<Entity> securityRoleResult = securityRoleCrmWebservice.RetrieveMultiple(myQuery).Entities;
            if (securityRoleResult.Count > 0)
                this.guidSecurityRoleId = (Guid)securityRoleResult[0]["roleid"];
        }
예제 #12
0
        /// <summary>
        /// Retrieve the list of views for a specific entity
        /// </summary>
        /// <param name="entityDisplayName">Logical name of the entity</param>
        /// <param name="entitiesCache">Entities cache</param>
        /// <param name="service">Organization Service</param>
        /// <returns>List of views</returns>
        public static List<Entity> RetrieveViews(string entityLogicalName, List<EntityMetadata> entitiesCache, IOrganizationService service)
        {
            try
            {
                EntityMetadata currentEmd = entitiesCache.Find(delegate(EntityMetadata emd) { return emd.LogicalName == entityLogicalName; });

                QueryByAttribute qba = new QueryByAttribute
                                           {
                                               EntityName = "savedquery",
                                               ColumnSet = new ColumnSet(true)
                                           };

                qba.Attributes.Add("returnedtypecode");
                qba.Values.Add(currentEmd.ObjectTypeCode.Value);

                EntityCollection views = service.RetrieveMultiple(qba);

                List<Entity> viewsList = new List<Entity>();

                foreach (Entity entity in views.Entities)
                {
                    viewsList.Add(entity);
                }

                return viewsList;
            }
            catch (Exception error)
            {
                string errorMessage = CrmExceptionHelper.GetErrorMessage(error, false);
                throw new Exception("Error while retrieving views: " + errorMessage);
            }
        }
 public OrgsByCategoryController(IOrganizationService organizationService, IWebSecurityService securityService, IEmailHelper emailHelper, IRegistrationService registrationService)
 {
     this.organizationService = organizationService;
     this.webSecurityService = securityService;
     this.emailHelper = emailHelper;
     this.registrationService = registrationService;
 }
        public void Import(ExcelWorksheet sheet, List<EntityMetadata> emds, IOrganizationService service)
        {
            var rmds = new List<OneToManyRelationshipMetadata>();

            foreach (var row in sheet.Rows.Where(r => r.Index != 0).OrderBy(r => r.Index))
            {
                var rmd = rmds.FirstOrDefault(r => r.MetadataId == new Guid(row.Cells[1].Value.ToString()));
                if (rmd == null)
                {
                    var currentEntity = emds.FirstOrDefault(e => e.LogicalName == row.Cells[0].Value.ToString());
                    if (currentEntity == null)
                    {
                        var request = new RetrieveEntityRequest
                        {
                            LogicalName = row.Cells[0].Value.ToString(),
                            EntityFilters = EntityFilters.Relationships
                        };

                        var response = ((RetrieveEntityResponse) service.Execute(request));
                        currentEntity = response.EntityMetadata;

                        emds.Add(currentEntity);
                    }

                    rmd =
                        currentEntity.OneToManyRelationships.FirstOrDefault(
                            r => r.SchemaName == row.Cells[2].Value.ToString());
                    if (rmd == null)
                    {
                        rmd =
                            currentEntity.ManyToOneRelationships.FirstOrDefault(
                                r => r.SchemaName == row.Cells[2].Value.ToString());
                    }

                    rmds.Add(rmd);
                }

                int columnIndex = 4;

                rmd.AssociatedMenuConfiguration.Label = new Label();

                while (row.Cells[columnIndex].Value != null)
                {
                    rmd.AssociatedMenuConfiguration.Label.LocalizedLabels.Add(
                        new LocalizedLabel(row.Cells[columnIndex].Value.ToString(),
                            int.Parse(sheet.Cells[0, columnIndex].Value.ToString())));

                    columnIndex++;
                }
            }

            foreach (var rmd in rmds)
            {
                var request = new UpdateRelationshipRequest
                {
                    Relationship = rmd,
                };
                service.Execute(request);
            }
        }
예제 #15
0
        public static IEnumerable<BusinessRules> RetrieveBusinessRules(IOrganizationService service)
        {
            var businessRules = service.RetrieveMultiple(new FetchExpression(@"
            <fetch>
                <entity name='workflow' >
                <attribute name='triggeroncreate' />
                <attribute name='createdon' />
                <attribute name='primaryentity' />
                <attribute name='triggerondelete' />
                <attribute name='triggeronupdateattributelist' />
                <attribute name='processorder' />
                <attribute name='modifiedon' />
                <attribute name='name' />
                <filter>
                    <condition attribute='type' operator='eq' value='1' />
                    <condition attribute='category' operator='eq' value='2' />
                </filter>
                </entity>
            </fetch>"));

            var q = from e in businessRules.Entities
                    orderby e.GetAttributeValue<string>("primaryentity"), e.GetAttributeValue<DateTime>("modifiedon")
                    select new BusinessRules(e);
            return q;
        }
예제 #16
0
        /// <summary>
        /// Retrieves main forms for the specified entity
        /// </summary>
        /// <param name="logicalName">Entity logical name</param>
        /// <param name="oService">Crm organization service</param>
        /// <returns>Document containing all forms definition</returns>
        public static IEnumerable<Entity> RetrieveEntityFormList(string logicalName, IOrganizationService oService)
        {
            var qe = new QueryExpression("systemform")
            {
                ColumnSet = new ColumnSet(true),
                Criteria = new FilterExpression
                {
                    Conditions =
                    {
                        new ConditionExpression("objecttypecode", ConditionOperator.Equal, logicalName),
                        new ConditionExpression("type", ConditionOperator.In, new[] {2,7}),
                    }
                }
            };

            try
            {
                return oService.RetrieveMultiple(qe).Entities;
            }
            catch
            {
                qe.Criteria.Conditions.RemoveAt(qe.Criteria.Conditions.Count - 1);
                return oService.RetrieveMultiple(qe).Entities;
            }
        }
예제 #17
0
        public void conUpdate(Microsoft.Crm.Sdk.Samples.ServerConnection.Configuration serverconfig, ArrayList data)
        {
            try
            {
                using (_serviceProxy = Microsoft.Crm.Sdk.Samples.ServerConnection.GetOrganizationProxy(serverconfig))
                {

                    String a_id = (String)data[0];
                    Guid _contactId = new Guid(a_id);
                    _serviceProxy.EnableProxyTypes();

                    _service = (IOrganizationService)_serviceProxy;

                    Contact contactToUpdate = new Contact
                    {
                        FirstName = (String)data[1],
                        EMailAddress1 = (String)data[2],
                        Address1_City = (String)data[3],
                        Address1_Country = (String)data[4],
                        Address1_Latitude = Convert.ToDouble(data[5]),
                        Address1_Longitude = Convert.ToDouble(data[6]),
                        ContactId = _contactId
                    };

                    _service.Update(contactToUpdate);

                }
            }
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                throw;
            }
        }
예제 #18
0
        public void Import(ExcelWorksheet sheet, IOrganizationService service)
        {
            var rowsCount = sheet.Dimension.Rows;

            for (var rowI = 1; rowI < rowsCount; rowI++)
            {
                var xml = new StringBuilder(string.Format("<LocLabel Id=\"{0}\"><Titles>", ZeroBasedSheet.Cell(sheet, rowI, 2).Value));

                var columnIndex = 3;

                while (ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value != null)
                {
                    xml.Append(string.Format("<Title description=\"{0}\" languagecode=\"{1}\"/>",
                                             ZeroBasedSheet.Cell(sheet, rowI, columnIndex).Value,
                                             int.Parse(ZeroBasedSheet.Cell(sheet, 0, columnIndex).Value.ToString())));

                    columnIndex++;
                }

                xml.Append("</Titles></LocLabel>");

                var ribbonDiff = new Entity("ribbondiff") { Id = new Guid(ZeroBasedSheet.Cell(sheet, rowI, 0).Value.ToString()) };
                ribbonDiff["rdx"] = xml.ToString();

                service.Update(ribbonDiff);
            }
        }
예제 #19
0
 internal XrmService(IOrganizationService actualService, LogController uiController)
 {
     _service = actualService;
     Controller = uiController;
     if (Controller == null)
         Controller = new LogController();
 }
예제 #20
0
        public bool connect(string serviceURL, string domainName, string userName, string password)
        {
            try
            {

                Uri organizationUri = new Uri(serviceURL);
                Uri homeRealmUri = null;
                ClientCredentials credentials = new ClientCredentials();
                // set default credentials for OrganizationService
                credentials.Windows.ClientCredential = new NetworkCredential(userName, password, domainName);
                // credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
                OrganizationServiceProxy orgProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);
                _service = (IOrganizationService)orgProxy;

                //to check connection with CRM
                getAttributeMax("campaign", "exchangerate");

                return true;
            }
            catch (InvalidOperationException)
            {
                throw new connectionException("The URI provided cannot be resolved ( " + serviceURL + " )");
            }
            catch (SecurityNegotiationException)
            {
                throw new connectionException("The authentication failed ! Please check the credentials provided.");
            }
            catch (Exception ex)
            {
                throw new connectionException(ex.Message);
            }
        }
예제 #21
0
        public CrmSystemViewList(IOrganizationService service, string entityName)
        {
            this.service = service;
            this.entityName = entityName;

            InitializeComponent();
        }
예제 #22
0
        public AreaControl(Dictionary<string, string> collection, List<Entity> webResourcesImageCache, List<Entity> webResourcesHtmlCache, IOrganizationService service)
            : this(webResourcesImageCache, webResourcesHtmlCache, service)
        {
            collec = collection;

            FillControls();
        }
예제 #23
0
        private void PurchaseDealUpdateMethod(new_aprove_price _proxyentity, List<new_port> _portList, OrganizationServiceContext orgContext, IOrganizationService service)
        {
            List<new_purchase_deal> _cdealListForUpdate = (from i in orgContext.CreateQuery<new_purchase_deal>()
                                                           where i.new_cropid.Id == _proxyentity.new_cropid.Id &&
                                                           (i.new_purchase_deal_stage == new OptionSetValue(100000000) ||
                                                           i.new_purchase_deal_stage == new OptionSetValue(100000002) ||
                                                           i.new_purchase_deal_stage == new OptionSetValue(100000001)) &&
                                                           i.new_opportunity_status == new OptionSetValue(100000000)
                                                           select i).ToList();

            foreach ( var item in _cdealListForUpdate )
            {
                new_purchase_deal _updateDeal = new new_purchase_deal();
                _updateDeal.Id = item.Id;
                if ( item.new_ship_portid == null )
                    continue;
                if ( _portList.Where(x => x.Id == item.new_ship_portid.Id)?.FirstOrDefault()?.new_name == "Одеса" )
                {
                    _updateDeal.new_recommended_price = _proxyentity.new_recom_purchase_price_odessa;
                }
                else if ( _portList.Where(x => x.Id == item.new_ship_portid.Id)?.FirstOrDefault()?.new_name == "Миколаїв" )
                {
                    _updateDeal.new_recommended_price = _proxyentity.new_recom_purchase_price_nikolaev;
                }
                service.Update(_updateDeal);
            }
        }
예제 #24
0
        public static void Main(IOrganizationService service)
        {
            ///Retreive all input varables.
            string Type = "QTE";
            string Event = "Quote Action";
            string Phase = "";
            string ChangeReason = "";
            string entityName = "h21_revenueorder";
            string UserId = "2FEC9AF5-698F-E311-93F5-00155D01173F";
            int LogicBased = 1;

            try
            {
                if (LogicBased == 0)
                {
                    string query = generateFetchForUser(UserId, entityName, Event, Type, Phase, ChangeReason);
                    retrievePermision(service, query);
                }
                else
                {
                    if (TeamMasterLogicMethod(service, Guid.Parse(UserId)))
                        return;
                    TeamLogic(service, Guid.Parse(UserId), entityName, Event, Type, Phase, ChangeReason);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
 public VolunteerFormController(IVolunteerFormService volunteers, IOrganizationService organizations, IAdopterService adopters, ISanitizer sanitizeService)
 {
     this.volunteers = volunteers;
     this.organizations = organizations;
     this.adopters = adopters;
     this.sanitizeService = sanitizeService;
 }
예제 #26
0
        public SubAreaControl(List<EntityMetadata> emds, List<Entity> imageCache, List<Entity> htmlCache, IOrganizationService service)
        {
            InitializeComponent();

            this.emds = emds;
            this.imageCache = imageCache;
            this.htmlCache = htmlCache;
            this.service = service;

            collec = new Dictionary<string, string>();

            tip = new ToolTip();
            tip.ToolTipTitle = "Information";
            tip.SetToolTip(chkSubAreaAvailableOffline, "Controls whether SubArea is available offline.");
            tip.SetToolTip(chkSubAreaPassParams, "Specifies whether information about the organization and language context are passed to the URL.");
            tip.SetToolTip(txtOutlookShortcutIcon, "Specifies the icon to display in Microsoft Dynamics CRM for Microsoft Office Outlook.");
            tip.SetToolTip(txtSubAreaEntity, "Specifies the name for the entity. If a Url is not specified, the default view of the specified entity will be displayed.");
            tip.SetToolTip(txtSubAreaGetStartedPanePath, "Specifies the path to the Get Started page for this subarea.");
            tip.SetToolTip(txtSubAreaGetStartedPanePathAdmin, "Specifies the path to the Get Started page for this subarea if the user is logged in as an administrator.");
            tip.SetToolTip(txtSubAreaGetStartedPanePathAdminOutlook, "Specifies the path to the Get Started page for this subarea if the user is logged in as an administrator and Microsoft Dynamics CRM for Outlook is in use.");
            tip.SetToolTip(txtSubAreaGetStartedPanePathOutlook, "Specifies the path to the Get Started page for this subarea when Microsoft Dynamics CRM for Outlook is in use.");
            tip.SetToolTip(txtSubAreaIcon, "Specifies a URL for an 18x18 pixel image to display for the SubArea.");
            tip.SetToolTip(txtSubAreaId, "A unique identifier for this SubArea element.\r\n\r\nValid values: a-z, A-Z, 0-9, and underscore (_)");
            tip.SetToolTip(txtSubAreaUrl, "Specifies a URL or HTML Web Resource for a page to display in the main frame of the application when this subarea is selected.");
            tip.SetToolTip(txtSubAreaTitle, "Deprecated. Use the <Titles> (SiteMap) and <Title> (SiteMap) elements.");
            tip.SetToolTip(txtSubAreaDescription, "Deprecated. Use the <Description> (SiteMap) element.");
            tip.SetToolTip(txtDefaultDashboardId, "This functionality is introduced in Microsoft Dynamics CRM 2013 and the Microsoft Dynamics CRM Online Fall '13 Service Update. \r\nSpecifies the GUID for default dashboard to be displayed for this subarea.");
        }
예제 #27
0
        public PublisherSelector(IOrganizationService service, string selectedPrefixes)
        {
            InitializeComponent();

            this.service = service;
            this.SelectedPrefixes = selectedPrefixes.Split(';').ToList();
        }
예제 #28
0
        public static void ApplyImagesToEntities(List<EntityImageMap> mappings, IOrganizationService service)
        {
            foreach (var mapping in mappings)
            {
                if (mapping.ImageSize == 16)
                {
                    mapping.Entity.IconSmallName = mapping.WebResourceName;
                }
                else
                {
                    mapping.Entity.IconMediumName = mapping.WebResourceName;
                }

                var request = new UpdateEntityRequest { Entity = mapping.Entity };
                service.Execute(request);
            }

            string parameter = mappings.Aggregate(string.Empty, (current, mapping) => current + ("<entity>" + mapping.Entity.LogicalName + "</entity>"));

            string parameterXml = string.Format("<importexportxml ><entities>{0}</entities></importexportxml>",
                                                parameter);

            var publishRequest = new PublishXmlRequest { ParameterXml = parameterXml };
            service.Execute(publishRequest);
        }
예제 #29
0
 public static AttributeMetadata GetAttribute(IOrganizationService service, string entity, string attribute)
 {
     // TODO: If AliasedValue, look up actual entity and attribute name to return correct metadata
     if (!entities.ContainsKey(entity))
     {
         var response = LoadEntityDetails(service, entity);
         if (response != null && response.EntityMetadata != null && response.EntityMetadata.Count == 1 && response.EntityMetadata[0].LogicalName == entity)
         {
             entities.Add(entity, response.EntityMetadata[0]);
         }
     }
     if (entities != null && entities.ContainsKey(entity))
     {
         if (entities[entity].Attributes != null)
         {
             foreach (var metaattribute in entities[entity].Attributes)
             {
                 if (metaattribute.LogicalName == attribute)
                 {
                     return metaattribute;
                 }
             }
         }
     }
     return null;
 }
예제 #30
0
        private static string ComputeMainClientID(string AccountName, IOrganizationService orgservice)
        {
            var result = new StringBuilder();
            var counter = 1;
            var maxClientIdLength = 35;

            //Change string to all lowercase
            AccountName = AccountName.ToLower();

            //Cycle through the string and remove all non alpha-numeric characters
            for (int i = 0; i <= AccountName.Length - 1; i++)
            {
                var c = AccountName[i];
                if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
                    result.Append(c);
            }

            //Make sure the string is between 2 and maxClientIdLength characters long, If it is over maxClientIdLength truncate it and if it is below 2 add padding
            if (result.Length > maxClientIdLength)
                result = result.Remove(maxClientIdLength, result.Length - maxClientIdLength);
            else if (result.Length < 2)
                result.Append("_");

            //Check existing accounts to make sure that the string is currently not already used in ergo_clientid
            //We append an incremental digit to the end of the string until we find a suitable clientid
            while(isDuplicate(result.ToString(), orgservice))
            {
                if (counter != 1 | result.Length + counter.ToString().Length > maxClientIdLength) 
                    result.Length = result.Length - counter.ToString().Length;
                result.Append(counter);
                counter++;
            }

            return result.ToString();
        }
예제 #31
0
        public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
        {
            RemoveUserFromRecordTeamRequest remReq = (RemoveUserFromRecordTeamRequest)request;

            EntityReference target         = remReq.Record;
            Guid            systemuserId   = remReq.SystemUserId;
            Guid            teamTemplateId = remReq.TeamTemplateId;

            if (target == null)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "Can not remove from team without target");
            }

            if (systemuserId == Guid.Empty)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "Can not remove from team without user");
            }

            if (teamTemplateId == Guid.Empty)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "Can not remove from team without team");
            }

            Entity teamTemplate = ctx.CreateQuery("teamtemplate").FirstOrDefault(p => p.Id == teamTemplateId);

            if (teamTemplate == null)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "Team template with id=" + teamTemplateId + " does not exist");
            }

            Entity user = ctx.CreateQuery("systemuser").FirstOrDefault(p => p.Id == systemuserId);

            if (user == null)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "User with id=" + teamTemplateId + " does not exist");
            }

            IOrganizationService service = ctx.GetOrganizationService();

            ctx.AccessRightsRepository.RevokeAccessTo(target, user.ToEntityReference());
            Entity team = ctx.CreateQuery("team").FirstOrDefault(p => ((EntityReference)p["teamtemplateid"]).Id == teamTemplateId);

            if (team == null)
            {
                return(new RemoveUserFromRecordTeamResponse
                {
                    ResponseName = "RemoveUserFromRecordTeam"
                });
            }

            Entity tm = ctx.CreateQuery("teammembership").FirstOrDefault(p => (Guid)p["teamid"] == team.Id);

            if (tm != null)
            {
                service.Delete(tm.LogicalName, tm.Id);
            }

            return(new RemoveUserFromRecordTeamResponse
            {
                ResponseName = "RemoveUserFromRecordTeam"
            });
        }
예제 #32
0
 public Policy(IOrganizationService svc, ITracingService tracingSvc, Entity entity)
     : base(svc, tracingSvc, entity)
 {
 }
        /// <summary>
        /// Assigns the provider to service request.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="objectIncident">The object incident.</param>
        private void AssignProviderToServiceRequest(IOrganizationService service, Entity objectIncident, ITracingService trace)
        {
            try
            {
                ////Check if building, roomtype, floor, problem class and problem type is not null. To be added, floor
                if (objectIncident.Attributes.Contains(CRMAttributesResource.ProblemBuildingIdAttribute) && objectIncident.Attributes.Contains(CRMAttributesResource.ProblemClassIdAttribute) && objectIncident.Attributes.Contains(CRMAttributesResource.ProblemTypeIdAttribute))
                {
                    ConditionExpression condBuilding = new ConditionExpression
                    {
                        AttributeName = CRMAttributesResource.BuildingIdAttribute,
                        Operator      = ConditionOperator.Equal,
                        Values        = { ((EntityReference)objectIncident.Attributes[CRMAttributesResource.ProblemBuildingIdAttribute]).Id }
                    };
                    ConditionExpression condProblemClass = new ConditionExpression
                    {
                        AttributeName = CRMAttributesResource.ProblemClassIdAttribute,
                        Operator      = ConditionOperator.Equal,
                        Values        = { ((EntityReference)objectIncident.Attributes[CRMAttributesResource.ProblemClassIdAttribute]).Id }
                    };
                    ConditionExpression condProblemType = new ConditionExpression
                    {
                        AttributeName = CRMAttributesResource.ProblemTypeIdAttribute,
                        Operator      = ConditionOperator.Equal,
                        Values        = { ((EntityReference)objectIncident.Attributes[CRMAttributesResource.ProblemTypeIdAttribute]).Id }
                    };
                    ConditionExpression condStatus = new ConditionExpression
                    {
                        AttributeName = "statuscode",
                        Operator      = ConditionOperator.Equal,
                        Values        = { 1 }
                    };
                    QueryExpression providerMatrixQuery = new QueryExpression
                    {
                        EntityName = CRMAttributesResource.ProviderMatrixEntity,
                        ColumnSet  = new ColumnSet(CRMAttributesResource.PrimaryProviderIdAttribute, CRMAttributesResource.ProviderMatrixIsApprovalRequired, CRMAttributesResource.ProviderMatrixIOCode),
                        Criteria   =
                        {
                            FilterOperator = LogicalOperator.And,
                            Conditions     = { condBuilding,     condProblemClass,condProblemType, condStatus }
                        }
                    };
                    if (service != null)
                    {
                        EntityCollection provider_Matrix = service.RetrieveMultiple(providerMatrixQuery);
                        ////Entity providerMatrix = service.RetrieveMultiple(providerMatrixQuery) == null ? null : service.RetrieveMultiple(providerMatrixQuery).Entities.FirstOrDefault();
                        Entity providerMatrix = provider_Matrix.Entities.FirstOrDefault();
                        if (providerMatrix != null)
                        {
                            if (providerMatrix.Attributes.Contains(CRMAttributesResource.PrimaryProviderIdAttribute))
                            {
                                bool   approvalRequired = false;
                                string io_Code          = string.Empty;
                                if (this.ProviderIsActive(((EntityReference)providerMatrix.Attributes[CRMAttributesResource.PrimaryProviderIdAttribute]).Id, service))
                                {
                                    if (providerMatrix.Attributes.Contains(CRMAttributesResource.ProviderMatrixIsApprovalRequired))
                                    {
                                        approvalRequired = Convert.ToBoolean(providerMatrix.Attributes[CRMAttributesResource.ProviderMatrixIsApprovalRequired], CultureInfo.CurrentCulture);
                                    }
                                    else
                                    {
                                        approvalRequired = false;
                                    }

                                    if (objectIncident.Attributes.Contains(CRMAttributesResource.IoCode) == false || string.IsNullOrEmpty(Convert.ToString(objectIncident.Attributes[CRMAttributesResource.IoCode], CultureInfo.InvariantCulture)))
                                    {
                                        if (providerMatrix.Attributes.Contains(CRMAttributesResource.ProviderMatrixIOCode))
                                        {
                                            io_Code = Convert.ToString(providerMatrix.Attributes[CRMAttributesResource.ProviderMatrixIOCode], CultureInfo.InvariantCulture);
                                        }
                                        else
                                        {
                                            io_Code = string.Empty;
                                        }
                                    }

                                    this.AssignProvider(((EntityReference)providerMatrix.Attributes[CRMAttributesResource.PrimaryProviderIdAttribute]).Id, service, objectIncident, approvalRequired, io_Code, trace);
                                }
                            }
                            else
                            {
                                trace.Trace("In Default Provider as No primary Provider matrix is Found");
                                this.SetDefaultProvider(service, objectIncident);
                            }
                        }
                        else
                        {
                            trace.Trace("In Default Provider as not Provider matrix is Found");
                            this.SetDefaultProvider(service, objectIncident);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new CustomServiceManagementPortalException("Failed to assign provider with the service request on Pre Create.", ex);
            }
        }
예제 #34
0
        public void Execute(IServiceProvider serviceProvider)
        {
            //Extract the tracing service for use in debugging sandboxed plug-ins.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));

            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);


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

                if (incident.Attributes.Contains("description"))
                {
                    incident.Attributes["description"] = "Sample description";
                }
                else

                {
                    incident.Attributes.Add("description", "Sample description");
                }



                // Creating Entity Object for Task

                Entity task = new Entity();
                task.LogicalName = "task";
                // String
                task.Attributes.Add("subject", "Follow up with customer");
                task.Attributes.Add("description", "Arrange a meeting with customer");

                // Optionset
                // 0 = Low, 1 = Normal, 2 = High
                task.Attributes.Add("prioritycode", new OptionSetValue(2));

                // Lookup
                task.Attributes.Add("regardingobjectid",
                                    new EntityReference("incident", incident.Id));

                // Datetime
                task.Attributes.Add("scheduledend", DateTime.Now.AddDays(3));

                // Two Options
                // task.Attributes.Add("somefield", true);

                // Currency
                //task.Attributes.Add("somefield", new Money(1300));

                AddRequest addRequest = new AddRequest();
                addRequest.intA = 100;
                addRequest.intB = 200;



                service.Create(task);
            }
        }
예제 #35
0
 public QuoteCabChassisHandler(IOrganizationService service, ITracingService trace)
 {
     _organizationService = service;
     _tracingService      = trace;
 }
 public void SetService(IOrganizationService newService)
 {
     service = newService;
 }
 public RecordManager(IOrganizationService service)
 {
     this.service        = service;
     logger              = new LogManager(GetType());
     recordsToDeactivate = new List <EntityReference>();
 }
예제 #38
0
 public OrganizationController(AIMSDbContext cntxt, IOrganizationService service)
 {
     this.context             = cntxt;
     this.organizationService = service;
 }
예제 #39
0
 public DeployPluginsTask(IOrganizationService service, ITrace trace) : base(service, trace)
 {
 }
 /// <summary>
 /// Assigns the provider.
 /// </summary>
 /// <param name="primaryProviderId">The primary provider id.</param>
 /// <param name="service">The service.</param>
 /// <param name="objectIncident">The object incident.</param>
 /// <param name="isApprovalRequired">if set to <c>true</c> [is approval required].</param>
 /// <param name="io_Code">The ioCode</param>
 private void AssignProvider(Guid primaryProviderId, IOrganizationService service, Entity objectIncident, bool isApprovalRequired, string io_Code, ITracingService trace)
 {
     this.SetProvider(primaryProviderId, service, objectIncident, isApprovalRequired, io_Code, trace);
 }
예제 #41
0
 public LoadDocParametersFactory(IOrganizationService service, Entity target, string subject)
 {
     _target  = target;
     _service = service;
     _subject = subject;
 }
        public void Execute(IServiceProvider serviceProvider)
        {
            CCRM.REF.TelemetryLog.LocalPluginContext localPluginContext = new CCRM.REF.TelemetryLog.LocalPluginContext(serviceProvider);
            IConfigurationRetrieval configurationRetrieval = new ConfigurationRetrieval();

            this.requestLogging = new RequestLogging(configurationRetrieval, localPluginContext);
            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));
            ITracingService trace =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            if (context != null && context.InputParameters["Target"] != null)
            {
                var serRequest = (Entity)context.InputParameters["Target"];

                if (service != null && serRequest != null)
                {
                    bool statusCode     = serRequest.Attributes.Contains(CRMAttributesResource.StatusCodeAttribute) ? true : false;
                    int  caseorigincode = ((OptionSetValue)serRequest["caseorigincode"]).Value;
                    try
                    {
                        if (statusCode)
                        {
                            bool smp_portalsubmit = (bool)serRequest["smp_portalsubmit"];
                            if ((caseorigincode == (int)ServiceRequestEnum.ServiceRequestOrigin.Web || caseorigincode == (int)ServiceRequestEnum.ServiceRequestOrigin.IOT || caseorigincode == (int)ServiceRequestEnum.ServiceRequestOrigin.Phone) && ((OptionSetValue)serRequest.Attributes[CRMAttributesResource.StatusCodeAttribute]).Value == (int)ServiceRequestEnum.StatusCode.Draft)
                            {
                                object smp_contact = this.GetFieldFromTargetOrImage(serRequest, "smp_contact");
                                if (smp_contact != null)
                                {
                                    object smp_requestorid = this.GetFieldFromTargetOrImage(serRequest, "smp_requestorid");
                                    if (smp_requestorid != null)
                                    {
                                        Entity requestor = this.GetRequestorDetails(service, ((EntityReference)smp_requestorid).Id, trace);
                                        if (requestor != null)
                                        {
                                            if (!serRequest.Attributes.Contains("smp_requestorphone"))
                                            {
                                                if (requestor.Attributes.Contains("telephone1"))
                                                {
                                                    serRequest["smp_requestorphone"] = requestor["telephone1"].ToString();
                                                }
                                                else if (caseorigincode == (int)ServiceRequestEnum.ServiceRequestOrigin.Web)
                                                {
                                                    serRequest["smp_requestorphone"] = "<None>";
                                                }
                                            }

                                            serRequest["smp_requestoralias"]      = this.GetFieldFromTargetOrImage(requestor, "smp_alias");
                                            serRequest["smp_requestoremail"]      = this.GetFieldFromTargetOrImage(requestor, "emailaddress1");
                                            serRequest["smp_buildingid"]          = this.GetFieldFromTargetOrImage(requestor, "smp_buildingid");
                                            serRequest["new_requestorroomnumber"] = this.GetFieldFromTargetOrImage(requestor, "new_requestorroomnumber");
                                        }
                                    }

                                    EntityReference otherRef   = this.GetRoomWithOther(service, trace);
                                    EntityReference problemRef = serRequest.Attributes.ContainsKey("new_problemroomnumber") ?
                                                                 (EntityReference)serRequest["new_problemroomnumber"] : null;
                                    if (problemRef != null)
                                    {
                                        problemRef.Name = this.GetRoomName(service, problemRef.Id);
                                    }

                                    if (problemRef == null)
                                    {
                                        serRequest["new_problemroomnumber"] = otherRef;
                                    }
                                    else if (problemRef.Id != otherRef.Id)
                                    {
                                        serRequest["smp_problemroom"] = problemRef.Name;
                                    }
                                    else
                                    {
                                        trace.Trace("Problem room lookup is Other, doing nothing");
                                    }

                                    if (serRequest.Attributes.Contains("smp_problembuilding"))
                                    {
                                        Entity building = this.GetBuildingDetails(service, ((EntityReference)serRequest["smp_problembuilding"]).Id, trace);
                                        if (building != null)
                                        {
                                            serRequest["smp_problembuildingaddressline1"] = this.GetFieldFromTargetOrImage(building, "smp_addressline1");
                                            serRequest["smp_problembuildingaddressline2"] = this.GetFieldFromTargetOrImage(building, "smp_addressline2");
                                            serRequest["smp_problembuildingstate"]        = this.GetFieldFromTargetOrImage(building, "smp_state");
                                            serRequest["smp_problembuildingcountry"]      = this.GetFieldFromTargetOrImage(building, "smp_country");
                                            serRequest["smp_problembuildingcity"]         = this.GetFieldFromTargetOrImage(building, "smp_city");
                                            serRequest["smp_problembuildingzipcode"]      = this.GetFieldFromTargetOrImage(building, "smp_zipcode");
                                            serRequest["smp_problembuildingtimezone"]     = this.GetFieldFromTargetOrImage(building, "smp_timezoneid");
                                        }
                                    }

                                    if (smp_portalsubmit == true)
                                    {
                                        serRequest["statuscode"] = new OptionSetValue(2);
                                        this.AssignProviderToServiceRequest(service, serRequest, trace);
                                    }
                                    else
                                    {
                                        //// Code to set the Default Provider When SR is Saved as Draft from Portal.
                                        this.AssignProviderToServiceRequest(service, serRequest, trace);
                                    }

                                    ServiceRequestHelper.SetIntegrationStatusandProblemOccuredDateTime(serRequest, false);
                                }
                            }
                            else
                            {
                                trace.Trace("in CRM");
                                string          roomName   = string.Empty;
                                EntityReference problemRef = serRequest.Attributes.ContainsKey("new_problemroomnumber") ?
                                                             (EntityReference)serRequest["new_problemroomnumber"] : null;
                                if (problemRef != null)
                                {
                                    roomName = this.GetRoomName(service, problemRef.Id);
                                }
                                else
                                {
                                    serRequest["new_problemroomnumber"] = this.GetRoomWithOther(service, trace);
                                    serRequest["smp_problemroom"]       = serRequest.Attributes.Contains("smp_problemroom") ? serRequest["smp_problemroom"].ToString() : string.Empty;
                                }

                                if (roomName != "Other" && !string.IsNullOrEmpty(roomName))
                                {
                                    serRequest["smp_problemroom"] = roomName;
                                }

                                this.AssignProviderToServiceRequest(service, serRequest, trace);
                                serRequest["smp_integrationstatus"] = false;
                            }
                        }

                        ////this.requestLogging.LogPluginTrace(serRequest, MappingConstants.ServiceRequestCreatedSequenceId, MappingConstants.ServiceRequestCreatedSuccessEventId, MappingConstants.ServiceRequestCreatedEventName, MappingConstants.ServiceRequestCreatedSuccessEventMessage);
                    }
                    catch (CustomServiceManagementPortalException ex)
                    {
                        ////this.requestLogging.LogPluginException(serRequest, ex, MappingConstants.ServiceRequestCreatedSequenceId, MappingConstants.ServiceRequestCreatedFailedEventId, MappingConstants.ServiceRequestCreatedEventName, MappingConstants.ServiceRequestCreatedFailedEventMessage);
                        ////Kill the exception so it does not effect other plugin execution
                    }
                }
            }
        }
예제 #43
0
 public static bool CheckEstimatedEscrowUnclosedDate(OptionSetValue paymentOption, EntityReference mainOpportunity, DateTime?estimatedCloseDate, IOrganizationService service)
 {
     if (paymentOption?.Value == AppSettings.optionValueHypothec && estimatedCloseDate.HasValue)
     {
         TimeSpan calculateRemainder = estimatedCloseDate.Value - DateTime.Now;
         if (calculateRemainder.Days >= 2 && calculateRemainder.Days <= 4 && mainOpportunity != null && !EscrowDateHasValue(service, mainOpportunity))
         {
             return(true);
         }
     }
     return(false);
 }
예제 #44
0
 public OrderParametersFactory(IOrganizationService service, Entity target, string subject) : base(service, target, subject)
 {
 }
예제 #45
0
        private void GetInterestedUsers(Entity entity, IOrganizationService org, HashSet <Guid> processedEntities, HashSet <EntityReference> userIds, Dictionary <Guid, Link> entityRelationships)
        {
            if (!processedEntities.Add(entity.Id))
            {
                return;
            }

            // Add any user explicitly linked to from the parent record
            // Include owner, exclude createdby and modifiedby as they can set to workflow owners who aren't interested
            // in specific records
            foreach (var attribute in entity.Attributes)
            {
                if (attribute.Key == "createdby" || attribute.Key == "modifiedby")
                {
                    continue;
                }

                var userRef = attribute.Value as EntityReference;

                if (userRef != null && (userRef.LogicalName == "systemuser" || userRef.LogicalName == "team"))
                {
                    if (userIds.Add(userRef))
                    {
                        entityRelationships.Add(userRef.Id, new Link {
                            From = entity.ToEntityReference(), Description = GetEntityMetadata(org, entity.LogicalName).Attributes.Single(a => a.LogicalName == attribute.Key).DisplayName.UserLocalizedLabel.Label
                        });
                    }
                }
            }

            // Add any user who follows the parent record.
            var entityFollowsQry = new QueryByAttribute("postfollow");

            entityFollowsQry.AddAttributeValue("regardingobjectid", entity.Id);
            entityFollowsQry.ColumnSet = new ColumnSet("ownerid");

            foreach (var entityFollow in org.RetrieveMultiple(entityFollowsQry).Entities)
            {
                var userRef = entityFollow.GetAttributeValue <EntityReference>("ownerid");

                if (userIds.Add(userRef))
                {
                    entityRelationships.Add(userRef.Id, new Link {
                        From = entity.ToEntityReference(), Description = "Followed By"
                    });
                }
            }

            // Recurse into any accounts linked to this record
            var accountIds = new HashSet <Guid>();

            foreach (var attribute in entity.Attributes)
            {
                var accountRef = attribute.Value as EntityReference;

                if (accountRef != null && accountRef.LogicalName == "account" && !processedEntities.Contains(accountRef.Id))
                {
                    accountIds.Add(accountRef.Id);

                    if (!entityRelationships.ContainsKey(accountRef.Id))
                    {
                        entityRelationships.Add(accountRef.Id, new Link {
                            From = entity.ToEntityReference(), Description = GetEntityMetadata(org, entity.LogicalName).Attributes.Single(a => a.LogicalName == attribute.Key).DisplayName.UserLocalizedLabel.Label
                        });
                    }
                }
            }

            foreach (var accountId in accountIds)
            {
                var account = org.Retrieve("account", accountId, new ColumnSet("ownerid"));

                // Recurse into the account
                GetInterestedUsers(account, org, processedEntities, userIds, entityRelationships);
            }
        }
예제 #46
0
 public static bool CheckDelayEscrowDate(EntityReference mainOpportunity, DateTime?estimatedCloseDate, IOrganizationService service)
 {
     if (mainOpportunity != null && estimatedCloseDate.HasValue)
     {
         TimeSpan calculateRemainder = estimatedCloseDate.Value - DateTime.Now;
         if (calculateRemainder.Days <= 1 && mainOpportunity != null && !EscrowDateHasValue(service, mainOpportunity))
         {
             return(true);
         }
     }
     return(false);
 }
예제 #47
0
        private void SendEmail(List <ProxyToSendEmailExtended> listSales, IOrganizationService service, byte whatDay)
        {
            var Agreements = getAgreements();

            foreach (var item in Agreements)
            {
                Email mail = new Email();

                mail.Subject = "Просьба согласовать Договор либо внести комментарии";

                string link = string.Empty;

                var current = from p in listSales
                              where Equals(p.agreementLaw, item) ||
                              Equals(p.agreementLog, item) ||
                              Equals(p.agreementFin, item) ||
                              Equals(p.agreementAc, item) ||
                              Equals(p.agreementSd, item)
                              select p;

                if (current.Count() == 0)
                {
                    continue;
                }

                foreach (var colection in current)
                {
                    link += string.Format("<p class='MsoNormal'><i><u><span lang='RU' style='color:rgb(0,112,192)'>" +

                                          /*"<a href=https://ukraine.crm.softlinegroup.com/main.aspx?etc=SalesOrder&extraqs=%3f_gridType%3d4212%26etc%3d4212%26id%3d%257b{0}" +
                                           *  "%257d%26preloadcache%3d1406639059288%26rskey%3d307497509&histKey=417657088&newWindow=true&pagetype=entityrecord>{1}</a></span></u></i></p>",*/
                                          "<a href=https://ukraine.crm.softlinegroup.com/main.aspx?etn=SalesOrder&pagetype=entityrecord&id=%7b{0}%7d>{1}</a></span></u></i></p>",
                                          colection.recordId.ToString(), colection.Name.ToString());
                }

                switch (whatDay)
                {
                case 0:
                    mail.Description = string.Format(@"<div id=':3ua' class='Am Al editable LW-avf' hidefocus='true' aria-label='Текст'
g_editable='true' role='textbox' contenteditable='true' tabindex='1' itacorner='6,7:1,1,0,0' style='direction: ltr; min-height: 236px;'>
<p class='MsoNormal'><span lang='RU'>Уважаемый коллега, срок согласования договора(ов) истекает завтра. Просьба согласовать Договор либо внести комментарии.</span><o:p></o:p></p>          
<p class='MsoNormal'><i><u><span lang='RU' style='color: rgb(0, 112, 192);'>{0}</span></u></i></p>
                                                            <br></div>", link.ToString());
                    break;

                case 1:
                    mail.Description = string.Format(@"<div id=':3ua' class='Am Al editable LW-avf' hidefocus='true' aria-label='Текст' 
g_editable='true' role='textbox' contenteditable='true' tabindex='1' itacorner='6,7:1,1,0,0' style='direction: ltr; min-height: 236px;'>
<p class='MsoNormal'><span lang='RU'>Уважаемый коллега, срок согласования договора(ов) истекает сегодня. Просьба согласовать Договор либо внести комментарии.</span><o:p></o:p></p>          
<p class='MsoNormal'><i><u><span lang='RU' style='color: rgb(0, 112, 192);'>{0}</span></u></i></p>
                                                            <br></div>", link.ToString());
                    break;
                }

                mail.DirectionCode = true;
                SystemUser user = (SystemUser)service.Retrieve(SystemUser.EntityLogicalName, item.Id, new ColumnSet("fullname", "internalemailaddress"));


                if (user.InternalEMailAddress == null)
                {
                    continue;
                }

                var activityParty1 = new ActivityParty
                {
                    AddressUsed = user.InternalEMailAddress
                };

                var activityParty2 = new ActivityParty
                {
                    PartyId = new EntityReference(SystemUser.EntityLogicalName,
                                                  new Guid("C49FE2C3-FB35-E511-80D7-005056820ECA")),
                };

                mail.From = new[] { activityParty2 };
                mail.To   = new[] { activityParty1 };

                Guid createdEmailId = service.Create(mail);

                var sendEmailreq = new SendEmailRequest
                {
                    EmailId       = createdEmailId,
                    TrackingToken = "",
                    IssueSend     = true
                };
                try
                {
                    service.Execute(sendEmailreq);
                }
                catch (Exception)
                {
                }
            }
        }
예제 #48
0
        public static bool EscrowDateHasValue(IOrganizationService service, EntityReference mainOpportunity)
        {
            Entity opportunity = service.Retrieve("opportunity", mainOpportunity.Id, new ColumnSet("mtr_escrowdate"));

            return(opportunity.GetAttributeValue <DateTime?>("mtr_escrowdate").HasValue);
        }
예제 #49
0
 public RecordManager(IOrganizationService service)
 {
     this.service = service;
     logger       = new LogManager(GetType());
 }
예제 #50
0
        private static Entity GetFullPostText(IOrganizationService org, EntityReference entityRef, Entity post,
                                              ref Entity postComment)
        {
            // Retrieve the full wall for this record to expand out any standard posts
            var wallPage = 1;

            while (true)
            {
                var wall = (RetrieveRecordWallResponse)org.Execute(new RetrieveRecordWallRequest
                {
                    Entity          = entityRef,
                    CommentsPerPost = 10,
                    PageSize        = 10,
                    PageNumber      = wallPage,
                    Source          = post.GetAttributeValue <OptionSetValue>("source")
                });

                var foundPost = false;

                foreach (var wallPost in wall.EntityCollection.Entities)
                {
                    if (wallPost.Id == post.Id)
                    {
                        if (post == postComment)
                        {
                            postComment = wallPost;
                        }

                        post      = wallPost;
                        foundPost = true;
                        break;
                    }
                }

                if (foundPost || !wall.EntityCollection.MoreRecords)
                {
                    break;
                }

                wallPage++;
            }

            if (postComment == post)
            {
                postComment = post;
            }
            else
            {
                EntityCollection comments;
                if (post.RelatedEntities.TryGetValue(new Relationship("Post_Comments"), out comments))
                {
                    foreach (var wallComment in comments.Entities)
                    {
                        if (wallComment.Id == postComment.Id)
                        {
                            postComment = wallComment;
                            break;
                        }
                    }
                }
            }
            return(post);
        }
예제 #51
0
        /// <summary>
        /// Standard Main() method used by most SDK samples.
        /// </summary>
        /// <param name="args"></param>
        static public void Main(string[] args)
        {
            IOrganizationService service = CRUDOptions.createOrganisationProxy();
            //CRUDOptions.update(service);
            //CRUDOptions.create(service);

            DataCollection <Entity> products = CRUDOptions.getOpportunityProducts(service, new Guid("840CFD52-0FF6-E711-A951-000D3A296791"));

            foreach (Entity entity in products)
            {
                Console.WriteLine("{0}", entity.GetAttributeValue <Guid>("opportunityproductid"));
            }


            OrganizationRequest  request  = new OrganizationRequest("mp_verarbeiten");
            OrganizationResponse response = service.Execute(request);

            Console.WriteLine("*** Fertig ***");
            Console.ReadLine();
            return;


            //try
            //{
            //    // Obtain the target organization's Web address and client logon
            //    // credentials from the user.
            //    ServerConnection serverConnect = new ServerConnection();
            //    ServerConnection.Configuration config = serverConnect.GetServerConfiguration();

            //    DiscoveryService app = new DiscoveryService();
            //    app.Run(config, true);
            //}
            //catch (FaultException<Microsoft.Xrm.Sdk.DiscoveryServiceFault> ex)
            //{
            //    Console.WriteLine("The application terminated with an error.");
            //    Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp);
            //    Console.WriteLine("Code: {0}", ex.Detail.ErrorCode);
            //    Console.WriteLine("Message: {0}", ex.Detail.Message);
            //    Console.WriteLine("Inner Fault: {0}",
            //        null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
            //}
            //catch (System.TimeoutException ex)
            //{
            //    Console.WriteLine("The application terminated with an error.");
            //    Console.WriteLine("Message: {0}", ex.Message);
            //    Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
            //    Console.WriteLine("Inner Fault: {0}",
            //        null == ex.InnerException.Message ? "No Inner Fault" : ex.InnerException.Message);
            //}
            //catch (System.Exception ex)
            //{
            //    Console.WriteLine("The application terminated with an error.");
            //    Console.WriteLine(ex.Message);

            //    // Display the details of the inner exception.
            //    if (ex.InnerException != null)
            //    {
            //        Console.WriteLine(ex.InnerException.Message);

            //        FaultException<Microsoft.Xrm.Sdk.DiscoveryServiceFault> fe = ex.InnerException
            //            as FaultException<Microsoft.Xrm.Sdk.DiscoveryServiceFault>;
            //        if (fe != null)
            //        {
            //            Console.WriteLine("Timestamp: {0}", fe.Detail.Timestamp);
            //            Console.WriteLine("Code: {0}", fe.Detail.ErrorCode);
            //            Console.WriteLine("Message: {0}", fe.Detail.Message);
            //            Console.WriteLine("Inner Fault: {0}",
            //                null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
            //        }
            //    }
            //}
            //// Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException,
            //// SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException.

            //finally
            //{
            //    Console.WriteLine("Press <Enter> to exit.");
            //    Console.ReadLine();
            //}
        }
예제 #52
0
        public void Execute(IServiceProvider serviceProvider)
        {
            SqlDataAccess sda = null;

            try
            {
                sda = new SqlDataAccess();
                sda.openConnection(Globals.ConnectionString);

                #region | SERVICE |
                IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

                #region | Validate Request |
                //Target yoksa veya Entity tipinde değilse, devam etme.
                if (!context.InputParameters.Contains("Target") || !(context.InputParameters["Target"] is Entity))
                {
                    return;
                }
                #endregion

                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                #endregion

                Entity entity = (Entity)context.InputParameters["Target"];

                #region | VARIABLES |
                MsCrmResultObject limitRes  = ScoreHelper.GetScoreLimitsByType(ScoreType.Login, sda);
                List <ScoreLimit> lstLimits = new List <ScoreLimit>();

                EntityReference portal = null;
                EntityReference user   = null;

                if (entity.Contains("new_portalid") && entity["new_portalid"] != null)
                {
                    portal = (EntityReference)entity["new_portalid"];
                }

                if (entity.Contains("new_userid") && entity["new_userid"] != null)
                {
                    user = (EntityReference)entity["new_userid"];
                }
                #endregion

                if (limitRes.Success)
                {
                    lstLimits = (List <ScoreLimit>)limitRes.ReturnObject;

                    for (int i = 0; i < lstLimits.Count; i++)
                    {
                        int      recCount = 0;
                        DateTime start    = GeneralHelper.GetStartDateByScorePeriod(lstLimits[i].Period);
                        DateTime end      = GeneralHelper.GetEndDateByScorePeriod(lstLimits[i].Period);

                        recCount = LoginHelper.GetUserLoginCount(portal.Id, user.Id, start, end, sda);

                        if (lstLimits[i].Frequency >= recCount)
                        {
                            Score sc = new Score()
                            {
                                Point     = lstLimits[i].Point,
                                Portal    = portal,
                                User      = user,
                                ScoreType = ScoreType.Login
                            };

                            MsCrmResult scoreRes = ScoreHelper.CreateScore(sc, service);

                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //LOG
                throw new InvalidPluginExecutionException(ex.Message);
            }
            finally
            {
                if (sda != null)
                {
                    sda.closeConnection();
                }
            }
        }
예제 #53
0
        public static string GetSolutionVersion(this IOrganizationService service, Guid solutionId)
        {
            var solution = service.Retrieve("solution", solutionId, new ColumnSet("friendlyname", "version"));

            return(solution.GetAttributeValue <string>("version"));
        }
예제 #54
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 ExecutePostQuoteCabChassisUpdate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            IPluginExecutionContext context = localContext.PluginExecutionContext;

            Entity preImageEntity  = (context.PreEntityImages != null && context.PreEntityImages.Contains(this.preImageAlias)) ? context.PreEntityImages[this.preImageAlias] : null;
            Entity postImageEntity = (context.PostEntityImages != null && context.PostEntityImages.Contains(this.postImageAlias)) ? context.PostEntityImages[this.postImageAlias] : null;

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

            if (!(context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity))
            {
                return;
            }

            Entity quoteCC = (Entity)context.InputParameters["Target"];

            if (quoteCC.LogicalName != "gsc_sls_quotecabchassis")
            {
                return;
            }

            if (context.Mode == 0) //Synchronous Plugin
            {
                try
                {
                    QuoteCabChassisHandler quoteCCHandler = new QuoteCabChassisHandler(service, trace);

                    string message = context.MessageName;

                    var  preAmount    = preImageEntity.Contains("gsc_amount") ? preImageEntity.GetAttributeValue <Money>("gsc_amount").Value : 0;
                    var  preFinancing = preImageEntity.GetAttributeValue <bool>("gsc_financing");
                    Guid preImageItem = preImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclecabchassisid") != null
                        ? preImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclecabchassisid").Id
                        : Guid.Empty;

                    var  postAmount    = postImageEntity.Contains("gsc_amount") ? postImageEntity.GetAttributeValue <Money>("gsc_amount").Value : 0;
                    var  postFinancing = postImageEntity.GetAttributeValue <bool>("gsc_financing");
                    Guid postImageItem = postImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclecabchassisid") != null
                        ? postImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclecabchassisid").Id
                        : Guid.Empty;

                    if (preAmount != postAmount || preFinancing != postFinancing)
                    {
                        quoteCCHandler.SetCCAddOnAmount(postImageEntity, message);
                    }

                    if (preImageItem != postImageItem)
                    {
                        quoteCCHandler.PopulateDetails(postImageEntity, message);
                    }
                }

                catch (Exception ex)
                {
                    //throw new InvalidPluginExecutionException(String.Concat("(Exception)\n", ex.Message, Environment.NewLine, ex.StackTrace, Environment.NewLine, error));
                    throw new InvalidPluginExecutionException(ex.Message);
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <example>
        /// viewId;entityLogicalName;viewName;ViewType;Type;LCID1;LCID2;...;LCODX
        /// </example>
        /// <param name="entities"></param>
        /// <param name="languages"></param>
        /// <param name="sheet"></param>
        /// <param name="service"></param>
        /// <param name="settings"></param>
        public void Export(List <EntityMetadata> entities, List <int> languages, ExcelWorksheet sheet, IOrganizationService service, ExportSettings settings)
        {
            var line = 0;
            int cell;

            AddHeader(sheet, languages);

            var crmViews = new List <CrmView>();

            foreach (var entity in entities.OrderBy(e => e.LogicalName))
            {
                if (!entity.MetadataId.HasValue)
                {
                    continue;
                }

                var views = RetrieveViews(entity.ObjectTypeCode.Value, service);

                foreach (var view in views)
                {
                    var crmView = crmViews.FirstOrDefault(cv => cv.Id == view.Id);
                    if (crmView == null)
                    {
                        crmView = new CrmView
                        {
                            Id           = view.Id,
                            Entity       = view.GetAttributeValue <string>("returnedtypecode"),
                            Type         = view.GetAttributeValue <int>("querytype"),
                            Names        = new Dictionary <int, string>(),
                            Descriptions = new Dictionary <int, string>()
                        };
                        crmViews.Add(crmView);
                    }

                    RetrieveLocLabelsRequest  request;
                    RetrieveLocLabelsResponse response;

                    if (settings.ExportNames)
                    {
                        // Names
                        request = new RetrieveLocLabelsRequest
                        {
                            AttributeName = "name",
                            EntityMoniker = new EntityReference("savedquery", view.Id)
                        };

                        response = (RetrieveLocLabelsResponse)service.Execute(request);
                        foreach (var locLabel in response.Label.LocalizedLabels)
                        {
                            crmView.Names.Add(locLabel.LanguageCode, locLabel.Label);
                        }
                    }

                    if (settings.ExportDescriptions)
                    {
                        // Descriptions
                        request = new RetrieveLocLabelsRequest
                        {
                            AttributeName = "description",
                            EntityMoniker = new EntityReference("savedquery", view.Id)
                        };

                        response = (RetrieveLocLabelsResponse)service.Execute(request);
                        foreach (var locLabel in response.Label.LocalizedLabels)
                        {
                            crmView.Descriptions.Add(locLabel.LanguageCode, locLabel.Label);
                        }
                    }
                }
            }

            foreach (var crmView in crmViews.OrderBy(cv => cv.Entity).ThenBy(cv => cv.Type))
            {
                if (settings.ExportNames)
                {
                    line++;
                    cell = 0;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = crmView.Id.ToString("B");
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = crmView.Entity;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = _viewTypes.ContainsKey(crmView.Type) ? _viewTypes[crmView.Type] : crmView.Type.ToString();
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Name";

                    foreach (var lcid in languages)
                    {
                        var name = crmView.Names.FirstOrDefault(n => n.Key == lcid);
                        if (name.Value != null)
                        {
                            ZeroBasedSheet.Cell(sheet, line, cell++).Value = name.Value;
                        }
                        else
                        {
                            cell++;
                        }
                    }
                }

                if (settings.ExportDescriptions)
                {
                    line++;
                    cell = 0;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = crmView.Id.ToString("B");
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = crmView.Entity;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = _viewTypes.ContainsKey(crmView.Type) ? _viewTypes[crmView.Type] : crmView.Type.ToString();
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Description";

                    foreach (var lcid in languages)
                    {
                        var desc = crmView.Descriptions.FirstOrDefault(n => n.Key == lcid);
                        if (desc.Value != null)
                        {
                            ZeroBasedSheet.Cell(sheet, line, cell++).Value = desc.Value;
                        }
                        else
                        {
                            cell++;
                        }
                    }
                }
            }

            // Applying style to cells
            for (int i = 0; i < (4 + languages.Count); i++)
            {
                StyleMutator.TitleCell(ZeroBasedSheet.Cell(sheet, 0, i).Style);
            }

            for (int i = 1; i <= line; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    StyleMutator.HighlightedCell(ZeroBasedSheet.Cell(sheet, i, j).Style);
                }
            }
        }
        /// <summary>
        /// This method first connects to the organization service. Afterwards,
        /// auditing is enabled on the organization, account entity, and a couple
        /// of attributes. Finally, display that information in Console, and creates
        /// an XML file.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            _sampleStartTime = DateTime.Now;
            using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
            {
                // This statement is required to enable early-bound type support.
                _serviceProxy.EnableProxyTypes();

                // You can access the service through the proxy, but this sample uses the interface instead.
                _service = _serviceProxy;

                #region Enable Auditing for an Account

                Console.WriteLine("Enabling auditing on the organization and account entities.");

                // Enable auditing on the organization.
                // First, get the organization's ID from the system user record.
                Guid orgId = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).OrganizationId;

                // Next, retrieve the organization's record.
                Organization org = _service.Retrieve(Organization.EntityLogicalName, orgId,
                                                     new ColumnSet(new string[] { "organizationid", "isauditenabled" })) as Organization;

                // Finally, enable auditing on the organization.
                bool organizationAuditingFlag = org.IsAuditEnabled.Value;
                bool usersAccessAuditingFlag  = org.IsUserAccessAuditEnabled.HasValue ?
                                                org.IsUserAccessAuditEnabled.Value : false;

                org.IsAuditEnabled           = true;
                org.IsUserAccessAuditEnabled = true;
                _service.Update(org);

                // Enable auditing on account entities.
                bool accountAuditingFlag = EnableEntityAuditing(Account.EntityLogicalName, true);

                #endregion Enable Auditing for an Account

                CreateRequiredRecords();

                #region Create and start XML file

                // Create the XML file
                String fileName = "auditReport.xml";
                textWriter = new XmlTextWriter(fileName, null);
                textWriter.WriteStartDocument();

                // Start Audit Node
                textWriter.WriteStartElement("auditReport", "");

                #endregion

                #region Retrive user access audit records

                var query = new QueryExpression(Audit.EntityLogicalName)
                {
                    ColumnSet = new ColumnSet("createdon", "action", "operation", "objectid"),
                    Criteria  = new FilterExpression(LogicalOperator.And)
                };

                // Only retrieve audit records that track user access.
                query.Criteria.AddCondition("action", ConditionOperator.In,
                                            (int)AuditAction.UserAccessAuditStarted,
                                            (int)AuditAction.UserAccessAuditStopped,
                                            (int)AuditAction.UserAccessviaWebServices,
                                            (int)AuditAction.UserAccessviaWeb);

                // Change this to false in order to retrieve audit records for all users
                // when running the sample.
                var filterAuditsRetrievedByUser = true;
                if (filterAuditsRetrievedByUser)
                {
                    // Only retrieve audit records for the current user.
                    var userFilter = new FilterExpression(LogicalOperator.Or);
                    userFilter.AddCondition(
                        "userid", ConditionOperator.Equal, _serviceProxy.CallerId);
                }
                // Only retrieve records for this sample run, so that we don't get too
                // many results if auditing was enabled previously.
                query.Criteria.AddCondition(
                    "createdon", ConditionOperator.GreaterEqual, _sampleStartTime);

                var results = _serviceProxy.RetrieveMultiple(query);
                foreach (Audit audit in results.Entities)
                {
                    // Display results
                    DisplayAndAddToXMLFileUserAccessDetails(audit);
                }

                #endregion

                #region Retrieve the Audit History
                Console.WriteLine("Retrieving the account change history.\n");

                DateTime startTime = DateTime.Now;

                // Retrieve the audit records for accounts.
                RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();
                changeRequest.Target = new EntityReference(Account.EntityLogicalName, _newAccountId);

                RetrieveRecordChangeHistoryResponse changeResponse =
                    (RetrieveRecordChangeHistoryResponse)_service.Execute(changeRequest);

                AuditDetailCollection details = changeResponse.AuditDetailCollection;

                foreach (AttributeAuditDetail detail in details.AuditDetails)
                {
                    // Write out some of the information in each audit record.
                    DisplayAndAddToXMLFileAuditDetails(detail);
                }
                #endregion Retrieve the Audit History

                #region RetrieveAttributeChangeHistoryRequest
                // How to use message: RetrieveAttributeChangeHistoryRequest

                // Update Telephone1 in account entity
                Account accountToUpdate = new Account();
                accountToUpdate.AccountId  = _newAccountId;
                accountToUpdate.Telephone1 = "123-555-5555";
                _serviceProxy.Update(accountToUpdate);
                Console.WriteLine("Updated Telephone1 field in Account entity.");

                Console.WriteLine("Retrieving attribute change history for Telephone1.");
                // Create RetrieveAttributeChangeHistoryRequest
                var attributeChangeHistoryRequest = new RetrieveAttributeChangeHistoryRequest
                {
                    Target = new EntityReference(
                        Account.EntityLogicalName, _newAccountId),
                    AttributeLogicalName = "telephone1"
                };

                // Execute RetrieveAttributeChangeHistoryRequest
                var attributeChangeHistoryResponse =
                    (RetrieveAttributeChangeHistoryResponse)_service.Execute(attributeChangeHistoryRequest);

                // Set AuditDetailCollection and output to console
                details = attributeChangeHistoryResponse.AuditDetailCollection;

                foreach (var detail in details.AuditDetails)
                {
                    DisplayAndAddToXMLFileAuditDetails(detail);
                }

                // Create an Audit record
                // to store a sample for use with RetrieveAuditDetailsRequest
                Guid auditSampleId = details.AuditDetails.First().AuditRecord.Id;
                #endregion RetrieveAttributeChangeHistoryRequest

                #region RetrieveAuditDetailsRequest
                // How to use message: RetrieveAuditDetailsRequest

                Console.WriteLine("Retrieving audit details for an audit record.");
                // Create RetrieveAuditDetailsRequest
                var auditDetailsRequest = new RetrieveAuditDetailsRequest
                {
                    AuditId = auditSampleId
                };

                // Execute RetrieveAuditDetailsRequest
                var auditDetailsResponse =
                    (RetrieveAuditDetailsResponse)_service.Execute(auditDetailsRequest);

                // Display results
                DisplayAndAddToXMLFileAuditDetails(auditDetailsResponse.AuditDetail);

                #endregion RetrieveAuditDetailsRequest

                #region Retrieve AuditExtension details

                Console.WriteLine("Simulating a user reading records");
                _service.Retrieve(Account.EntityLogicalName, _newAccountId, new ColumnSet("accountid"));

                // creating read records is an async process - wait until the records have been created
                // wait a max of 30 seconds
                Console.WriteLine("Fetching read audit records for accounts");
                for (int i = 0; i < 30; i++)
                {
                    query = new QueryExpression
                    {
                        EntityName = "sample_auditextension",
                        ColumnSet  = new ColumnSet("createdon", "sample_objectlogicalname",
                                                   "sample_objectid", "sample_userid", "sample_action", "sample_operation"),
                        Criteria = new FilterExpression
                        {
                            Conditions =
                            {
                                new ConditionExpression("sample_objectlogicalname", ConditionOperator.Equal, Account.EntityLogicalName),
                                new ConditionExpression("sample_objectid",          ConditionOperator.Equal,
                                                        _newAccountId.ToString().TrimStart('{').TrimEnd('}'))
                            }
                        }
                    };
                    results = _service.RetrieveMultiple(query);
                    if (results.Entities.Count > 0)
                    {
                        break;
                    }
                    else if (i == 29)
                    {
                        throw new Exception("Exceeded maximum wait time");
                    }
                    System.Threading.Thread.Sleep(1000);
                }

                foreach (var record in results.Entities)
                {
                    _auditExtensionRecordIds.Add(record.Id);
                    DisplayAndAddToXmlFileAuditExtension(record);
                }

                #endregion

                #region Finish and close XML file

                // End auditReport Xml Node
                textWriter.WriteEndElement();
                textWriter.WriteEndDocument();

                // Close xml writer.
                textWriter.Close();

                Console.WriteLine("File name: " + fileName);

                #endregion

                #region Revert auditing
                // Set the organization and account auditing flags back to the old values
                org.IsAuditEnabled           = organizationAuditingFlag;
                org.IsUserAccessAuditEnabled = usersAccessAuditingFlag;
                _service.Update(org);

                EnableEntityAuditing(Account.EntityLogicalName, accountAuditingFlag);

                #endregion Revert auditing

                DeleteRequiredRecords(promptforDelete);
            }
        }
        /// <summary>
        /// Executes the workflow activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Create the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
            }

            tracingService.Trace("Entered " + _activityName + ".Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                                 executionContext.ActivityInstanceId,
                                 executionContext.WorkflowInstanceId);

            // Create the context
            IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>();

            if (context == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
            }

            tracingService.Trace(_activityName + ".Execute(), Correlation Id: {0}, Initiating User: {1}",
                                 context.CorrelationId,
                                 context.InitiatingUserId);

            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                string inputText = TextInput.Get(executionContext);
                if (inputText != string.Empty)
                {
                    inputText = HtmlTools.StripHTML(inputText);

                    //create the webrequest object and execute it (and post jsonmsg to it)
                    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(_webAddress);

                    //set request content type so it is treated as a regular form post
                    req.ContentType = "application/x-www-form-urlencoded";

                    //set method to post
                    req.Method = "POST";

                    StringBuilder postData = new StringBuilder();

                    //HttpUtility.UrlEncode
                    //set the apikey request value
                    postData.Append("apikey=" + System.Uri.EscapeDataString(_apiKey) + "&");
                    //postData.Append("apikey=" + _apiKey + "&");

                    //set the text request value
                    postData.Append("text=" + System.Uri.EscapeDataString(inputText));
                    //postData.Append("text=" + inputText);

                    //create a stream
                    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData.ToString());
                    req.ContentLength = bytes.Length;
                    System.IO.Stream os = req.GetRequestStream();
                    os.Write(bytes, 0, bytes.Length);
                    os.Close();

                    //get the response
                    System.Net.WebResponse resp = req.GetResponse();

                    //deserialize the response to a SentimentResponse object
                    SentimentResponse myResponse = new SentimentResponse();
                    System.Runtime.Serialization.Json.DataContractJsonSerializer deserializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myResponse.GetType());
                    myResponse = deserializer.ReadObject(resp.GetResponseStream()) as SentimentResponse;

                    //set output values from the fields of the deserialzed myjsonresponse object
                    Score.Set(executionContext, myResponse.Aggregate.Score);
                    Sentiment.Set(executionContext, myResponse.Aggregate.Sentiment);
                }
            }

            catch (WebException exception)
            {
                string str = string.Empty;
                if (exception.Response != null)
                {
                    using (StreamReader reader =
                               new StreamReader(exception.Response.GetResponseStream()))
                    {
                        str = reader.ReadToEnd();
                    }
                    exception.Response.Close();
                }
                if (exception.Status == WebExceptionStatus.Timeout)
                {
                    throw new InvalidPluginExecutionException(
                              "The timeout elapsed while attempting to issue the request.", exception);
                }
                throw new InvalidPluginExecutionException(String.Format(CultureInfo.InvariantCulture,
                                                                        "A Web exception ocurred while attempting to issue the request. {0}: {1}",
                                                                        exception.Message, str), exception);
            }
            catch (FaultException <OrganizationServiceFault> e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());

                // Handle the exception.
                throw;
            }
            catch (Exception e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());
                throw;
            }

            tracingService.Trace("Exiting " + _activityName + ".Execute(), Correlation Id: {0}", context.CorrelationId);
        }
예제 #58
0
 public DataConstructor(IOrganizationService incomingService)
 {
     service = incomingService;
 }
예제 #59
0
        public XTLInterpreter(string input, Entity primary, OrganizationConfig organizationConfig, IOrganizationService service, ITracingService tracing)
        {
            _primary            = primary;
            _service            = service;
            _tracing            = tracing;
            _organizationConfig = organizationConfig;
            _input    = input;
            _position = 0;

            _reader = new StringReader(input ?? string.Empty);
            GetChar();
            SkipWhiteSpace();
        }
예제 #60
0
 public Numbering(IOrganizationService svc, ITracingService tracingSvc, Entity entity)
     : base(svc, tracingSvc, entity)
 {
 }