Exemplo n.º 1
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Create a medication request.
        /// </summary>

        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetMarketingAutomation1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    Entity medicationrequest = new Entity("msemr_medicationrequest");

                    medicationrequest["msemr_identifier"]      = "MR-1234";
                    medicationrequest["msemr_groupidentifier"] = "MRG-12345";
                    medicationrequest["msemr_priority"]        = new OptionSetValue(935000000);
                    medicationrequest["msemr_intent"]          = new OptionSetValue(935000000);
                    medicationrequest["msemr_status"]          = new OptionSetValue(935000000);
                    medicationrequest["msemr_dispenserequestvalidityperiodstartdate"] = DateTime.Now;
                    medicationrequest["msemr_dispenserequestvalidityperiodenddate"]   = DateTime.Now;
                    medicationrequest["msemr_authoredon"]             = DateTime.Now;
                    medicationrequest["msemr_expectedsupplyduration"] = (decimal)3.5;

                    // Setting Request Type as Organisation
                    medicationrequest["msemr_requesteragenttype"] = new OptionSetValue(935000001); //Organisation
                    Guid RequesteragentTypeOrganization = Organization.GetAccountId(_serviceProxy, "Galaxy Corp");
                    if (RequesteragentTypeOrganization != Guid.Empty)
                    {
                        medicationrequest["msemr_requesteragenttypeorganization"] = new EntityReference("account", RequesteragentTypeOrganization);
                    }

                    //Setting Medication Type as Medication Reference
                    medicationrequest["msemr_medicationtype"] = new OptionSetValue(935000001);
                    Guid MedicationTypeReference = Medication.GetProductId(_serviceProxy, "Panadol");
                    if (MedicationTypeReference != Guid.Empty)
                    {
                        medicationrequest["msemr_medicationtypereference"] = new EntityReference("product", MedicationTypeReference);
                    }


                    // Setting Subject Type as Patient
                    medicationrequest["msemr_subjecttype"] = new OptionSetValue(935000000);
                    Guid SubjectTypePatient = SDKFunctions.GetContactId(_serviceProxy, "James Kirk", 935000000);
                    if (SubjectTypePatient != Guid.Empty)
                    {
                        medicationrequest["msemr_subjecttypepatient"] = new EntityReference("contact", SubjectTypePatient);
                    }

                    //Setting Context Type as Episode as Care
                    medicationrequest["msemr_contexttype"] = new OptionSetValue(935000000);
                    Guid ConextTypeEpisodeofCare = EpisodeOfCare.GetEpisodeOfCareId(_serviceProxy, "EPC-153");
                    if (ConextTypeEpisodeofCare != Guid.Empty)
                    {
                        medicationrequest["msemr_contexttypeepisodeofcare"] = new EntityReference("msemr_episodeofcare", ConextTypeEpisodeofCare);
                    }


                    Guid Recorder = SDKFunctions.GetContactId(_serviceProxy, "Emily Williams", 935000001);
                    if (Recorder != Guid.Empty)
                    {
                        medicationrequest["msemr_recorder"] = new EntityReference("contact", Recorder);
                    }
                    Guid Category = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Pain", 935000080);
                    if (Category != Guid.Empty)
                    {
                        medicationrequest["msemr_category"] = new EntityReference("msemr_codeableconcept", Category);
                    }
                    Guid PriorPrescription = getMedicationRequestId(_serviceProxy, "MR-1234");
                    if (PriorPrescription != Guid.Empty)
                    {
                        medicationrequest["msemr_priorprescription"] = new EntityReference("msemr_medicationrequest", PriorPrescription);
                    }
                    Guid RequesterOnBehalfOf = Organization.GetAccountId(_serviceProxy, "Galaxy Corp");
                    if (RequesterOnBehalfOf != Guid.Empty)
                    {
                        medicationrequest["msemr_requesteronbehalfof"] = new EntityReference("account", RequesterOnBehalfOf);
                    }

                    Guid SubstitutionReason = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Substitution Reason", 935000144);
                    if (SubstitutionReason != Guid.Empty)
                    {
                        medicationrequest["msemr_substitutionreason"] = new EntityReference("msemr_codeableconcept", SubstitutionReason);
                    }



                    Guid DispenseRequestPerformer = Organization.GetAccountId(_serviceProxy, "Galaxy Corp");
                    if (DispenseRequestPerformer != Guid.Empty)
                    {
                        medicationrequest["msemr_dispenserequestperformer"] = new EntityReference("account", DispenseRequestPerformer);
                    }

                    medicationrequest["msemr_substitutionallowed"]     = true;
                    medicationrequest["msemr_dispenserequestquantity"] = 1;
                    medicationrequest["msemr_dispenserequestnumberofrepeatsallowed"] = 1;
                    medicationrequest["msemr_dispenserequestexpectedsupplyduration"] = 1;


                    Guid MedicationRequestId = _serviceProxy.Create(medicationrequest);

                    // Verify that the record has been created.
                    if (MedicationRequestId != Guid.Empty)
                    {
                        Console.WriteLine("Succesfully created {0}.", MedicationRequestId);
                    }
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        /*private void btnConnect_Click(object sender, EventArgs e)
        {
            btnConnect.Text = "Connecting";
            btnConnect.Enabled = false;

            if (cmb_configurations.SelectedIndex >= 0 && cmb_configurations.SelectedItem.ToString() != "<< Create new server configuration >>") {
                try {
                    ServerConnection.Configuration config = _myCrmHelper.Configurations[cmb_configurations.SelectedIndex];
                    config.Credentials.Windows.ClientCredential = new System.Net.NetworkCredential("tnd_dlagrew", "Welcome1", "tnd");
                    //config.Credentials.Windows.ClientCredential.UserName = "******";
                    //config.Credentials.Windows.ClientCredential.Password = "******";
                    // Set IServiceManagement for the current organization.
                    _myCrmHelper.SetIServiceManagementForOrganization(ref config);

                    btnConnect.Enabled = true;
                    btnConnect.Text = "Connect";

                    Views.RibbonDownloadForm ribbonDlForm = new RibbonDownloadForm(config);
                    ribbonDlForm.Text = config.ServerAddress.ToString() + ": " + config.OrganizationName;
                    ribbonDlForm.MdiParent = this.MdiParent;
                    ribbonDlForm.Show();

                    this.Close();
                }
                catch (Exception ex) {
                    MessageBox.Show(ex.Message);
                }
            }
        }*/
        private void btnSaveConfig_Click(object sender, EventArgs e)
        {
            ResetLabels();
            bool isError = false;
            if (String.IsNullOrWhiteSpace(tbxServerAddr.Text)) {
                lblServerAddr.ForeColor = Color.Red;
                lblServerAddr.Text = "* " + lblServerAddr.Text;
                isError = true;
            }

            if (String.IsNullOrWhiteSpace(tbxDomainUsername.Text)) {
                lblDomainAndUsername.ForeColor = Color.Red;
                lblDomainAndUsername.Text = "* " + lblDomainAndUsername.Text;
                isError = true;
            }
            if (String.IsNullOrWhiteSpace(tbxPassword.Text)) {
                lblPassword.ForeColor = Color.Red;
                lblPassword.Text = "* " + lblPassword.Text;
                isError = true;
            }

            if (isError) return;

            String[] domainAndUserName = tbxDomainUsername.Text.Split('\\');

            if (domainAndUserName.Count() != 2) {
                lblDomainAndUsername.ForeColor = Color.Red;
                lblDomainAndUsername.Text = "* " + lblDomainAndUsername.Text;
                return;
            }

            _newConfig = new ServerConnection.Configuration { ServerAddress = tbxServerAddr.Text };

            if (String.IsNullOrWhiteSpace(_newConfig.ServerAddress))
                _newConfig.ServerAddress = "crm.dynamics.com";

            // One of the Microsoft Dynamics CRM Online data centers.
            if (_newConfig.ServerAddress.EndsWith(".dynamics.com", StringComparison.InvariantCultureIgnoreCase)) {
                // Check if the organization is provisioned in Microsoft Office 365.
                if (cbxOffice365.Checked) {
                    _newConfig.DiscoveryUri = new Uri(String.Format("https://disco.{0}/XRMServices/2011/Discovery.svc", _newConfig.ServerAddress));
                }
                else {
                    _newConfig.DiscoveryUri = new Uri(String.Format("https://dev.{0}/XRMServices/2011/Discovery.svc", _newConfig.ServerAddress));

                    // Get or set the device credentials. This is required for Windows Live ID authentication.
                    _newConfig.DeviceCredentials = Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice();
                }
            }
            // Check if the server uses Secure Socket Layer (https).
            else if (cbxHttps.Checked)
                _newConfig.DiscoveryUri = new Uri(String.Format("https://{0}/XRMServices/2011/Discovery.svc", _newConfig.ServerAddress));
            else
                _newConfig.DiscoveryUri = new Uri(String.Format("http://{0}/XRMServices/2011/Discovery.svc", _newConfig.ServerAddress));

            // Get Login Credentials
            ClientCredentials creds = new ClientCredentials();
            creds.Windows.ClientCredential = new System.Net.NetworkCredential(domainAndUserName[1], tbxPassword.Text, domainAndUserName[0]);
            _newConfig.Credentials = creds;

            // Get Target Organization
            OrganizationDetailCollection organizations = new OrganizationDetailCollection();
            try {
                organizations = _myCrmHelper.GetOrganizationAddressesAsList(_newConfig);
            }
            catch (System.IO.FileNotFoundException ex) {
                MessageBox.Show(String.Format("Error: {0}", ex.Message));
            }

            // If there's only one organization then use that. Otherwise present the user with the multiple options.
            if (organizations.Count == 1) {
                _newConfig.OrganizationName = organizations[0].FriendlyName;
                _newConfig.OrganizationUri = new Uri(organizations[0].Endpoints[EndpointType.OrganizationService]);
                SaveConfiguration();
            }
            else {
                this.Height = 510;
                gbxOrgs.Visible = true;
                lbOrganizations.DataSource = organizations;
                lbOrganizations.DisplayMember = "FriendlyName";
            }
        }
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Create an appointment.
        /// </summary>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetMarketingAutomation1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    var person = new Entity("contact");

                    person["firstname"]                    = "Betty";
                    person["lastname"]                     = "Welch";
                    person["msfsi_billpay"]                = true;
                    person["msfsi_chargestartdate"]        = DateTime.UtcNow;
                    person["msfsi_churnscore"]             = 1m;
                    person["parentcustomerid"]             = new EntityReference("account", new Guid("{3DB68AE1-D9B9-440D-92CC-821CD251EB91}"));
                    person["msfsi_creditscore"]            = 5;
                    person["msfsi_debtburdenratio"]        = 1m;
                    person["msfsi_defaultchargeaccountid"] = new EntityReference("msfsi_financialproduct", new Guid("{3DB68AE1-D9B9-440D-92CC-821CD251EB92}"));
                    person["msfsi_delinquencyscore"]       = 5;
                    person["msfsi_delinquentamount"]       = new Money(0);
                    person["msfsi_directdeposit"]          = true;
                    person["msfsi_employerid"]             = new EntityReference("account", new Guid(""));
                    person["msfsi_employmentstatus"]       = new OptionSetValue();               //
                    person["msfsi_enrollmentbranchid"]     = new EntityReference("msfsi_branch", new Guid("{3DB68AE1-D9B9-440D-92CC-821CD251EB93}"));
                    person["msdyn_gdproptout"]             = true;
                    person["msfsi_idexpirydate"]           = DateTime.UtcNow;
                    person["msfsi_idtype"]                 = new OptionSetValue();     //
                    person["msfsi_isminor"]                = true;
                    person["msfsi_monthlyincome"]          = new Money(0);
                    person["msfsi_monthlyliabilities"]     = new Money(0);
                    person["msdyn_orgchangestatus"]        = new OptionSetValue(0);              // No
                    person["msfsi_placeofbirth"]           = string.Empty;
                    person["msfsi_preferredbranchid"]      = new EntityReference("msfsi_branch", new Guid("{3DB68AE1-D9B9-440D-92CC-821CD251EB94}"));
                    person["msfsi_profittier"]             = new OptionSetValue(104800000);         // High
                    person["msfsi_residencystatus"]        = new OptionSetValue(104800000);         // Resident
                    person["msfsi_residentincountrysince"] = DateTime.UtcNow;
                    person["msfsi_totaldeposits"]          = new Money(0);
                    person["msfsi_totalloans"]             = new Money(0);
                    person["msfsi_visaexpiry"]             = DateTime.UtcNow;
                    person["msfsi_waivecharges"]           = true;

                    var id = _serviceProxy.Create(person);

                    // Verify that the record has been created.
                    if (id != Guid.Empty)
                    {
                        Console.WriteLine($"Succesfully created {id}.");
                    }
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Standard Main() method used by most SDK samples.
        /// </summary>
        /// <param name="args"></param>
        static public void Main(string[] args)
        {
            try
            {
                // Obtain the target organization's Web address and client logon
                // credentials from the user.
                ServerConnection serverConnect        = new ServerConnection();
                ServerConnection.Configuration config = serverConnect.GetServerConfiguration();

                MedicationRequest app = new MedicationRequest();
                app.Run(config, true);
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> 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("Plugin Trace: {0}", ex.Detail.TraceText);
                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.OrganizationServiceFault> fe = ex.InnerException
                                                                                     as FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault>;
                    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("Plugin Trace: {0}", fe.Detail.TraceText);
                        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();
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Demonstrates sharing records by exercising various access messages including:
        /// Grant, Modify, Revoke, RetrievePrincipalAccess, and
        /// RetrievePrincipalsAndAccess.
        /// </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)
        {
            try
            {
                Console.WriteLine("Looking for picklists to export values for");

                string solutionName = ConfigurationManager.AppSettings["cdm:solution"];

                // we need this to support communicating with Dynamics Online Instances
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                //<snippetSharingRecords1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    _service = (IOrganizationService)_serviceProxy;

                    IEnumerable <EntityMetadata> entities = getSolutionEntities(solutionName, _serviceProxy);

                    foreach (EntityMetadata em in entities)
                    {
                        foreach (AttributeMetadata am in em.Attributes)
                        {
                            if (am.AttributeType == AttributeTypeCode.Picklist)
                            {
                                if ((em.LogicalName.ToLower().StartsWith("msemr_")) || (am.LogicalName.ToLower().StartsWith("msemr_")))
                                {
                                    PickListEnums ple = new PickListEnums();
                                    ple = GetOptionPickListValues(em.LogicalName, em.DisplayName.UserLocalizedLabel.Label.ToString(), am.LogicalName, _serviceProxy);

                                    enums.Add(ple);

                                    newNumerations += ple.GenerateEnum();
                                }
                            }
                        }
                    }


                    string picklistoutputfile = ConfigurationManager.AppSettings["cdm:picklistvaluesoutputfilename"];
                    string enumfile           = ConfigurationManager.AppSettings["cdm:enumsourceoutputfilename"];

                    // if we don't have any don't write anything
                    if (picklistmappingdata.Count > 0)
                    {
                        File.Delete(picklistoutputfile); // Remove this line if you don't want to erase the current version
                        File.WriteAllLines(picklistoutputfile, picklistmappingdata);
                    }
                    else
                    {
                        Console.WriteLine("Could not find any pick list Types");
                    }

                    File.Delete(enumfile); // Remove this line if you don't want to erase the current version
                    File.WriteAllText(enumfile, newNumerations);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Create an encounter.
        /// </summary>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetMarketingAutomation1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    Entity encounter = new Entity("msemr_encounter");

                    encounter["msemr_name"] = "Routine";

                    Guid subjectpatientContactId = SDKFunctions.GetContactId(_serviceProxy, "Daniel Atlas");
                    if (subjectpatientContactId != Guid.Empty)
                    {
                        encounter["msemr_subjectpatient"] = new EntityReference("contact", subjectpatientContactId);
                    }

                    encounter["msemr_class"] = new OptionSetValue(935000008); //short stay

                    encounter["msemr_encounterstartdate"]  = DateTime.Now;
                    encounter["msemr_encounterenddate"]    = DateTime.Now;
                    encounter["msemr_encounterclass"]      = new OptionSetValue(935000001); //outPatient
                    encounter["msemr_encounterlength"]     = (decimal)30.5;
                    encounter["msemr_encounterstatus"]     = new OptionSetValue(935000000); //Planned
                    encounter["msemr_encounteridentifier"] = "Routine 25352";
                    Guid priorityCodeableConceptId = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Urgent", 935000102);
                    if (priorityCodeableConceptId != Guid.Empty)
                    {
                        encounter["msemr_encounterpriority"] = new EntityReference("msemr_codeableconcept", priorityCodeableConceptId);
                    }
                    Guid groupCodeableConceptId = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Group Identifier", 935000063);
                    if (groupCodeableConceptId != Guid.Empty)
                    {
                        encounter["msemr_encountergroupidentifier"] = new EntityReference("msemr_codeableconcept", groupCodeableConceptId);
                    }
                    Guid parentEncountertId = GetEncounterId(_serviceProxy, "E23556");
                    if (parentEncountertId != Guid.Empty)
                    {
                        encounter["msemr_encounterparentencounteridentifier"] = new EntityReference("msemr_encounter", parentEncountertId);
                    }
                    Guid patientIdentifier = SDKFunctions.GetContactId(_serviceProxy, "James Kirk");
                    if (patientIdentifier != Guid.Empty)
                    {
                        encounter["msemr_encounterpatientidentifier"] = new EntityReference("contact", patientIdentifier);
                    }

                    encounter["msemr_periodstart"] = DateTime.Now;
                    encounter["msemr_periodend"]   = DateTime.Now;
                    encounter["msemr_duration"]    = 30;
                    encounter["msemr_priority"]    = new OptionSetValue(935000000); //ASAP

                    encounter["msemr_hospitalizationpreadmissionnumber"] = "25352";
                    Guid destinationLocationId = SDKFunctions.GetLocationId(_serviceProxy, "Noble Hospital Center");
                    if (destinationLocationId != Guid.Empty)
                    {
                        encounter["msemr_hospitalizationdestination"] = new EntityReference("msemr_location", destinationLocationId);
                    }
                    Guid dischargedispositionCodeableConceptId = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Discharge Disposition", 935000042);
                    if (dischargedispositionCodeableConceptId != Guid.Empty)
                    {
                        encounter["msemr_hospitalizationdischargedisposition"] = new EntityReference("msemr_codeableconcept", dischargedispositionCodeableConceptId);
                    }
                    Guid admitsourceCodeableConceptId = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Admit Source", 935000007);
                    if (admitsourceCodeableConceptId != Guid.Empty)
                    {
                        encounter["msemr_hospitalizationadmitsource"] = new EntityReference("msemr_codeableconcept", admitsourceCodeableConceptId);
                    }
                    Guid readmissionCodeableConceptId = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Re-admission", 935000114);
                    if (readmissionCodeableConceptId != Guid.Empty)
                    {
                        encounter["msemr_hospitalizationreadmission"] = new EntityReference("msemr_codeableconcept", readmissionCodeableConceptId);
                    }

                    Guid originLocationId = SDKFunctions.GetLocationId(_serviceProxy, "Alpine");
                    if (originLocationId != Guid.Empty)
                    {
                        encounter["msemr_hospitalizationorigin"] = new EntityReference("msemr_location", originLocationId);
                    }

                    Guid accountId = Organization.GetAccountId(_serviceProxy, "Galaxy Corp");
                    if (accountId != Guid.Empty)
                    {
                        encounter["msemr_onbehalfof"] = new EntityReference("account", accountId);
                    }

                    Guid encounterId = _serviceProxy.Create(encounter);

                    // Verify that the record has been created.
                    if (encounterId != Guid.Empty)
                    {
                        Console.WriteLine("Succesfully created {0}.", encounterId);
                    }
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Demonstrates sharing records by exercising various access messages including:
        /// Grant, Modify, Revoke, RetrievePrincipalAccess, and
        /// RetrievePrincipalsAndAccess.
        /// </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)
        {
            try
            {
                Console.WriteLine("Export codeable concept pick list values");

                string picklistmappingfilename = ConfigurationManager.AppSettings["cdm:conceptpicklistvalues"];

                if (string.IsNullOrEmpty(picklistmappingfilename))
                {
                    Console.WriteLine("Error: could not find the pick list mapping file name value");
                    return;
                }

                // we need this to support communicating with Dynamics Online Instances
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                //<snippetSharingRecords1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    _service = (IOrganizationService)_serviceProxy;


                    // set the properties to get back the codeable concept picklist values
                    // from the picklist (optionset)
                    RetrieveAttributeRequest retrieveEntityRequest = new RetrieveAttributeRequest
                    {
                        EntityLogicalName     = "msemr_codeableconcept",
                        LogicalName           = "msemr_type",
                        RetrieveAsIfPublished = true
                    };

                    // execute the call and retrieve the actual metadata directly
                    RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)_serviceProxy.Execute(retrieveEntityRequest);
                    var attributeMetadata = (EnumAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;

                    // retrieve each option list item
                    var optionList = (from o in attributeMetadata.OptionSet.Options
                                      select new { Value = o.Value, Text = o.Label.UserLocalizedLabel.Label }).ToList();

                    // the data we will write to the CSV file that get's used by our import program
                    // remember what we are doing here, is making the mapping file between
                    // the codeable concepts actual values, and the OptionSet "attribute" that
                    // needs to be set when you import a codeable concept
                    // so you have can either use the file we produce for you
                    // or create a fresh one based on any new values that are added over time
                    List <string> picklistmappingdata = new List <string>();

                    // iterate through each option and write out the value and text
                    // this will enable us to map the "Text" value given to us in the
                    // codeable concepts file that we generated OR if you generate some new ones
                    // you can run this program again to create the mapping file
                    // or at least have the copy that was generated for you

                    int totalOptions = 0;

                    foreach (var option in optionList)
                    {
                        totalOptions++;

                        // add to our string list of options
                        picklistmappingdata.Add(option.Text.Trim() + "," + option.Value.ToString().Trim()); //default to first string of the label

                        // write out our option count
                        Console.SetCursorPosition(0, Console.CursorTop);
                        Console.Write("Total Options Found [" + totalOptions.ToString() + "]");

                        System.Threading.Thread.Sleep(0);
                    }

                    // if we don't have any don't write anything
                    if (picklistmappingdata.Count > 0)
                    {
                        File.Delete(picklistmappingfilename); // Remove this line if you don't want to erase the current version
                        File.WriteAllLines(picklistmappingfilename, picklistmappingdata);

                        Console.SetCursorPosition(0, Console.CursorTop);
                        Console.WriteLine("Created codeable concepts mapping file [" + picklistmappingfilename + "]");
                    }
                    else
                    {
                        Console.WriteLine("Could not find any Codeable Concept Types");
                    }
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Create a location.
        /// </summary>

        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetMarketingAutomation1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    Entity location = new Entity("msemr_location");

                    location["msemr_name"] = "Noble Hospital Center";

                    location["msemr_addresstype"]        = new OptionSetValue(935000001); //Physical
                    location["msemr_addressuse"]         = new OptionSetValue(935000001); //Work
                    location["msemr_addresscity"]        = "Albuquerque";
                    location["msemr_addresscountry"]     = "US";
                    location["msemr_addressline1"]       = "1770";
                    location["msemr_addressline2"]       = "Byrd";
                    location["msemr_addressline3"]       = "Lane";
                    location["msemr_addresspostalcode"]  = "87107";
                    location["msemr_addressstate"]       = "New Mexico";
                    location["msemr_addresstext"]        = "Primary Location";
                    location["msemr_addressperiodend"]   = DateTime.Now;
                    location["msemr_addressperiodstart"] = DateTime.Now.AddDays(20);

                    Guid accountId = Organization.GetAccountId(_serviceProxy, "Galaxy Corp");
                    if (accountId != Guid.Empty)
                    {
                        location["msemr_managingorganization"] = new EntityReference("account", accountId);
                    }

                    Guid partOfLocationId = SDKFunctions.GetLocationId(_serviceProxy, "FHIR Organizational Unit");
                    if (partOfLocationId != Guid.Empty)
                    {
                        location["msemr_partof"] = new EntityReference("msemr_location", partOfLocationId);
                    }

                    Guid physicaltypeCodeableConceptId = SDKFunctions.GetCodeableConceptId(_serviceProxy, "si", 935000072);
                    if (physicaltypeCodeableConceptId != Guid.Empty)
                    {
                        location["msemr_physicaltype"] = new EntityReference("msemr_codeableconcept", physicaltypeCodeableConceptId);
                    }

                    Guid typeCodeableConceptId = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Dx", 935000131);
                    if (typeCodeableConceptId != Guid.Empty)
                    {
                        location["msemr_type"] = new EntityReference("msemr_codeableconcept", typeCodeableConceptId);
                    }

                    location["msemr_mode"] = new OptionSetValue(935000001);              //Kind

                    location["msemr_status"] = new OptionSetValue(935000000);            //Active

                    location["msemr_operationalstatus"] = new OptionSetValue(935000004); //Occupied

                    location["msemr_description"] = "Primary Location";

                    location["msemr_locationnumber"]            = "L442";
                    location["msemr_locationalias1"]            = "General Hospital";
                    location["msemr_locationpositionaltitude"]  = (decimal)18524.5265;
                    location["msemr_locationpositionlatitude"]  = (decimal)24.15;
                    location["msemr_locationpositionlongitude"] = (decimal)841.12;

                    Guid locationId = _serviceProxy.Create(location);

                    // Verify that the record has been created.
                    if (locationId != Guid.Empty)
                    {
                        Console.WriteLine("Succesfully created {0}.", locationId);
                    }
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Exemplo n.º 9
0
        private static void Run(CommandLineArgs arguments)
        {
            try
            {
                if (arguments.Task.Length < 3)
                {
                    throw new CommandLineException("Invalid Command");
                }
                var trace = new TraceLogger();

                if (arguments.Connection == null)
                {
                    // No Connection is supplied to ask for connection on command line
                    ServerConnection serverConnect        = new ServerConnection();
                    ServerConnection.Configuration config = serverConnect.GetServerConfiguration(arguments.IgnoreLocalPrincipal);

                    arguments.Connection = BuildConnectionString(config);

                    using (var serviceProxy = new OrganizationServiceProxy(config.OrganizationUri, config.HomeRealmUri, config.Credentials, config.DeviceCredentials))
                    {
                        // This statement is required to enable early-bound type support.
                        serviceProxy.EnableProxyTypes();
                        serviceProxy.Timeout = new TimeSpan(1, 0, 0);
                        RunTask(arguments, serviceProxy, trace);
                    }
                }
                else if (arguments.Connection == "")
                {
                    // Support for tasks that require no connection string such as pack
                    RunTask(arguments, null, trace);
                }
                else
                {
                    // Does the connection contain a password prompt?
                    var passwordMatch = Regex.Match(arguments.Connection, "Password=[*]+", RegexOptions.IgnoreCase);
                    if (passwordMatch.Success)
                    {
                        // Prompt for password
                        Console.WriteLine("Password required for connection {0}", arguments.Connection);
                        Console.Write("Password:"******"Password="******"Error connecting to the Organization Service Proxy: {0}", serviceProxy.LastCrmError));
                        }

                        serviceProxy.OrganizationServiceProxy.Timeout = new TimeSpan(1, 0, 0);
                        if (!serviceProxy.IsReady)
                        {
                            trace.WriteLine("Not Ready {0} {1}", serviceProxy.LastCrmError, serviceProxy.LastCrmException);
                        }

                        RunTask(arguments, serviceProxy, trace);
                    }
                }
            }
            catch (CommandLineException exception)
            {
                Console.WriteLine(exception.ArgumentHelp.Message);
                Console.WriteLine(exception.ArgumentHelp.GetHelpText(Console.BufferWidth));
            }
        }
Exemplo n.º 10
0
        private static string BuildConnectionString(ServerConnection.Configuration config)
        {
            //string onlineRegion, organisationName;
            //bool isOnPrem;
            //Utilities.GetOrgnameAndOnlineRegionFromServiceUri(config.OrganizationUri, out onlineRegion, out organisationName, out isOnPrem);
            string connectionString;

            // On prem connection
            // AuthType = AD; Url = http://contoso:8080/Test;

            // AuthType=AD;Url=http://contoso:8080/Test; Domain=CONTOSO; Username=jsmith; Password=passcode

            // Office 365
            // AuthType = Office365; Username = [email protected]; Password = passcode; Url = https://contoso.crm.dynamics.com

            // IFD
            // AuthType=IFD;Url=http://contoso:8080/Test; HomeRealmUri=https://server-1.server.com/adfs/services/trust/mex/;Domain=CONTOSO; Username=jsmith; Password=passcode

            switch (config.EndpointType)
            {
            case AuthenticationProviderType.ActiveDirectory:
                connectionString = String.Format("AuthType=AD;Url={0}", config.OrganizationUri);

                break;

            case AuthenticationProviderType.Federation:
                connectionString = String.Format("AuthType=IFD;Url={0}", config.OrganizationUri);
                break;

            case AuthenticationProviderType.OnlineFederation:
                connectionString = String.Format("AuthType=Office365;Url={0}", config.OrganizationUri);
                break;

            default:
                throw new SparkleTaskException(SparkleTaskException.ExceptionTypes.AUTH_ERROR, String.Format("Unsupported Endpoint Type {0}", config.EndpointType.ToString()));
            }

            if (config.Credentials != null && config.Credentials.Windows != null)
            {
                if (!String.IsNullOrEmpty(config.Credentials.Windows.ClientCredential.Domain))
                {
                    connectionString += ";DOMAIN=" + config.Credentials.Windows.ClientCredential.Domain;
                }

                if (!String.IsNullOrEmpty(config.Credentials.Windows.ClientCredential.UserName))
                {
                    connectionString += ";Username="******";Password="******";Password="******";Username="******";Password="******";HomeRealmUri=" + config.HomeRealmUri.ToString();
            }

            return(connectionString);
        }
        /// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// creates a follow-up task activity when a new account is created.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    _serviceProxy.EnableProxyTypes();

                    #region Create XAML

                    // Define the workflow XAML.
                    string xamlWF = @"<?xml version=""1.0"" encoding=""utf-16""?>
                    <Activity x:Class=""FollowupWithAccount"" xmlns=""http://schemas.microsoft.com/netfx/2009/xaml/activities"" xmlns:mva=""clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:mxs=""clr-namespace:Microsoft.Xrm.Sdk;assembly=Microsoft.Xrm.Sdk, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:mxsw=""clr-namespace:Microsoft.Xrm.Sdk.Workflow;assembly=Microsoft.Xrm.Sdk.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:mxswa=""clr-namespace:Microsoft.Xrm.Sdk.Workflow.Activities;assembly=Microsoft.Xrm.Sdk.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:s=""clr-namespace:System;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:scg=""clr-namespace:System.Collections.Generic;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:srs=""clr-namespace:System.Runtime.Serialization;assembly=System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:this=""clr-namespace:"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
                        <x:Members>
                        <x:Property Name=""InputEntities"" Type=""InArgument(scg:IDictionary(x:String, mxs:Entity))"" />
                        <x:Property Name=""CreatedEntities"" Type=""InArgument(scg:IDictionary(x:String, mxs:Entity))"" />
                        </x:Members>
                        <this:FollowupWithAccount.InputEntities>
                        <InArgument x:TypeArguments=""scg:IDictionary(x:String, mxs:Entity)"" />
                        </this:FollowupWithAccount.InputEntities>
                        <this:FollowupWithAccount.CreatedEntities>
                        <InArgument x:TypeArguments=""scg:IDictionary(x:String, mxs:Entity)"" />
                        </this:FollowupWithAccount.CreatedEntities>
                        <mva:VisualBasic.Settings>Assembly references and imported namespaces for internal implementation</mva:VisualBasic.Settings>
                        <mxswa:Workflow>
                        <Sequence DisplayName=""CreateStep1"">
                            <Sequence.Variables>
                            <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_1"" />
                            <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_2"" />
                            <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_3"" />
                            <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_4"" />
                            <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_5"" />
                            <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_6"" />
                            <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_7"" />
                            <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_8"" />
                            <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_9"" />
                            <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_10"" />
                            <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_11"" />
                            <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_12"" />
                            <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_13"" />
                            <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_14"" />
                            <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_15"" />
                            <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_16"" />
                            <Variable x:TypeArguments=""mxsw:XrmTimeSpan"" Name=""CreateStep1_17"">
                                <Variable.Default>
                                <Literal x:TypeArguments=""mxsw:XrmTimeSpan"">
                                    <mxsw:XrmTimeSpan Days=""30"" Hours=""0"" Minutes=""0"" Months=""0"" Years=""0"" />
                                </Literal>
                                </Variable.Default>
                            </Variable>
                            <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_18"" />
                            <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_19"" />
                            </Sequence.Variables>
                            <Assign x:TypeArguments=""mxs:Entity"" To=""[CreatedEntities(&amp;quot;CreateStep1_localParameter#Temp&amp;quot;)]"" Value=""[New Entity(&amp;quot;task&amp;quot;)]"" />
                            <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression"">
                            <mxswa:ActivityReference.Arguments>
                                <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">CreateCrmType</InArgument>
                                <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { Microsoft.Xrm.Sdk.Workflow.WorkflowPropertyType.String, ""Send e-mail to the "", ""String"" }]</InArgument>
                                <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" />
                                </InArgument>
                                <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_2]</OutArgument>
                            </mxswa:ActivityReference.Arguments>
                            </mxswa:ActivityReference>
                            <mxswa:GetEntityProperty Attribute=""accountid"" Entity=""[InputEntities(&amp;quot;primaryEntity&amp;quot;)]"" EntityName=""account"" Value=""[CreateStep1_4]"">
                            <mxswa:GetEntityProperty.TargetType>
                                <InArgument x:TypeArguments=""s:Type"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" />
                                </InArgument>
                            </mxswa:GetEntityProperty.TargetType>
                            </mxswa:GetEntityProperty>
                            <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression"">
                            <mxswa:ActivityReference.Arguments>
                                <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">SelectFirstNonNull</InArgument>
                                <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_4 }]</InArgument>
                                <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" />
                                </InArgument>
                                <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_3]</OutArgument>
                            </mxswa:ActivityReference.Arguments>
                            </mxswa:ActivityReference>
                            <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression"">
                            <mxswa:ActivityReference.Arguments>
                                <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">CreateCrmType</InArgument>
                                <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { Microsoft.Xrm.Sdk.Workflow.WorkflowPropertyType.String, ""&amp;amp;#160;customer."", ""String"" }]</InArgument>
                                <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" />
                                </InArgument>
                                <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_5]</OutArgument>
                            </mxswa:ActivityReference.Arguments>
                            </mxswa:ActivityReference>
                            <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression"">
                            <mxswa:ActivityReference.Arguments>
                                <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">Add</InArgument>
                                <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_2, CreateStep1_3, CreateStep1_5 }]</InArgument>
                                <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" />
                                </InArgument>
                                <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_1]</OutArgument>
                            </mxswa:ActivityReference.Arguments>
                            </mxswa:ActivityReference>
                            <mxswa:SetEntityProperty Attribute=""subject"" Entity=""[CreatedEntities(&amp;quot;CreateStep1_localParameter#Temp&amp;quot;)]"" EntityName=""task"" Value=""[CreateStep1_1]"">
                            <mxswa:SetEntityProperty.TargetType>
                                <InArgument x:TypeArguments=""s:Type"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" />
                                </InArgument>
                            </mxswa:SetEntityProperty.TargetType>
                            </mxswa:SetEntityProperty>
                            <mxswa:GetEntityProperty Attribute=""accountid"" Entity=""[InputEntities(&amp;quot;primaryEntity&amp;quot;)]"" EntityName=""account"" Value=""[CreateStep1_7]"">
                            <mxswa:GetEntityProperty.TargetType>
                                <InArgument x:TypeArguments=""s:Type"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:EntityReference"" />
                                </InArgument>
                            </mxswa:GetEntityProperty.TargetType>
                            </mxswa:GetEntityProperty>
                            <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression"">
                            <mxswa:ActivityReference.Arguments>
                                <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">SelectFirstNonNull</InArgument>
                                <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_7 }]</InArgument>
                                <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:EntityReference"" />
                                </InArgument>
                                <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_6]</OutArgument>
                            </mxswa:ActivityReference.Arguments>
                            </mxswa:ActivityReference>
                            <mxswa:SetEntityProperty Attribute=""regardingobjectid"" Entity=""[CreatedEntities(&amp;quot;CreateStep1_localParameter#Temp&amp;quot;)]"" EntityName=""task"" Value=""[CreateStep1_6]"">
                            <mxswa:SetEntityProperty.TargetType>
                                <InArgument x:TypeArguments=""s:Type"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:EntityReference"" />
                                </InArgument>
                            </mxswa:SetEntityProperty.TargetType>
                            </mxswa:SetEntityProperty>
                            <mxswa:GetEntityProperty Attribute=""accountid"" Entity=""[InputEntities(&amp;quot;primaryEntity&amp;quot;)]"" EntityName=""account"" Value=""[CreateStep1_9]"">
                            <mxswa:GetEntityProperty.TargetType>
                                <InArgument x:TypeArguments=""s:Type"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" />
                                </InArgument>
                            </mxswa:GetEntityProperty.TargetType>
                            </mxswa:GetEntityProperty>
                            <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression"">
                            <mxswa:ActivityReference.Arguments>
                                <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">SelectFirstNonNull</InArgument>
                                <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_9 }]</InArgument>
                                <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" />
                                </InArgument>
                                <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_8]</OutArgument>
                            </mxswa:ActivityReference.Arguments>
                            </mxswa:ActivityReference>
                            <mxswa:SetEntityProperty Attribute=""category"" Entity=""[CreatedEntities(&amp;quot;CreateStep1_localParameter#Temp&amp;quot;)]"" EntityName=""task"" Value=""[CreateStep1_8]"">
                            <mxswa:SetEntityProperty.TargetType>
                                <InArgument x:TypeArguments=""s:Type"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" />
                                </InArgument>
                            </mxswa:SetEntityProperty.TargetType>
                            </mxswa:SetEntityProperty>
                            <mxswa:GetEntityProperty Attribute=""createdby"" Entity=""[InputEntities(&amp;quot;related_createdby#systemuser&amp;quot;)]"" EntityName=""systemuser"" Value=""[CreateStep1_11]"">
                            <mxswa:GetEntityProperty.TargetType>
                                <InArgument x:TypeArguments=""s:Type"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:EntityReference"" />
                                </InArgument>
                            </mxswa:GetEntityProperty.TargetType>
                            </mxswa:GetEntityProperty>
                            <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression"">
                            <mxswa:ActivityReference.Arguments>
                                <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">SelectFirstNonNull</InArgument>
                                <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_11 }]</InArgument>
                                <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:EntityReference"" />
                                </InArgument>
                                <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_10]</OutArgument>
                            </mxswa:ActivityReference.Arguments>
                            </mxswa:ActivityReference>
                            <mxswa:SetEntityProperty Attribute=""ownerid"" Entity=""[CreatedEntities(&amp;quot;CreateStep1_localParameter#Temp&amp;quot;)]"" EntityName=""task"" Value=""[CreateStep1_10]"">
                            <mxswa:SetEntityProperty.TargetType>
                                <InArgument x:TypeArguments=""s:Type"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:EntityReference"" />
                                </InArgument>
                            </mxswa:SetEntityProperty.TargetType>
                            </mxswa:SetEntityProperty>
                            <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression"">
                            <mxswa:ActivityReference.Arguments>
                                <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">CreateCrmType</InArgument>
                                <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { Microsoft.Xrm.Sdk.Workflow.WorkflowPropertyType.OptionSetValue, ""1"", ""Picklist"" }]</InArgument>
                                <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:OptionSetValue"" />
                                </InArgument>
                                <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_12]</OutArgument>
                            </mxswa:ActivityReference.Arguments>
                            </mxswa:ActivityReference>
                            <mxswa:SetEntityProperty Attribute=""prioritycode"" Entity=""[CreatedEntities(&amp;quot;CreateStep1_localParameter#Temp&amp;quot;)]"" EntityName=""task"" Value=""[CreateStep1_12]"">
                            <mxswa:SetEntityProperty.TargetType>
                                <InArgument x:TypeArguments=""s:Type"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:OptionSetValue"" />
                                </InArgument>
                            </mxswa:SetEntityProperty.TargetType>
                            </mxswa:SetEntityProperty>
                            <mxswa:GetEntityProperty Attribute=""createdon"" Entity=""[InputEntities(&amp;quot;primaryEntity&amp;quot;)]"" EntityName=""account"" Value=""[CreateStep1_16]"">
                            <mxswa:GetEntityProperty.TargetType>
                                <InArgument x:TypeArguments=""s:Type"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""s:DateTime"" />
                                </InArgument>
                            </mxswa:GetEntityProperty.TargetType>
                            </mxswa:GetEntityProperty>
                            <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression"">
                            <mxswa:ActivityReference.Arguments>
                                <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">SelectFirstNonNull</InArgument>
                                <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_16 }]</InArgument>
                                <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""s:DateTime"" />
                                </InArgument>
                                <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_15]</OutArgument>
                            </mxswa:ActivityReference.Arguments>
                            </mxswa:ActivityReference>
                            <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression"">
                            <mxswa:ActivityReference.Arguments>
                                <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">Add</InArgument>
                                <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_15, CreateStep1_17 }]</InArgument>
                                <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""s:DateTime"" />
                                </InArgument>
                                <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_14]</OutArgument>
                            </mxswa:ActivityReference.Arguments>
                            </mxswa:ActivityReference>
                            <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression"">
                            <mxswa:ActivityReference.Arguments>
                                <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">SelectFirstNonNull</InArgument>
                                <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_14 }]</InArgument>
                                <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""s:DateTime"" />
                                </InArgument>
                                <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_13]</OutArgument>
                            </mxswa:ActivityReference.Arguments>
                            </mxswa:ActivityReference>
                            <mxswa:SetEntityProperty Attribute=""scheduledend"" Entity=""[CreatedEntities(&amp;quot;CreateStep1_localParameter#Temp&amp;quot;)]"" EntityName=""task"" Value=""[CreateStep1_13]"">
                            <mxswa:SetEntityProperty.TargetType>
                                <InArgument x:TypeArguments=""s:Type"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""s:DateTime"" />
                                </InArgument>
                            </mxswa:SetEntityProperty.TargetType>
                            </mxswa:SetEntityProperty>
                            <mxswa:GetEntityProperty Attribute=""createdon"" Entity=""[InputEntities(&amp;quot;primaryEntity&amp;quot;)]"" EntityName=""account"" Value=""[CreateStep1_19]"">
                            <mxswa:GetEntityProperty.TargetType>
                                <InArgument x:TypeArguments=""s:Type"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""s:DateTime"" />
                                </InArgument>
                            </mxswa:GetEntityProperty.TargetType>
                            </mxswa:GetEntityProperty>
                            <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression"">
                            <mxswa:ActivityReference.Arguments>
                                <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">SelectFirstNonNull</InArgument>
                                <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_19 }]</InArgument>
                                <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""s:DateTime"" />
                                </InArgument>
                                <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_18]</OutArgument>
                            </mxswa:ActivityReference.Arguments>
                            </mxswa:ActivityReference>
                            <mxswa:SetEntityProperty Attribute=""scheduledstart"" Entity=""[CreatedEntities(&amp;quot;CreateStep1_localParameter#Temp&amp;quot;)]"" EntityName=""task"" Value=""[CreateStep1_18]"">
                            <mxswa:SetEntityProperty.TargetType>
                                <InArgument x:TypeArguments=""s:Type"">
                                <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""s:DateTime"" />
                                </InArgument>
                            </mxswa:SetEntityProperty.TargetType>
                            </mxswa:SetEntityProperty>
                            <mxswa:CreateEntity EntityId=""{x:Null}"" DisplayName=""CreateStep1"" Entity=""[CreatedEntities(&amp;quot;CreateStep1_localParameter#Temp&amp;quot;)]"" EntityName=""task"" />
                            <Assign x:TypeArguments=""mxs:Entity"" To=""[CreatedEntities(&amp;quot;CreateStep1_localParameter&amp;quot;)]"" Value=""[CreatedEntities(&amp;quot;CreateStep1_localParameter#Temp&amp;quot;)]"" />
                            <Persist />
                        </Sequence>
                        </mxswa:Workflow>
                    </Activity>";

                    #endregion Create XAML

                    #region Create Workflow

                    // Create the workflow.
                    Workflow workflow = new Workflow()
                    {
                        Name            = "SampleFollowupWithAccountWorkflow",
                        Type            = new OptionSetValue((int)WorkflowType.Definition),
                        Category        = new OptionSetValue((int)WorkflowCategory.Workflow),
                        Scope           = new OptionSetValue((int)WorkflowScope.User),
                        LanguageCode    = 1033,             // U.S. English
                        TriggerOnCreate = true,
                        OnDemand        = true,
                        PrimaryEntity   = Account.EntityLogicalName,
                        Description     = @"Follow up with the customer. Check if there are any new issues that need resolution.",
                        Xaml            = xamlWF
                    };
                    _workflowId = _serviceProxy.Create(workflow);

                    Console.WriteLine("Created Workflow: " + workflow.Name);

                    #endregion Create Workflow

                    #region Activate Workflow

                    // Activate the workflow.
                    var activateRequest = new SetStateRequest
                    {
                        EntityMoniker = new EntityReference
                                            (Workflow.EntityLogicalName, _workflowId),
                        State  = new OptionSetValue((int)WorkflowState.Activated),
                        Status = new OptionSetValue((int)workflow_statuscode.Activated)
                    };
                    _serviceProxy.Execute(activateRequest);
                    Console.WriteLine("Activated Workflow: " + workflow.Name);

                    #endregion Activate Workflow

                    #region Create Account Record

                    CreateRequiredRecords();

                    #endregion Create Account Record

                    DeleteRequiredRecords(promptforDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Create a referral request.
        /// </summary>

        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetMarketingAutomation1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    Practitioner practioner = new Practitioner();

                    Entity referralRequest = new Entity("msemr_referralrequest");

                    //Primary Field
                    referralRequest["msemr_name"] = "Andrea Leonardo";

                    //Setting context type as encounter
                    referralRequest["msemr_contexttype"] = new OptionSetValue(935000000); //Encounter
                    Guid subjectcontextencounterId = Encounter.GetEncounterId(_serviceProxy, "E23556");
                    if (subjectcontextencounterId != Guid.Empty)
                    {
                        referralRequest["msemr_subjectcontextencounter"] = new EntityReference("msemr_encounter", subjectcontextencounterId);
                    }
                    Guid encounterId = Encounter.GetEncounterId(_serviceProxy, "E23556");
                    if (encounterId != Guid.Empty)
                    {
                        referralRequest["msemr_initiatingencounter"] = new EntityReference("msemr_encounter", encounterId);
                    }

                    //Setting requester agent as Practitioner
                    referralRequest["msemr_requesteragent"] = new OptionSetValue(935000000); //Practitioner
                    Guid requesteragentpractitionerContactId = SDKFunctions.GetContactId(_serviceProxy, "Daniel Atlas");
                    if (requesteragentpractitionerContactId != Guid.Empty)
                    {
                        referralRequest["msemr_requesteragentpractitioner"] = new EntityReference("contact", requesteragentpractitionerContactId);
                    }

                    Guid requesteronbehalfofAccountId = Organization.GetAccountId(_serviceProxy, "Galaxy Corp");
                    if (requesteronbehalfofAccountId != Guid.Empty)
                    {
                        referralRequest["msemr_requesteronbehalfof"] = new EntityReference("account", requesteronbehalfofAccountId);
                    }

                    Guid requestorContactId = SDKFunctions.GetContactId(_serviceProxy, "James Kirk");
                    if (requestorContactId != Guid.Empty)
                    {
                        referralRequest["msemr_requestor"] = new EntityReference("contact", requestorContactId);
                    }

                    referralRequest["msemr_occurenceperiodstartdate"] = DateTime.Now;
                    referralRequest["msemr_occurenceperiodenddate"]   = DateTime.Now;
                    referralRequest["msemr_occurrencedate"]           = DateTime.Now;
                    referralRequest["msemr_occurrencetype"]           = new OptionSetValue(935000000); //Date

                    referralRequest["msemr_authoredon"] = DateTime.Now;

                    Guid typeCodeableConceptId = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Referral Request", 935000094);
                    if (typeCodeableConceptId != Guid.Empty)
                    {
                        referralRequest["msemr_type"] = new EntityReference("msemr_codeableconcept", typeCodeableConceptId);
                    }

                    Guid basedonreferralId = SDKFunctions.GetReferralRequestId(_serviceProxy, "Ref452");
                    if (basedonreferralId != Guid.Empty)
                    {
                        referralRequest["msemr_basedonreferral"] = new EntityReference("msemr_referralrequest", basedonreferralId);
                    }

                    Guid practitionerspecialtyCodeableConceptId = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Psychiatric", 935000101);
                    if (practitionerspecialtyCodeableConceptId != Guid.Empty)
                    {
                        referralRequest["msemr_practitionerspecialty"] = new EntityReference("msemr_codeableconcept", practitionerspecialtyCodeableConceptId);
                    }

                    referralRequest["msemr_priority"] = new OptionSetValue(935000000); //Routine

                    referralRequest["msemr_intent"] = new OptionSetValue(935000000);   //Proposal

                    referralRequest["msemr_subject"] = new OptionSetValue(935000000);  //Patient

                    Guid subjectpatientContactId = SDKFunctions.GetContactId(_serviceProxy, "Emily Williams");
                    if (subjectpatientContactId != Guid.Empty)
                    {
                        referralRequest["msemr_subjectpatient"] = new EntityReference("contact", subjectpatientContactId);
                    }

                    referralRequest["msemr_status"] = new OptionSetValue(935000000); //Draft

                    referralRequest["msemr_description"] = "";

                    referralRequest["msemr_referralrequestnumber"] = "Ref452";

                    referralRequest["msemr_groupidentifier"] = "";

                    Guid referralRequestId = _serviceProxy.Create(referralRequest);

                    // Verify that the record has been created.
                    if (referralRequestId != Guid.Empty)
                    {
                        Console.WriteLine("Succesfully created {0}.", referralRequestId);
                    }
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Create a medication.
        /// </summary>

        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetMarketingAutomation1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    Entity product = new Entity("product");

                    product["name"] = "Paracetamol";

                    Guid medicationcodeCodeableConceptId = SDKFunctions.GetCodeableConceptId(_serviceProxy, "HCPCS", 935000076);
                    if (medicationcodeCodeableConceptId != Guid.Empty)
                    {
                        product["msemr_medicationcode"] = new EntityReference("msemr_codeableconcept", medicationcodeCodeableConceptId);
                    }

                    Guid formCodeableConceptId = SDKFunctions.GetCodeableConceptId(_serviceProxy, "1095-C", 935000058);
                    if (formCodeableConceptId != Guid.Empty)
                    {
                        product["msemr_form"] = new EntityReference("msemr_codeableconcept", formCodeableConceptId);
                    }

                    Guid packagecontainerCodeableConceptId = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Blister pack", 935000077);
                    if (packagecontainerCodeableConceptId != Guid.Empty)
                    {
                        product["msemr_packagecontainer"] = new EntityReference("msemr_codeableconcept", packagecontainerCodeableConceptId);
                    }

                    Guid defaultUnitId = GetDefaultUnit(_serviceProxy, "Primary Unit");
                    if (defaultUnitId != Guid.Empty)
                    {
                        product["defaultuomid"] = new EntityReference("uom", defaultUnitId);
                    }

                    Guid unitGroupId = GetUnitGroup(_serviceProxy, "Default Unit");
                    if (unitGroupId != Guid.Empty)
                    {
                        product["defaultuomscheduleid"] = new EntityReference("uomschedule", unitGroupId);
                    }

                    product["msemr_isoverthecounter"] = true;

                    product["msemr_isbrand"] = true;

                    Guid productid = _serviceProxy.Create(product);

                    // Verify that the record has been created.
                    if (productid != Guid.Empty)
                    {
                        Console.WriteLine("Succesfully created {0}.", productid);
                    }
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Create a healthcare service.
        /// </summary>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetMarketingAutomation1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    Entity healthcareService = new Entity("msemr_healthcareservice");

                    healthcareService["msemr_name"] = "Surgical Treatment";

                    healthcareService["msemr_appointmentrequired"] = true;

                    healthcareService["msemr_availabilityexceptions"] = "Public holiday availability";

                    healthcareService["msemr_comment"] = "More details";

                    healthcareService["msemr_healthcareservice"] = "Healthcare Service";

                    healthcareService["msemr_extradetails"] = "Extra Details";

                    healthcareService["msemr_notavailableduringenddatetime"]   = DateTime.Now;
                    healthcareService["msemr_notavailableduringstartdatetime"] = DateTime.Now;
                    healthcareService["msemr_notavailabledescription"]         = "Machine failure";

                    healthcareService["msemr_eligibilitynote"] = "Eligibility Note";
                    Guid eligibilityCodeableConceptId = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Eligibile", 935000132);
                    if (eligibilityCodeableConceptId != Guid.Empty)
                    {
                        healthcareService["msemr_eligibility"] = new EntityReference("msemr_codeableconcept", eligibilityCodeableConceptId);
                    }

                    Guid providedbyAccountId = Organization.GetAccountId(_serviceProxy, "Galaxy Corp");
                    if (providedbyAccountId != Guid.Empty)
                    {
                        healthcareService["msemr_providedby"] = new EntityReference("account", providedbyAccountId);
                    }

                    Guid categoryCodeableConceptId = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Category", 935000129);
                    if (categoryCodeableConceptId != Guid.Empty)
                    {
                        healthcareService["msemr_category"] = new EntityReference("msemr_codeableconcept", categoryCodeableConceptId);
                    }

                    Guid healthcareServiceId = _serviceProxy.Create(healthcareService);

                    // Verify that the record has been created.
                    if (healthcareServiceId != Guid.Empty)
                    {
                        Console.WriteLine("Succesfully created {0}.", healthcareServiceId);
                    }
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Create an observation.
        /// </summary>

        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetMarketingAutomation1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    Entity observation = new Entity("msemr_observation");

                    observation["msemr_identifier"]  = "OBS-123";
                    observation["msemr_comment"]     = "following Schedule";
                    observation["msemr_description"] = "Recovery is good";
                    observation["msemr_status"]      = new OptionSetValue(935000000);

                    //Setting Context Type as Encounter
                    observation["msemr_contexttype"] = new OptionSetValue(935000001); //Encounter
                    Guid EncounterId = Encounter.GetEncounterId(_serviceProxy, "E23556");
                    if (EncounterId != Guid.Empty)
                    {
                        observation["msemr_conexttypeencounter"] = new EntityReference("msemr_encounter", EncounterId);
                    }

                    //Setting Device Type as Device Metric
                    observation["msemr_devicetype"] = new OptionSetValue(935000001);
                    Guid DeviceMetricId = SDKFunctions.GetDeviceMetricId(_serviceProxy, "Device Metric");
                    if (DeviceMetricId != Guid.Empty)
                    {
                        observation["msemr_devicetypedevicemetric"] = new EntityReference("msemr_device", DeviceMetricId);
                    }

                    //Setting Effictive as DateTime
                    observation["msemr_effectivetype"]         = new OptionSetValue(935000000); //DateTime
                    observation["msemr_effectivetypedatetime"] = DateTime.Now;

                    //Setting Subject Type as Device
                    observation["msemr_subjecttype"] = new OptionSetValue(935000002);//Device
                    Guid SubjectTypeDevice = Device.GetDeviceId(_serviceProxy, "Pacemaker");
                    if (SubjectTypeDevice != Guid.Empty)
                    {
                        observation["msemr_subjecttypedevice"] = new EntityReference("msemr_device", SubjectTypeDevice);
                    }


                    //Setting Value Type as Range
                    observation["msemr_valuetype"]           = new OptionSetValue(935000004); //Range
                    observation["msemr_valuerangehighlimit"] = 10;
                    observation["msemr_valuerangelowlimit"]  = 1;


                    Guid BodySite = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Body Site", 100000000);
                    if (BodySite != Guid.Empty)
                    {
                        observation["msemr_bodysite"] = new EntityReference("msemr_codeableconcept", BodySite);
                    }
                    Guid Code = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Observation Name", 935000073);
                    if (Code != Guid.Empty)
                    {
                        observation["msemr_code"] = new EntityReference("msemr_codeableconcept", Code);
                    }

                    Guid EpisodeOfCareId = EpisodeOfCare.GetEpisodeOfCareId(_serviceProxy, "EPC-153");
                    if (EpisodeOfCareId != Guid.Empty)
                    {
                        observation["msemr_episodeofcare"] = new EntityReference("msemr_episodeofcare", EpisodeOfCareId);
                    }
                    Guid DataAbsentReason = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Absent Reason", 935000090);
                    if (DataAbsentReason != Guid.Empty)
                    {
                        observation["msemr_dataabsentreason"] = new EntityReference("msemr_codeableconcept", DataAbsentReason);
                    }
                    Guid DeviceId = Device.GetDeviceId(_serviceProxy, "MAGNETOM Sola");
                    if (DeviceId != Guid.Empty)
                    {
                        observation["msemr_device"] = new EntityReference("msemr_device", DeviceId);
                    }
                    Guid Interpretation = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Interpretation Code", 935000085);
                    if (Interpretation != Guid.Empty)
                    {
                        observation["msemr_interpretation"] = new EntityReference("msemr_codeableconcept", Interpretation);
                    }
                    observation["msemr_issueddate"] = DateTime.Now;
                    Guid Method = SDKFunctions.GetCodeableConceptId(_serviceProxy, "Interpretation Code", 935000086);
                    if (Method != Guid.Empty)
                    {
                        observation["msemr_method"] = new EntityReference("msemr_codeableconcept", Method);
                    }
                    observation["msemr_observationnumber"] = "OBS-123";
                    Guid SpecimenId = SDKFunctions.GetSpecimenId(_serviceProxy, "SP-1234");
                    if (SpecimenId != Guid.Empty)
                    {
                        observation["msemr_specimen"] = new EntityReference("msemr_specimen", SpecimenId);
                    }


                    Guid ObservationId = _serviceProxy.Create(observation);

                    // Verify that the record has been created.
                    if (ObservationId != Guid.Empty)
                    {
                        Console.WriteLine("Succesfully created {0}.", ObservationId);
                    }
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }