public string RetrieveObjectId(string propertyName, string value, string objectType)
        {
            var request = new RetrieveRequest
            {
                ClientIDs = _config.ClientId.HasValue
                            ? new[] { new ClientID { ID = _config.ClientId.Value, IDSpecified = true } }
                            : null,
                ObjectType = objectType,
                Properties = new[] { "Name", "ObjectID", "CustomerKey" },
                Filter = new SimpleFilterPart
                {
                    Property = propertyName,
                    SimpleOperator = SimpleOperators.@equals,
                    Value = new[] { value }
                }
            };

            string requestId;
            APIObject[] results;

            _client.Retrieve(request, out requestId, out results);

            if (results != null && results.Any())
            {
                return results.First().ObjectID;
            }

            return string.Empty;
        }
        public static void RetrieveImportResultsSummary(SoapClient soapClient,
            string TaskID)
        {
            RetrieveRequest rr = new RetrieveRequest();

            rr.ObjectType = "ImportResultsSummary";

            SimpleFilterPart sf = new SimpleFilterPart();
            sf.Property = "TaskResultID";
            sf.SimpleOperator = SimpleOperators.equals;
            sf.Value = new String[] { TaskID };
            rr.Filter = sf;

            rr.Properties = new string[] { "ImportStatus" };

            string sStatus = "";
            string sRequestId = "";
            APIObject[] rResults;

            sStatus = soapClient.Retrieve(rr, out sRequestId, out rResults);

            Console.WriteLine("Status: " + sStatus);
            Console.WriteLine("RequestID: " + sRequestId);

            foreach (ImportResultsSummary irs in rResults)
            {
                // Possible values for ImportStatus are New, Processing, Completed, Error, IOWork, and Unknown
                Console.WriteLine("ImportStatus: " + irs.ImportStatus);
            }
        }
        public void descargaOpen(String jobid, BackgroundWorker bgw)
        {
            EmailInfo einf = new EmailInfo();
            Send objSend = einf.getEmailInformationOpenSent(jobid);
            double deci = Convert.ToDouble(objSend.UniqueOpens);
            Conexion conex =new Conexion();

            RetrieveRequest rr = new RetrieveRequest();
            rr.ObjectType = "OpenEvent";

            String[] props = { "SubscriberKey" };
            rr.Properties = props;
            /**
            * Details for single JobId/SendId
            */
            SimpleFilterPart filter = new SimpleFilterPart();
            filter.Property = "SendID";
            String[] vlaues = { jobid + " " };
            filter.Value = vlaues;

            rr.Filter = filter;

            APIObject[] results = null;
            String requestId = null;
            String status;
            List<String> lista = new List<String>();
            int k = 0;
            int porcentaje;

            do
            {
                status = conex.cliente.Retrieve(rr, out requestId, out results);
                for (int i = 0; i < results.Length; i++)
                {
                    OpenEvent deo = results[i] as OpenEvent;
                    string parte3 = deo.SubscriberKey;
                    var newLine = string.Format("{0}", parte3);
                    lista.Add(newLine);
                    porcentaje = Convert.ToInt32((k / deci) * 100);
                    if (porcentaje > 100) porcentaje = 100;
                    bgw.ReportProgress(porcentaje);
                    k++;
                }
                rr = new RetrieveRequest();
                rr.ContinueRequest = requestId;
                System.Console.Out.WriteLine("Procesando....");
                System.Console.Out.WriteLine(results.Length);
            } while (status.Equals("MoreDataAvailable"));
            List<String> sinDup = lista.Distinct().ToList();
            System.Console.Out.WriteLine("Descarga Completa!");
            StreamWriter file = new StreamWriter(@"D:\ET_EXTRACTOR\Open_" + jobid + ".txt", true);
            System.Console.Out.WriteLine("Formateando");
            for (int j = 0; j < sinDup.Count; j++)
            {
                file.WriteLine(sinDup.ElementAt(j));
            }
            file.Close();
            bgw.ReportProgress(0);
        }
Exemple #4
0
        public void RetrieveFolderStructure(string id, ET_Client etClient, string contentType, string path)
        {
            // Create the SOAP binding for call.
                BasicHttpBinding binding = new BasicHttpBinding();
                binding.Name = "UserNameSoapBinding";
                binding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential;
                binding.MaxReceivedMessageSize = 2147483647;
                var client = new FuelSDK.SoapClient(binding, etClient.soapclient.Endpoint.Address);
                client.ClientCredentials.UserName.UserName = "******";
                client.ClientCredentials.UserName.Password = "******";

                using (var scope = new OperationContextScope(client.InnerChannel))
                {
                    // Add oAuth token to SOAP header.
                    XNamespace ns = "http://exacttarget.com";
                    var oauthElement = new XElement(ns + "oAuthToken", etClient.internalAuthToken);
                    var xmlHeader = MessageHeader.CreateHeader("oAuth", "http://exacttarget.com", oauthElement);
                    OperationContext.Current.OutgoingMessageHeaders.Add(xmlHeader);

                    List<object> folders = new List<object>();

                    String requestID;
                    String status;
                    APIObject[] results;

                    SimpleFilterPart sfp = new SimpleFilterPart();
                    sfp.Property = "ContentType";
                    sfp.SimpleOperator = SimpleOperators.equals;
                    sfp.Value = new string[] { contentType };

                    SimpleFilterPart rf = new SimpleFilterPart();
                    rf.Property = "ParentFolder.ID";
                    rf.SimpleOperator = SimpleOperators.equals;
                    rf.Value = new string[] { id };

                    ComplexFilterPart cfp = new ComplexFilterPart();
                    cfp.LeftOperand = sfp;
                    cfp.LogicalOperator = LogicalOperators.AND;
                    cfp.RightOperand = rf;

                    RetrieveRequest rr = new RetrieveRequest();

                    rr.ObjectType = "DataFolder";
                    rr.Properties = new string[] { "ID", "Name", "ParentFolder.ID", "ParentFolder.Name" };
                    rr.Filter = cfp;

                    status = client.Retrieve(rr, out requestID, out results);

                    if (results.Count() > 0)
                    {
                        foreach (DataFolder df in results)
                        {
                            RetrieveObjectsByFolderID(df.ID.ToString(), etClient, path + "/" + df.Name + "/", contentType);
                            RetrieveFolderStructure(df.ID.ToString(), etClient, contentType, path + "/" + df.Name + "/");
                        }
                    }
                }
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();

            //Create an Organization Service
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.InitiatingUserId);

            //Retrieve the contact id
            Guid contactId = this.Contact.Get(executionContext).Id;

            //<snippetReleaseISVActivities1>
            //Create the request
            RetrieveRequest request = new RetrieveRequest();
            request.ColumnSet = new ColumnSet(new string[] { "birthdate" });
            request.Target = new EntityReference(EntityName.Contact, contactId);

            //Retrieve the entity to determine what the birthdate is set at
            Entity entity = (Entity)((RetrieveResponse)service.Execute(request)).Entity;
            //</snippetReleaseISVActivities1>

            //Extract the date out of the entity
            DateTime? birthdate;
            if (entity.Contains(ContactAttributes.Birthdate))
            {
                birthdate = (DateTime?)entity[ContactAttributes.Birthdate];
            }
            else
            {
                birthdate = null;
            }

            //Check to see if the current birthday is set. We don't want the activity to fail if the birthdate is not set
            if (birthdate == null)
            {
                return;
            }

            //Calculate the next birthdate. Encapsulated in a methdo so that the method can be used in the test case for verification purposes
            DateTime nextBirthdate = CalculateNextBirthday(birthdate.Value);

            //Update the next birthday field on the entity
            Entity updateEntity = new Entity(EntityName.Contact);
            updateEntity.Id = contactId;
            updateEntity["new_nextbirthday"] = nextBirthdate;

            service.Update(updateEntity);
        }
        // Externally callabled methods
        /// <summary>
        /// Associate an email activity with a GovDelivery email by writing the email ID into a field on the entity
        /// </summary>
        /// <returns></returns>
        public void AssociateGovdeliveryEmail(string id, string govdId)
        {
            RetrieveRequest emailRequest = new RetrieveRequest()
            {
                ColumnSet = new ColumnSet("govd_id"),
                Target = new EntityReference("email", new Guid(id))
            };

            var email = retrieveEntity(emailRequest);
            email["govd_id"] = govdId;

            UpdateRequest updateEmail = new UpdateRequest()
            {
                Target = email
            };
            this.getService().Execute(updateEmail);
        }
        public static void RetrieveAutomation(SoapClient soapClient,
            string iAutomationCustomerKey)
        {
            RetrieveRequest rr = new RetrieveRequest();
            rr.ObjectType = "Automation";

            SimpleFilterPart sf = new SimpleFilterPart();
            sf.Property = "CustomerKey";
            sf.SimpleOperator = SimpleOperators.equals;
            sf.Value = new String[] { iAutomationCustomerKey };
            rr.Filter = sf;

            rr.Properties = new string[] { "ObjectID", "Name", "Description", "Schedule.ID", "CustomerKey",  "IsActive", "CreatedDate",  "ModifiedDate", "Status"};

            string sStatus = "";
            string sRequestId = "";
            APIObject[] rResults;

            sStatus = soapClient.Retrieve(rr, out sRequestId, out rResults);

            Console.WriteLine("Status: " + sStatus);
            Console.WriteLine("RequestID: " + sRequestId);

            foreach (Automation automation in rResults)
            {
                Console.WriteLine("ObjectID: " + automation.ObjectID);
                Console.WriteLine("Name: " + automation.Name);
                Console.WriteLine("Description: " + automation.Description);
                if (automation.Schedule != null)
                {
                    Console.WriteLine("Schedule.ID: " + automation.Schedule.ID);
                }
                Console.WriteLine("CustomerKey: " + automation.CustomerKey);
                Console.WriteLine("IsActive: " + automation.IsActive);
                Console.WriteLine("CreatedDate: " + automation.CreatedDate.ToString());
                Console.WriteLine("ModifiedDate: " + automation.ModifiedDate);
                Console.WriteLine("Status: " + automation.Status);
            }
        }
        public int RetrieveEmailTemplateId(string externalKey)
        {
            var request = new RetrieveRequest
            {
                ClientIDs = _config.ClientId.HasValue
                    ? new[] { new ClientID { ID = _config.ClientId.Value, IDSpecified = true } }
                    : null,
                ObjectType = "Template",
                Properties = new[] { "ID", "TemplateName", "ObjectID", "CustomerKey" },
                Filter = new SimpleFilterPart
                {
                    Property = "CustomerKey",
                    SimpleOperator = SimpleOperators.@equals,
                    Value = new[] { externalKey }
                }
            };

            string requestId;
            APIObject[] results;
            _client.Retrieve(request, out requestId, out results);

            return results != null && results.Any() ? results.First().ID : 0;
        }
Exemple #9
0
        public Send getEmailInformationOpenSent(String jobid)
        {
            Conexion conex = new Conexion();

            RetrieveRequest rr = new RetrieveRequest();
            rr.ObjectType = "Send";

            String[] props = { "UniqueOpens", "NumberSent" };
            rr.Properties = props;

            SimpleFilterPart filter = new SimpleFilterPart();
            filter.Property = "ID";
            String[] vlaues = { jobid + " " };
            filter.Value = vlaues;

            rr.Filter = filter;

            APIObject[] results = null;
            String requestId = null;
            String status;
            List<String> lista = new List<String>();
            Send obj=null;
            status = conex.cliente.Retrieve(rr, out requestId, out results);

            while (status.CompareTo("OK") != 0)
            {
                status = conex.cliente.Retrieve(rr, out requestId, out results);

            }

            for (int i = 0; i < results.Length; i++)
            {
                  Send deo = results[i] as Send;
                  obj = deo;
            }
            return obj;
        }
        public static void RetrieveSend(SoapClient soapClient,
            string JobID)
        {
            RetrieveRequest rr = new RetrieveRequest();

            rr.ObjectType = "Send";

            SimpleFilterPart sf = new SimpleFilterPart();
            sf.Property = "ID";
            sf.SimpleOperator = SimpleOperators.equals;
            sf.Value = new String[] { JobID };
            rr.Filter = sf;

            rr.Properties = new string[] { "ID", "SendDate", "NumberSent", "NumberDelivered", "HardBounces", "SoftBounces", "OtherBounces", "Unsubscribes", "Status" };

            string sStatus = "";
            string sRequestId = "";
            APIObject[] rResults;

            sStatus = soapClient.Retrieve(rr, out sRequestId, out rResults);

            Console.WriteLine("Status: " + sStatus);
            Console.WriteLine("RequestID: " + sRequestId);

            foreach (Send s in rResults)
            {
                Console.WriteLine("ID (JobID): " + s.ID);
                Console.WriteLine("SendDate: " + s.SendDate.ToString());
                Console.WriteLine("NumberSent: " + s.NumberSent);
                Console.WriteLine("NumberDelivered: " + s.NumberDelivered);
                Console.WriteLine("SoftBounces: " + s.SoftBounces);
                Console.WriteLine("OtherBounces: " + s.OtherBounces);
                Console.WriteLine("Unsubscribes: " + s.Unsubscribes);
                Console.WriteLine("Status: " + s.Status);
            }
        }
Exemple #11
0
        /// <summary>
        /// This method first retrieves the lead. Afterwards, it checks the value of
        /// the new_autoroute field, and if it is True, it retrieves all the users 
        /// with 'Customer Service Representative' role, and assigns this lead to
        /// the user with the fewest lead records assigned.
        /// </summary>
        protected override void Execute(CodeActivityContext executionContext)
        {
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = 
                executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = 
                serviceFactory.CreateOrganizationService(context.UserId);

            #region Retrieve the lead
            
            // Get the lead ID
            Guid leadId = this.lead_input.Get(executionContext).Id;
            
            //Request for Entity
            RetrieveRequest request = new RetrieveRequest();
            request.ColumnSet = new ColumnSet(true);
            request.Target = new EntityReference("lead", leadId);
            
            //Execute request
            Entity targetRequest = 
                (Entity)((RetrieveResponse)service.Execute(request)).Entity;

            #endregion Retrieve the lead

            bool autoroute = false;
            autoroute = (bool)targetRequest.Attributes["new_autoroute"];

            if (autoroute)
            {
                // Get user's BusinessUnit
                RetrieveRequest userrequest = new RetrieveRequest();
                userrequest.ColumnSet = new ColumnSet("businessunitid");
                userrequest.Target = new EntityReference("systemuser", context.UserId);

                Entity userEntity = 
                    (Entity)((RetrieveResponse)service.Execute(userrequest)).Entity;
                EntityReference bu = (EntityReference)userEntity["businessunitid"];
                
                // Get roleid for 'Customer Service Representative' with that BU
                QueryExpression queryRole = new QueryExpression();
                queryRole.ColumnSet = new ColumnSet("roleid");
                queryRole.EntityName = "role";
                queryRole.Criteria.AddCondition(new ConditionExpression
                {
                    AttributeName = "name",
                    Operator = ConditionOperator.Equal,
                    Values = { "Customer Service Representative" }
                });
                queryRole.Criteria.AddCondition(new ConditionExpression
                {
                    AttributeName = "businessunitid",
                    Operator = ConditionOperator.Equal,
                    Values = { bu.Id }
                });

                var roles = service.RetrieveMultiple(queryRole);

                if (roles.Entities.Count > 0)
                {
                    Guid roleId = (Guid)roles.Entities[0]["roleid"];

                    // Create the query to get all the users with that role
                    QueryExpression queryUsers = new QueryExpression();

                    // Set the properties of the query.
                    queryUsers.EntityName = "systemuserroles";
                    queryUsers.ColumnSet = new ColumnSet("systemuserid");
                    queryUsers.Criteria.AddCondition
                        ("roleid", ConditionOperator.Equal, roleId);

                    // Get the list of users.
                    var users = service.RetrieveMultiple(queryUsers);

                    if (users.Entities.Count > 0)
                    {
                        #region Get User with lowest number of leads assigned

                        // Initialize variables
                        int lowLeadCount = -1;
                        int currentLeadCount = 0;
                        Guid lowUserId = new Guid();

                        // Create the query to find out how many leads 
                        // each retrieved user has
                        QueryExpression queryUsersLeads = new QueryExpression();

                        // Set the properties of the query.
                        queryUsersLeads.EntityName = "lead";
                        queryUsersLeads.ColumnSet = new ColumnSet("leadid", "ownerid");
                        
                        foreach (var user in users.Entities)
                        {
                            queryUsersLeads.Criteria.AddCondition
                                ("ownerid", ConditionOperator.Equal, user["systemuserid"]);
                            EntityCollection currentUserLeads = 
                                service.RetrieveMultiple(queryUsersLeads);
                            currentLeadCount = currentUserLeads.Entities.Count;

                            // If is the first time or the number of leads is lowest, 
                            // the current User is marked lowest.
                            if ((lowLeadCount == -1) || (currentLeadCount < lowLeadCount))
                            {
                                lowLeadCount = currentLeadCount;
                                lowUserId = (Guid)user["systemuserid"];
                            }
                            
                        }
                        #endregion Get User with Lowest Number of leads assigned

                        #region Assign new lead to identified user

                        // Assign the lead to the user 
                        // with the fewest lead records assigned
                        AssignRequest assignRequest = new AssignRequest()
                        {
                            Target = new EntityReference("lead", leadId),
                            Assignee = new EntityReference("systemuser", lowUserId)
                        };
                        service.Execute(assignRequest);
                        
                        #endregion Assign new lead to identified user
                    }
                }
            }
        }
Exemple #12
0
        /// <summary>
        /// Demonstrates how to use the Deployment Web Service to create an organization
        /// and poll the status of the job.
        /// </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 = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords(serverConfig, promptforDelete);

                    //<snippetUseAsyncDeploymentServiceMessages1>
                    // Instantiate DeploymentServiceClient for calling the service.
                    client =
                        ProxyClientHelper.CreateClient(
                            new Uri(serverConfig.DiscoveryUri.ToString()
                                    .Replace("Services", "Deployment")
                                    .Replace("Discovery", "Deployment")));

                    // Setting credentials from the current security context.
                    if (serverConfig.Credentials == null)
                    {
                        client.ClientCredentials.Windows.ClientCredential =
                            CredentialCache.DefaultNetworkCredentials;
                    }
                    else
                    {
                        client.ClientCredentials.Windows.ClientCredential =
                            serverConfig.Credentials.Windows.ClientCredential;
                    }

                    using (client)
                    {
                        // Set properties for the new organization
                        Microsoft.Xrm.Sdk.Deployment.Organization organization =
                            new Microsoft.Xrm.Sdk.Deployment.Organization
                        {
                            BaseCurrencyCode      = "USD",
                            BaseCurrencyName      = "US Dollar",
                            BaseCurrencyPrecision = 2,
                            BaseCurrencySymbol    = "$",
                            BaseLanguageCode      = 1033,
                            FriendlyName          = _friendlyName,
                            UniqueName            = _uniqueName,
                            SqlCollation          = "Latin1_General_CI_AI",
                            SqlServerName         = _sqlServerName,
                            SrsUrl       = _srsUrl,
                            SqmIsEnabled = false
                        };

                        // Create a request for the deployment web service
                        // CRM server app pool must have permissions on SQL server
                        BeginCreateOrganizationRequest request =
                            new BeginCreateOrganizationRequest
                        {
                            Organization = organization,
                            SysAdminName = _sysAdminName
                        };

                        // Execute the request
                        BeginCreateOrganizationResponse response =
                            (BeginCreateOrganizationResponse)client.Execute(request);

                        // The operation is asynchronous, so the response object contains
                        // a unique identifier for the operation
                        Guid operationId = response.OperationId;

                        // Retrieve the Operation using the OperationId
                        RetrieveRequest retrieveOperationStatus = new RetrieveRequest();
                        retrieveOperationStatus.EntityType =
                            DeploymentEntityType.DeferredOperationStatus;
                        retrieveOperationStatus.InstanceTag =
                            new EntityInstanceId {
                            Id = operationId
                        };

                        RetrieveResponse        retrieveResponse;
                        DeferredOperationStatus deferredOperationStatus;

                        Console.WriteLine("Retrieving state of the job...");

                        // Retrieve the Operation State until Organization is created
                        do
                        {
                            // Wait 3 secs to not overload server
                            Thread.Sleep(3000);

                            retrieveResponse =
                                (RetrieveResponse)client.Execute(retrieveOperationStatus);

                            deferredOperationStatus =
                                ((DeferredOperationStatus)retrieveResponse.Entity);
                        }while (deferredOperationStatus.State !=
                                DeferredOperationState.Processing &&
                                deferredOperationStatus.State !=
                                DeferredOperationState.Completed);

                        // Poll OrganizationStatusRequest
                        RetrieveRequest retrieveReqServer = new RetrieveRequest();
                        retrieveReqServer.EntityType       = DeploymentEntityType.Organization;
                        retrieveReqServer.InstanceTag      = new EntityInstanceId();
                        retrieveReqServer.InstanceTag.Name = organization.UniqueName;

                        RetrieveResponse  retrieveRespServer;
                        OrganizationState orgState;

                        Console.WriteLine("Retrieving state of the organization...");

                        // Retrieve and check the Organization State until is enabled
                        do
                        {
                            retrieveRespServer =
                                (RetrieveResponse)client.Execute(retrieveReqServer);
                            _organizationID =
                                ((Microsoft.Xrm.Sdk.Deployment.Organization)retrieveRespServer.Entity).Id;
                            orgState =
                                ((Microsoft.Xrm.Sdk.Deployment.Organization)retrieveRespServer.Entity).State;

                            // Wait 5 secs to not overload server
                            Thread.Sleep(5000);
                        }while (orgState != OrganizationState.Enabled);

                        Console.WriteLine("Organization has been created!");

                        //</snippetUseAsyncDeploymentServiceMessages1>
                        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;
            }
        }
        public Response GetDataExtension()
        {
            var response = new Response { Success = true, Warning = false };
            try
            {
                //Retrieve Subscriber

                //Local variables
                APIObject[] Results;
                String requestID;
                String status;

                // Instantiate the retrieve request
                RetrieveRequest rr = new RetrieveRequest();
                rr.ObjectType = "DataExtensionObject[P00 SF_ SC Cumpleaños Mayo_PRUEBA_0001]";//required

                // Setting up a simple filter
                SimpleFilterPart sf = new SimpleFilterPart();
                sf.SimpleOperator = SimpleOperators.equals;
                sf.Property = "EMAIL";
                sf.Value = new String[] { "" };

                //Add Filter
                //rr.Filter = sf;

                rr.Properties = new string[] { "EMAIL","NOMBRE","MONTO","VISITAS", "DNI" };//required //Any Column on the Data Extension
                status = conexion.ETCliente.Retrieve(rr, out requestID, out Results);
                Console.WriteLine("EMAIL \t\t NOMBRE \t MONTO \t VISITAS \t DNI");
                for (int i = 0; i < Results.Length; i++)
                {
                    DataExtensionObject deo = Results[i] as DataExtensionObject;
                    for (int j = 0; j < deo.Properties.Length; j++)
                    {
                        //Console.Write(string.Format("{0}-{1}     ", deo.Properties[j].Name, deo.Properties[j].Value));
                        Console.Write(string.Format("{0}\t", deo.Properties[j].Value));
                    }

                    Console.WriteLine();
                }

                response.Data += "\nTotal Registros: " + Results.Length;
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }

            return response;
        }
Exemple #14
0
 public static jQueryXmlHttpRequest Retrieve(RetrieveRequest request, Action <RetrieveResponse <MeetingDecisionRow> > onSuccess, ServiceCallOptions options = null)
 {
     return(Q.ServiceRequest("Meeting/MeetingDecision/Retrieve", request, onSuccess, options));
 }
        /// <summary>
        /// Gets a <c>Dictionary</c> that contains the <c>Entity</c> instance that was retrieved using the supplied <c>RetrieveTarget</c>.
        /// </summary>
        /// <param name="target">A <c>TargetRetrive</c> to use when calling the CRM web service.</param>
        /// <returns>A <c>Dictionary</c> that contains the retrieved <c>Entity</c>'s property names as Keys and property values 
        /// as Values for those Keys.</returns>
        protected Dictionary<string, object> RetrieveEntityAsDictionary(Entity target)
        {
            if (target == null)
            {
                throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.ArgumentNullExceptionMessage)) { ExceptionId = AdapterException.SystemExceptionGuid };
            }

            List<string> attributes = new List<string>();
            List<FieldDefinition> defs = new List<FieldDefinition>();
            foreach (FieldDefinition def in this.ObjectDefinition.ToComplexType().Fields)
            {
                if (!(def.TypeDefinition is CollectionType))
                {
                    attributes.Add(def.Name);
                    defs.Add(def);
                }
            }

            ColumnSet cols = new ColumnSet(attributes.ToArray());
            RetrieveRequest request = new RetrieveRequest() { ColumnSet = cols, Target = new EntityReference(target.LogicalName, target.Id) };
            RetrieveResponse response = this.CallCrmExecuteWebMethod(request) as RetrieveResponse;
            Entity parent = response.Entity;
            return GetDictionary(parent, this.CrmAdapter, defs);
        }
Exemple #16
0
        public void RetrieveObjectsByFolderID(string folderId, ET_Client etClient, string path, string contentType)
        {
            // Create the SOAP binding for call.
                BasicHttpBinding binding = new BasicHttpBinding();
                binding.Name = "UserNameSoapBinding";
                binding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential;
                binding.MaxReceivedMessageSize = 2147483647;
                var client = new FuelSDK.SoapClient(binding, etClient.soapclient.Endpoint.Address);
                client.ClientCredentials.UserName.UserName = "******";
                client.ClientCredentials.UserName.Password = "******";

                using (var scope = new OperationContextScope(client.InnerChannel))
                {
                    // Add oAuth token to SOAP header.
                    XNamespace ns = "http://exacttarget.com";
                    var oauthElement = new XElement(ns + "oAuthToken", etClient.internalAuthToken);
                    var xmlHeader = MessageHeader.CreateHeader("oAuth", "http://exacttarget.com", oauthElement);
                    OperationContext.Current.OutgoingMessageHeaders.Add(xmlHeader);

                    List<object> folders = new List<object>();
                    string cType = "Email";

                    switch (contentType)
                    {
                        case "media":
                            cType = "Portfolio";
                            break;
                        case "dataextension":
                            cType = "DataExtension";
                            break;
                        case "content":
                            cType = "ContentArea";
                            break;
                    }

                    string requestID;
                    // Filter by the Folder/Category
                    SimpleFilterPart sfp = new SimpleFilterPart();
                    sfp.Property = "CategoryID";
                    sfp.SimpleOperator = SimpleOperators.equals;
                    sfp.Value = new string[] { folderId };

                    // Create the RetrieveRequest object

                    RetrieveRequest request = new RetrieveRequest();
                    request.ObjectType = cType;
                    request.Filter = sfp;
                    request.Properties = new string[] { "CustomerKey", "Name", "CreatedDate", "ModifiedDate" };

                    if(contentType == "media")
                        request.Properties = new string[] { "CustomerKey", "FileName", "CreatedDate", "ModifiedDate" };

                    // Execute the Retrieve
                    APIObject[] results;

                    string status = client.Retrieve(request, out requestID, out results);

                    for (int cntr = 0; cntr < results.Length; cntr++)
                    {
                            string sql = "INSERT INTO [Results] ([IdResult] ,[CustomerKey] ,[Name] ,[ResultType] ,[Path] ,[URL],[ThumbnailURL],[CreatedDate],[ModifiedDate],[IdContactIndex])VALUES (@IdResult ,@CustomerKey ,@Name ,@ResultType ,@Path ,@URL,@ThumbnailURL,@CreatedDate,@ModifiedDate,@IdContactIndex)";

                            switch (contentType)
                            {
                                case "media":
                                    var portfolio = (Portfolio)results[cntr];
                                    using (System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["FindIt.Data.Entities"].ConnectionString))
                                    using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, cn))
                                    {

                                        cmd.Parameters.Add("@IdResult", System.Data.SqlDbType.UniqueIdentifier).Value = Guid.NewGuid();
                                        cmd.Parameters.Add("@CustomerKey", System.Data.SqlDbType.VarChar).Value = portfolio.CustomerKey;
                                        cmd.Parameters.Add("@Name", System.Data.SqlDbType.VarChar).Value = portfolio.FileName;
                                        cmd.Parameters.Add("@ResultType", System.Data.SqlDbType.VarChar).Value = contentType;
                                        cmd.Parameters.Add("@Path", System.Data.SqlDbType.VarChar).Value = path;
                                        cmd.Parameters.Add("@URL", System.Data.SqlDbType.VarChar).Value = "";
                                        cmd.Parameters.Add("@ThumbnailURL", System.Data.SqlDbType.VarChar).Value = "";
                                        cmd.Parameters.Add("@CreatedDate", System.Data.SqlDbType.DateTime).Value = portfolio.CreatedDate;
                                        cmd.Parameters.Add("@ModifiedDate", System.Data.SqlDbType.DateTime).Value = portfolio.ModifiedDate;
                                        cmd.Parameters.Add("@IdContactIndex", System.Data.SqlDbType.UniqueIdentifier).Value = new Guid("A08D166C-F310-4F2D-8D44-5DD8F1564B8F");
                                        cn.Open();

                                        cmd.ExecuteNonQuery();
                                    }
                                    break;
                                case "dataextension":
                                    var dataextension = (DataExtension)results[cntr];
                                    using (System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["FindIt.Data.Entities"].ConnectionString))
                                    using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, cn))
                                    {

                                        cmd.Parameters.Add("@IdResult", System.Data.SqlDbType.UniqueIdentifier).Value = Guid.NewGuid();
                                        cmd.Parameters.Add("@CustomerKey", System.Data.SqlDbType.VarChar).Value = dataextension.CustomerKey;
                                        cmd.Parameters.Add("@Name", System.Data.SqlDbType.VarChar).Value = dataextension.Name;
                                        cmd.Parameters.Add("@ResultType", System.Data.SqlDbType.VarChar).Value = contentType;
                                        cmd.Parameters.Add("@Path", System.Data.SqlDbType.VarChar).Value = path;
                                        cmd.Parameters.Add("@URL", System.Data.SqlDbType.VarChar).Value = "";
                                        cmd.Parameters.Add("@ThumbnailURL", System.Data.SqlDbType.VarChar).Value = "";
                                        cmd.Parameters.Add("@CreatedDate", System.Data.SqlDbType.DateTime).Value = dataextension.CreatedDate;
                                        cmd.Parameters.Add("@ModifiedDate", System.Data.SqlDbType.DateTime).Value = dataextension.ModifiedDate;
                                        cmd.Parameters.Add("@IdContactIndex", System.Data.SqlDbType.UniqueIdentifier).Value = new Guid("A08D166C-F310-4F2D-8D44-5DD8F1564B8F");
                                        cn.Open();

                                        cmd.ExecuteNonQuery();
                                    }
                                    break;
                                case "content":
                                    var content = (ContentArea)results[cntr];
                                    using (System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["FindIt.Data.Entities"].ConnectionString))
                                    using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, cn))
                                    {

                                        cmd.Parameters.Add("@IdResult", System.Data.SqlDbType.UniqueIdentifier).Value = Guid.NewGuid();
                                        cmd.Parameters.Add("@CustomerKey", System.Data.SqlDbType.VarChar).Value = content.CustomerKey;
                                        cmd.Parameters.Add("@Name", System.Data.SqlDbType.VarChar).Value = content.Name;
                                        cmd.Parameters.Add("@ResultType", System.Data.SqlDbType.VarChar).Value = contentType;
                                        cmd.Parameters.Add("@Path", System.Data.SqlDbType.VarChar).Value = path;
                                        cmd.Parameters.Add("@URL", System.Data.SqlDbType.VarChar).Value = "";
                                        cmd.Parameters.Add("@ThumbnailURL", System.Data.SqlDbType.VarChar).Value = "";
                                        cmd.Parameters.Add("@CreatedDate", System.Data.SqlDbType.DateTime).Value = content.CreatedDate;
                                        cmd.Parameters.Add("@ModifiedDate", System.Data.SqlDbType.DateTime).Value = content.ModifiedDate;
                                        cmd.Parameters.Add("@IdContactIndex", System.Data.SqlDbType.UniqueIdentifier).Value = new Guid("A08D166C-F310-4F2D-8D44-5DD8F1564B8F");
                                        cn.Open();

                                        cmd.ExecuteNonQuery();
                                    }
                                    break;
                                default:
                                    var email = (Email)results[cntr];

                                    using (System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["FindIt.Data.Entities"].ConnectionString))
                                    using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, cn))
                                    {

                                        cmd.Parameters.Add("@IdResult",System.Data.SqlDbType.UniqueIdentifier).Value = Guid.NewGuid();
                                        cmd.Parameters.Add("@CustomerKey", System.Data.SqlDbType.VarChar).Value = email.CustomerKey;
                                        cmd.Parameters.Add("@Name", System.Data.SqlDbType.VarChar).Value = email.Name;
                                        cmd.Parameters.Add("@ResultType", System.Data.SqlDbType.VarChar).Value = contentType;
                                        cmd.Parameters.Add("@Path", System.Data.SqlDbType.VarChar).Value = path;
                                        cmd.Parameters.Add("@URL", System.Data.SqlDbType.VarChar).Value = "";
                                        cmd.Parameters.Add("@ThumbnailURL", System.Data.SqlDbType.VarChar).Value = "";
                                        cmd.Parameters.Add("@CreatedDate", System.Data.SqlDbType.DateTime).Value = email.CreatedDate;
                                        cmd.Parameters.Add("@ModifiedDate", System.Data.SqlDbType.DateTime).Value = email.ModifiedDate;
                                        cmd.Parameters.Add("@IdContactIndex", System.Data.SqlDbType.UniqueIdentifier).Value = new Guid("A08D166C-F310-4F2D-8D44-5DD8F1564B8F");
                                        cn.Open();

                                        cmd.ExecuteNonQuery();
                                    }
                                    break;
                            }

                    }
                }
        }
        public GetReturn(APIObject theObject, Boolean Continue, String OverrideObjectType)
        {
            string OverallStatus = string.Empty, RequestID = string.Empty;
            APIObject[] objectResults = new APIObject[0];
            theObject.AuthStub.refreshToken();
            this.Results = new APIObject[0];
            using (var scope = new OperationContextScope(theObject.AuthStub.soapclient.InnerChannel))
            {
                //Add oAuth token to SOAP header.
                XNamespace ns = "http://exacttarget.com";
                var oauthElement = new XElement(ns + "oAuthToken", theObject.AuthStub.internalAuthToken);
                var xmlHeader = MessageHeader.CreateHeader("oAuth", "http://exacttarget.com", oauthElement);
                OperationContext.Current.OutgoingMessageHeaders.Add(xmlHeader);

                var httpRequest = new System.ServiceModel.Channels.HttpRequestMessageProperty();
                OperationContext.Current.OutgoingMessageProperties.Add(System.ServiceModel.Channels.HttpRequestMessageProperty.Name, httpRequest);
                httpRequest.Headers.Add(HttpRequestHeader.UserAgent, theObject.AuthStub.SDKVersion);

                RetrieveRequest rr = new RetrieveRequest();
                if (Continue)
                {
                    if (theObject.LastRequestID == null)
                    {
                        throw new Exception("Unable to call GetMoreResults without first making successful Get() request");
                    }
                    rr.ContinueRequest = theObject.LastRequestID;
                }
                else
                {
                    if (theObject.SearchFilter != null)
                    {
                        rr.Filter = theObject.SearchFilter;
                    }

                    // Use the name from the object passed in unless an override is passed (Used for DataExtensionObject)
                    if (OverrideObjectType == null)
                        rr.ObjectType = this.TranslateObject(theObject).GetType().ToString().Replace("FuelSDK.", "");
                    else
                        rr.ObjectType = OverrideObjectType;

                    //If they didn't specify Props then we look them up using Info()
                    if (theObject.Props == null && theObject.GetType().GetMethod("Info") != null)
                    {
                        InfoReturn ir = new InfoReturn(theObject);
                        List<string> lProps = new List<string>();
                        if (ir.Status)
                        {
                            foreach (ET_PropertyDefinition pd in ir.Results)
                            {
                                if (pd.IsRetrievable)
                                    lProps.Add(pd.Name);
                            }
                        }
                        else
                        {
                            throw new Exception("Unable to find properties for object in order to perform Get() request");
                        }
                        rr.Properties = lProps.ToArray();
                    }
                    else
                        rr.Properties = theObject.Props;
                }
                OverallStatus = theObject.AuthStub.soapclient.Retrieve(rr, out RequestID, out objectResults);

                this.RequestID = RequestID;

                if (objectResults.Length > 0)
                {
                    List<APIObject> cleanedObjectResults = new List<APIObject>();
                    foreach (APIObject obj in objectResults)
                    {
                        cleanedObjectResults.Add(this.TranslateObject(obj));
                    }
                    this.Results = cleanedObjectResults.ToArray();
                }

                this.Status = true;
                this.Code = 200;
                this.MoreResults = false;
                this.Message = "";

                if (OverallStatus != "OK" && OverallStatus != "MoreDataAvailable")
                {
                    this.Status = false;
                    this.Message = OverallStatus;
                }
                else if (OverallStatus == "MoreDataAvailable")
                {
                    this.MoreResults = true;
                }
            }
        }
Exemple #18
0
        /// <summary>
        /// This method first connects to the Deployment service. Then,
        /// uses RetrieveRequest, UpdateRequest and UpdateAdvancedSettingsRequest.
        /// </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))
                {
                    // Instantiate DeploymentServiceClient for calling the service.
                    DeploymentServiceClient serviceClient =
                        ProxyClientHelper.CreateClient(
                            new Uri(serverConfig.DiscoveryUri.ToString()
                                    .Replace("Services", "Deployment")
                                    .Replace("Discovery", "Deployment")));

                    // Setting credentials from the current security context.
                    if (serverConfig.Credentials != null)
                    {
                        serviceClient.ClientCredentials.Windows.ClientCredential =
                            serverConfig.Credentials.Windows.ClientCredential;
                    }
                    else
                    {
                        serviceClient.ClientCredentials.Windows.ClientCredential =
                            CredentialCache.DefaultNetworkCredentials;
                    }

                    #region RetrieveRequest

                    // Retrieve all servers available in the deployment
                    Console.WriteLine("\nRetrieving list of servers...\n");
                    var servers =
                        serviceClient.RetrieveAll(DeploymentEntityType.Server);

                    // Print list of all retrieved servers.
                    Console.WriteLine("Servers in your deployment");
                    Console.WriteLine("================================");
                    foreach (var server in servers)
                    {
                        Console.WriteLine(server.Name);
                    }
                    Console.WriteLine("<End of Listing>");
                    Console.WriteLine();

                    // Retrieve details of first (other than current server) or default server from previous call.
                    var serverId = servers.FirstOrDefault(x => x.Name.ToLowerInvariant() != serverConfig.ServerAddress.ToLowerInvariant());
                    // If no other server exists then default to existing one.
                    if (serverId == null)
                    {
                        serverId = servers.FirstOrDefault();
                    }

                    Console.WriteLine("\nRetrieving details of one server...\n");
                    RetrieveRequest retrieveReqServer = new RetrieveRequest();
                    retrieveReqServer.EntityType  = DeploymentEntityType.Server;
                    retrieveReqServer.InstanceTag = serverId;
                    RetrieveResponse retrieveRespServer =
                        (RetrieveResponse)serviceClient.Execute(retrieveReqServer);
                    Server serverToUpdate =
                        (Server)retrieveRespServer.Entity;

                    Console.WriteLine("================================");
                    Console.WriteLine("Name: " + serverToUpdate.Name);
                    Console.WriteLine("State: " + serverToUpdate.State);
                    Console.WriteLine();

                    #endregion RetrieveRequest

                    #region UpdateRequest
                    // Avoid updating current server as it would disrupt the further sample execution.
                    if (servers.Count > 1)
                    {
                        // Modified the property we want to update
                        serverToUpdate.State = ServerState.Disabled;

                        // Update the deployment record
                        Console.WriteLine("\nUpdating server...\n");
                        UpdateRequest updateReq = new UpdateRequest();
                        updateReq.Entity = serverToUpdate;
                        UpdateResponse uptRes =
                            (UpdateResponse)serviceClient.Execute(updateReq);

                        // Retrieve server details again to check if it is updated
                        RetrieveResponse retrieveRespServerUpdated =
                            (RetrieveResponse)serviceClient.Execute(retrieveReqServer);
                        Server serverUpdated =
                            (Server)retrieveRespServerUpdated.Entity;

                        Console.WriteLine("Server Updated");
                        Console.WriteLine("================================");
                        Console.WriteLine("Name: " + serverUpdated.Name);
                        Console.WriteLine("State: " + serverUpdated.State);
                        Console.WriteLine();

                        // Revert change
                        serverUpdated.State = ServerState.Enabled;

                        Console.WriteLine("\nReverting change made in server...\n");
                        UpdateRequest updateReqRevert = new UpdateRequest();
                        updateReqRevert.Entity = serverUpdated;
                        UpdateResponse uptResRev =
                            (UpdateResponse)serviceClient.Execute(updateReqRevert);

                        RetrieveResponse retrieveRespServerReverted =
                            (RetrieveResponse)serviceClient.Execute(retrieveReqServer);
                        Server serverReverted =
                            (Server)retrieveRespServerReverted.Entity;

                        Console.WriteLine("Server Reverted");
                        Console.WriteLine("================================");
                        Console.WriteLine("Name: " + serverReverted.Name);
                        Console.WriteLine("State: " + serverReverted.State);
                        Console.WriteLine();
                    }
                    else
                    {
                        Console.WriteLine("\nMulti-server environment missing."
                                          + "\nSkipping server update request to avoid disruption in the sample execution.");
                    }
                    #endregion UpdateRequest

                    #region UpdateAdvanceRequest

                    // Retrieve Advanced Settings for your organization.
                    Console.WriteLine("\nRetrieving Advanced Settings...\n");
                    RetrieveAdvancedSettingsRequest requestAdvSettings =
                        new RetrieveAdvancedSettingsRequest
                    {
                        ConfigurationEntityName = "Deployment",
                        ColumnSet = new ColumnSet("Id")
                    };
                    ConfigurationEntity configuration =
                        ((RetrieveAdvancedSettingsResponse)
                         serviceClient.Execute(requestAdvSettings)).Entity;

                    // Print out all advanced settings where IsWritable==true.
                    Console.WriteLine("Advanced deployment settings that can be updated");
                    Console.WriteLine("================================================");
                    foreach (var setting in configuration.Attributes)
                    {
                        if (setting.Key != "Id")
                        {
                            Console.WriteLine(
                                String.Format("{0}: {1}",
                                              setting.Key,
                                              setting.Value));
                        }
                    }
                    Console.WriteLine();

                    // Create the Configuration Entity with the values to update
                    ConfigurationEntity configEntity = new ConfigurationEntity();
                    configEntity.LogicalName = "Deployment";
                    configEntity.Attributes  = new AttributeCollection();
                    configEntity.Attributes.Add
                        (new KeyValuePair <string, object>
                            ("AutomaticallyInstallDatabaseUpdates", true));

                    // Update Advanced Settings
                    Console.WriteLine("\nUpdating Advanced Settings...\n");
                    UpdateAdvancedSettingsRequest updateAdvanceReq =
                        new UpdateAdvancedSettingsRequest();
                    updateAdvanceReq.Entity = configEntity;
                    serviceClient.Execute(updateAdvanceReq);

                    // Retrieve Advanced Settings to check if they have been updated
                    ConfigurationEntity configurationUpdated =
                        ((RetrieveAdvancedSettingsResponse)
                         serviceClient.Execute(requestAdvSettings)).Entity;

                    Console.WriteLine("Advanced deployment settings updated");
                    Console.WriteLine("================================================");
                    foreach (var setting in configurationUpdated.Attributes)
                    {
                        if (setting.Key != "Id")
                        {
                            Console.WriteLine(
                                String.Format("{0}: {1}",
                                              setting.Key,
                                              setting.Value));
                        }
                    }
                    Console.WriteLine();

                    // Revert change
                    ConfigurationEntity entityRevert = new ConfigurationEntity();
                    entityRevert.LogicalName = "Deployment";
                    entityRevert.Attributes  = new AttributeCollection();
                    entityRevert.Attributes.Add
                        (new KeyValuePair <string, object>
                            ("AutomaticallyInstallDatabaseUpdates", false));

                    Console.WriteLine("\nReverting Advanced Settings...\n");
                    UpdateAdvancedSettingsRequest requestRevert =
                        new UpdateAdvancedSettingsRequest();
                    requestRevert.Entity = entityRevert;
                    serviceClient.Execute(requestRevert);

                    ConfigurationEntity configurationReverted =
                        ((RetrieveAdvancedSettingsResponse)
                         serviceClient.Execute(requestAdvSettings)).Entity;
                    Console.WriteLine("Advanced deployment settings reverted");
                    Console.WriteLine("================================================");
                    foreach (var setting in configurationReverted.Attributes)
                    {
                        if (setting.Key != "Id")
                        {
                            Console.WriteLine(
                                String.Format("{0}: {1}",
                                              setting.Key,
                                              setting.Value));
                        }
                    }
                    Console.WriteLine();
                    #endregion UpdateAdvanceRequest
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <DeploymentServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
 public static jQueryXmlHttpRequest Retrieve(RetrieveRequest request, Action <RetrieveResponse <OrderDetailRow> > onSuccess, ServiceCallOptions options = null)
 {
     return(null);
 }
 public static jQueryXmlHttpRequest Retrieve(RetrieveRequest request, Action <RetrieveResponse <RoleRow> > onSuccess, ServiceCallOptions options = null)
 {
     return(Q.ServiceRequest(Methods.Retrieve, request, onSuccess, options));
 }
Exemple #21
0
 public Result <RetrieveResponse <MyRow> > Retrieve(RetrieveRequest request)
 {
     return(this.UseConnection("Default", (cnn) => new MyRepository().Retrieve(cnn, request)));
 }
Exemple #22
0
        public static void Should_Retrieve_A_Correct_Entity_With_1_To_N_Related_Records_And_Related_Record_Query_Criteria()
        {
            var account1 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 1"
            };

            var account2 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 2"
            };

            var contact1 = new Contact
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Contact 1",
                ParentCustomerId = account2.ToEntityReference()
            };

            var contact2 = new Contact
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Contact 2",
                ParentCustomerId = account1.ToEntityReference()
            };

            var contact3 = new Contact
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Contact 3",
                ParentCustomerId = account2.ToEntityReference()
            };

            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

            fakedContext.Initialize(new Entity[] { account1, account2, contact1, contact2, contact3 });
            fakedContext.AddRelationship("contact_customer_accounts", new XrmFakedRelationship
                                         (
                                             entity1LogicalName: Contact.EntityLogicalName,
                                             entity1Attribute: "parentcustomerid",
                                             entity2LogicalName: Account.EntityLogicalName,
                                             entity2Attribute: "accountid"
                                         ));

            var request = new RetrieveRequest
            {
                ColumnSet            = new ColumnSet("name"),
                Target               = account2.ToEntityReference(),
                RelatedEntitiesQuery = new RelationshipQueryCollection
                {
                    {
                        new Relationship("contact_customer_accounts"),
                        new QueryExpression
                        {
                            ColumnSet  = new ColumnSet("firstname"),
                            EntityName = Contact.EntityLogicalName,
                            Criteria   = new FilterExpression
                            {
                                Conditions =
                                {
                                    new ConditionExpression("firstname", ConditionOperator.Equal, contact3.FirstName),
                                    new ConditionExpression("statecode", ConditionOperator.Equal, 0)
                                }
                            }
                        }
                    }
                }
            };

            var result = (RetrieveResponse)fakedService.Execute(request);

            Assert.NotNull(result.Entity);

            var resultAccount = result.Entity.ToEntity <Account>();

            Assert.Equal(account2.Id, resultAccount.Id);

            Assert.NotNull(resultAccount.contact_customer_accounts);
            Assert.Equal(1, resultAccount.contact_customer_accounts.Count());
            Assert.Equal(contact3.Id, resultAccount.contact_customer_accounts.First().Id);
        }
 public virtual Entity retrieveEntity(RetrieveRequest request)
 {
     RetrieveResponse response = (RetrieveResponse)service.Execute(request);
     return response.Entity;
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        ClientScriptManager csm            = Page.ClientScript;
        string display                     = "";
        string prodid                      = Request["prodid"];
        string connectionString            = GetServiceConfiguration();
        Dictionary <string, object> result = new Dictionary <string, object>();
        string json = "";

        if (connectionString != null && prodid != null)
        {
            display = "Invalid prodid";
            csm.RegisterClientScriptBlock(this.GetType(), "Pop", "alert('" + display + "');", true);

            CrmServiceClient conn = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connectionString);
            _orgService = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;

            DataSet    dataSet            = new DataSet("product");
            DataTable  table              = new DataTable("products");
            DataColumn col_product_id     = new DataColumn("productId");
            DataColumn col_product_name   = new DataColumn("productName");
            DataColumn col_product_number = new DataColumn("productNumber");
            DataColumn col_product_parent = new DataColumn("productcategory");
            DataColumn col_amount_value   = new DataColumn("productprice");
            //DataColumn col_product_description = new DataColumn("description");
            DataColumn col_product_image = new DataColumn("image");
            DataColumn col_product_url   = new DataColumn("url");
            table.Columns.Add(col_product_id);
            table.Columns.Add(col_product_name);
            table.Columns.Add(col_product_parent);
            table.Columns.Add(col_product_number);
            table.Columns.Add(col_amount_value);
            //table.Columns.Add(col_product_description);
            table.Columns.Add(col_product_image);
            table.Columns.Add(col_product_url);
            dataSet.Tables.Add(table);

            QueryExpression qe = new QueryExpression("product");
            qe.ColumnSet = new ColumnSet("name", "productnumber", "price", "parentproductid", "description", "adx_partialurl");
            qe.Criteria.AddCondition("productnumber", ConditionOperator.Equal, prodid);
            EntityCollection results = _orgService.RetrieveMultiple(qe);
            if (results.Entities != null)
            {
                foreach (Entity product in results.Entities)
                {
                    DataRow newRow = table.NewRow();
                    newRow["productId"]       = product.Id.ToString();
                    newRow["productName"]     = product["name"];
                    newRow["productNumber"]   = product["productnumber"];
                    newRow["productcategory"] = product.GetAttributeValue <EntityReference>("parentproductid").Name;
                    newRow["productprice"]    = ((Money)(product["price"])).Value.ToString("0.00", CultureInfo.InvariantCulture);
                    //newRow["description"] = product["description"];
                    newRow["url"] = product["adx_partialurl"];

                    EntityReference             productRef            = new EntityReference("product", new Guid(product.Id.ToString()));
                    RelationshipQueryCollection relationshipQueryColl = new RelationshipQueryCollection();
                    Relationship relationship = new Relationship();
                    relationship.SchemaName = "productsalesliterature_association";
                    QueryExpression qe2 = new QueryExpression("salesliterature");
                    qe2.ColumnSet = new ColumnSet(true);
                    relationshipQueryColl.Add(relationship, qe2);

                    RetrieveRequest retrieveRequest = new RetrieveRequest();
                    retrieveRequest.RelatedEntitiesQuery = relationshipQueryColl;
                    retrieveRequest.Target    = productRef;
                    retrieveRequest.ColumnSet = new ColumnSet(true);
                    //CrmConnection connection = new CrmConnection("CRM");
                    string connectionString2 = GetServiceConfiguration();

                    //using (var _serviceProxy = new OrganizationService(connection))
                    if (connectionString2 != null)
                    {
                        //OrganizationResponse response = _serviceProxy.Execute(retrieveRequest);
                        CrmServiceClient conn2 = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connectionString2);
                        _orgService = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;
                        OrganizationResponse response             = _orgService.Execute(retrieveRequest);
                        Entity           product2                 = (Entity)response.Results["Entity"];
                        EntityCollection ecRelatedSalesLiterature = product2.RelatedEntities[relationship];

                        if (ecRelatedSalesLiterature.Entities != null)
                        {
                            QueryExpression qe3 = new QueryExpression("salesliteratureitem");
                            qe3.ColumnSet = new ColumnSet(true);
                            qe3.Criteria.AddCondition("salesliteratureid", ConditionOperator.Equal, ecRelatedSalesLiterature.Entities[0].Id);
                            EntityCollection results2 = _orgService.RetrieveMultiple(qe3);
                            if (results2.Entities != null)
                            {
                                newRow["image"] = results2.Entities[0]["documentbody"];
                            }
                        }
                        // do whatever you want
                    }
                    table.Rows.Add(newRow);
                }
            }

            json = JsonConvert.SerializeObject(dataSet, Formatting.Indented);
            Response.ContentType = "application/json; charset=utf-8";
            Response.Write(json);
        }
        else
        {
            display = "Invalid prodid";
            csm.RegisterClientScriptBlock(this.GetType(), "Pop", "alert('" + display + "');", true);
        }
    }
 public Result<RetrieveResponse<MyRow>> Retrieve(RetrieveRequest request)
 {
     return this.UseConnection("Default", (cnn) => new MyRepository().Retrieve(cnn, request));
 }
Exemple #26
0
        public void Should_Be_Able_To_Insert_And_Retrieve_Inserted_Account_In_Single_Bulk_Request()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["CrmOrganisation"];
            using (var conn = new CrmDbConnection(connectionString.ConnectionString))
            {
                conn.Open();
                var orgService = conn.OrganizationService;

                // Create an ExecuteMultipleRequest object.
                var multipleRequests = new ExecuteMultipleRequest()
                {
                    // Assign settings that define execution behavior: continue on error, return responses.
                    Settings = new ExecuteMultipleSettings()
                    {
                        ContinueOnError = false,
                        ReturnResponses = true
                    },
                    // Create an empty organization request collection.
                    Requests = new OrganizationRequestCollection()
                };

                var entity = new Entity("account");
                entity.Id = Guid.NewGuid();
                entity["name"] = "experimental test";

                CreateRequest createRequest = new CreateRequest
                {
                    Target = entity
                };

                RetrieveRequest retrieveRequest = new RetrieveRequest
                {
                    Target = new EntityReference(entity.LogicalName, entity.Id),
                    ColumnSet = new ColumnSet("createdon")
                };

                multipleRequests.Requests.Add(createRequest);
                multipleRequests.Requests.Add(retrieveRequest);

                // Execute all the requests in the request collection using a single web method call.
                ExecuteMultipleResponse responseWithResults = (ExecuteMultipleResponse)orgService.Execute(multipleRequests);

                var createResponseItem = responseWithResults.Responses[0];
                CreateResponse createResponse = null;
                if (createResponseItem.Response != null)
                {
                    createResponse = (CreateResponse)createResponseItem.Response;
                }

                var retrieveResponseItem = responseWithResults.Responses[1];

                RetrieveResponse retrieveResponse = null;
                if (retrieveResponseItem.Response != null)
                {
                    retrieveResponse = (RetrieveResponse)retrieveResponseItem.Response;
                }

                Console.Write(retrieveResponse.Entity["createdon"]);

            }
        }
 public static jQueryXmlHttpRequest Retrieve(RetrieveRequest request, Action <RetrieveResponse <CustomerDemographicRow> > onSuccess, ServiceCallOptions options = null)
 {
     return(null);
 }
Exemple #28
0
        public static void Should_Retrieve_All_Related_Records()
        {
            //related entities should all be returned
            //even when PageInfo is set
            //AM: There is no reason for the result to retun all related records regardless of the PageSize - at least that is not the CRM behavior
            //The result set shoudl not exceed the number specifit in he Page info

            var account1 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 1"
            };

            var account2 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 2"
            };

            var leads = new List <Lead>();

            for (int i = 0; i < 50; i++)
            {
                leads.Add(new Lead {
                    Id = Guid.NewGuid()
                });
            }

            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

            var relationshipName = "accountleads_association";

            fakedContext.AddRelationship(relationshipName, new XrmFakedRelationship
            {
                IntersectEntity    = "accountleads",
                Entity1LogicalName = Account.EntityLogicalName,
                Entity1Attribute   = "accountid",
                Entity2LogicalName = Lead.EntityLogicalName,
                Entity2Attribute   = "leadid"
            });

            var initData = new List <Entity>();

            initData.AddRange(new Entity[] { account1, account2 });
            initData.AddRange(leads);

            fakedContext.Initialize(initData);
            fakedService.Associate(Account.EntityLogicalName, account2.Id, new Relationship(relationshipName),
                                   new EntityReferenceCollection(leads.Select(x => x.ToEntityReference()).ToList()));

            var request = new RetrieveRequest
            {
                ColumnSet            = new ColumnSet("name"),
                Target               = account2.ToEntityReference(),
                RelatedEntitiesQuery = new RelationshipQueryCollection
                {
                    {
                        new Relationship(relationshipName),
                        new QueryExpression
                        {
                            PageInfo = new PagingInfo {
                                Count = 20, PageNumber = 1
                            },
                            ColumnSet  = new ColumnSet(false),
                            EntityName = Lead.EntityLogicalName
                        }
                    }
                }
            };

            var result = (RetrieveResponse)fakedService.Execute(request);

            Assert.NotNull(result.Entity);

            //check account
            var resultAccount = result.Entity.ToEntity <Account>();

            //check relationship
            Assert.NotNull(resultAccount.accountleads_association);
            //The
            Assert.Equal(20, resultAccount.accountleads_association.Count());
        }
Exemple #29
0
 public RetrieveResponse <MyRow> Retrieve(IDbConnection connection, RetrieveRequest request)
 {
     Session["UserID"] = request.EntityId;
     return(new MyRepository().Retrieve(connection, request));
 }
Exemple #30
0
        public static void Should_Retrieve_A_Correct_Entity_With_N_To_N_Related_Records_Vice_Versa()
        {
            var account1 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 1"
            };

            var account2 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 2"
            };

            var account3 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 3"
            };

            var lead1 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 1"
            };

            var lead2 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 2"
            };

            var lead3 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 3"
            };

            var lead4 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 4"
            };

            var lead5 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 5"
            };

            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

            var relationshipName = "accountleads_association";

            fakedContext.AddRelationship(relationshipName, new XrmFakedRelationship
            {
                IntersectEntity    = "accountleads",
                Entity1LogicalName = Account.EntityLogicalName,
                Entity1Attribute   = "accountid",
                Entity2LogicalName = Lead.EntityLogicalName,
                Entity2Attribute   = "leadid"
            });

            fakedContext.Initialize(new Entity[] { account1, account2, account3, lead1, lead2, lead3, lead4, lead5 });
            fakedService.Associate(Account.EntityLogicalName, account2.Id, new Relationship(relationshipName),
                                   new EntityReferenceCollection()
            {
                lead2.ToEntityReference(),
                lead4.ToEntityReference(),
                lead5.ToEntityReference()
            });

            fakedService.Associate(Account.EntityLogicalName, account1.Id, new Relationship(relationshipName),
                                   new EntityReferenceCollection()
            {
                lead2.ToEntityReference(),
                lead3.ToEntityReference()
            });

            var request = new RetrieveRequest
            {
                ColumnSet            = new ColumnSet("subject"),
                Target               = lead2.ToEntityReference(),
                RelatedEntitiesQuery = new RelationshipQueryCollection
                {
                    {
                        new Relationship(relationshipName),
                        new QueryExpression
                        {
                            ColumnSet  = new ColumnSet("name"),
                            EntityName = Account.EntityLogicalName
                        }
                    }
                }
            };

            var result = (RetrieveResponse)fakedService.Execute(request);

            Assert.NotNull(result.Entity);

            //check account
            var resultLead = result.Entity.ToEntity <Lead>();

            Assert.Equal(lead2.Id, lead2.Id);
            Assert.Equal(lead2.Subject, lead2.Subject);

            //check relationship
            Assert.NotNull(resultLead.accountleads_association);
            Assert.Equal(2, resultLead.accountleads_association.Count());

            //check that accounts are retrieved
            var resultRelatedRecordsList = resultLead.accountleads_association;

            Assert.True(resultRelatedRecordsList.Any(x => x.Id == account2.Id));
            Assert.True(resultRelatedRecordsList.Any(x => x.Id == account1.Id));

            //check accounts (optional check)
            Assert.Equal(account2.Name, resultRelatedRecordsList.First(x => x.Id == account2.Id).Name);
            Assert.Equal(account1.Name, resultRelatedRecordsList.First(x => x.Id == account1.Id).Name);
        }
Exemple #31
0
 public static jQueryXmlHttpRequest Retrieve(RetrieveRequest request, Action <RetrieveResponse <CategoryRow> > onSuccess, ServiceCallOptions options = null)
 {
     return(Q.ServiceRequest("Northwind/Category/Retrieve", request, onSuccess, options));
 }
        /// <summary>
        /// Populates a <c>Dictionary</c> with the values contained in a <c>DynamicEntity</c>.
        /// </summary>
        /// <param name="dynamicEntity">The <c>DynamicEntity</c> to get the properties and data from.</param>
        /// <param name="complexTypeDictionary">The <c>Dictionary</c> to be populated.</param>
        /// <param name="property">The property on the <c>DynamicEntity</c> to populate the supplied <c>Dictionary</c> for.</param>
        /// <param name="adapter">An instance of a <c>CRMAdapter</c> to use when getting dynamics_integrationkey data for a <c>Lookup</c> type.</param>
        /// <param name="definition">The <see cref="FieldDefinition"/> for the referenced entity.</param>
        private static void PopulateDictionary(Entity dynamicEntity, Dictionary<string, object> complexTypeDictionary, KeyValuePair<string, object> property, DynamicCrmAdapter adapter, FieldDefinition definition)
        {
            PopulateDictionary(dynamicEntity, complexTypeDictionary, property);

            if (complexTypeDictionary.ContainsKey("Id") && complexTypeDictionary.ContainsKey("LogicalName"))
            {
                if (complexTypeDictionary["LogicalName"].ToString() != "attachment" && complexTypeDictionary["LogicalName"].ToString() != "activitymimeattachment")
                {
                    ColumnSet cols = new ColumnSet(true);
                    if (!CRM2011AdapterUtilities.GetIntegratedEntities().Contains(complexTypeDictionary["LogicalName"].ToString()))
                    {
                        cols = new ColumnSet(true);
                    }

                    RetrieveRequest request = new RetrieveRequest() { ColumnSet = cols, Target = new EntityReference(complexTypeDictionary["LogicalName"].ToString(), new Guid(complexTypeDictionary["Id"].ToString())) };
                    RetrieveResponse response = adapter.OrganizationService.Execute(request) as RetrieveResponse;
                    Entity entity = response.Entity;

                    var lookupType = definition.AdditionalAttributes.FirstOrDefault(x => x.Name == "LookupType");
                    var lookupField = definition.AdditionalAttributes.FirstOrDefault(x => x.Name == "LookupField");

                    var typeSplit = lookupType.Value.Split(',');
                    var fieldSplit = lookupField.Value.Split(',');

                    var keyValueLookup = new List<KeyValuePair<string, string>>();

                    if (typeSplit.Count() > 1 && fieldSplit.Count() > 1)
                    {
                        for (int i = 0; i < typeSplit.Count(); i++)
                        {
                            keyValueLookup.Add(new KeyValuePair<string, string>(typeSplit[i], fieldSplit[i]));
                        }

                        lookupField.Value = keyValueLookup.FirstOrDefault(x => x.Key == entity.LogicalName).Value;
                    }

                    if (lookupField != null)
                    {
                        if (lookupField.Value == "domainname" || entity.LogicalName == "systemuser")
                        {
                            lookupField.Value = "fullname";
                        }
                        else if (entity.LogicalName == "activitypointer")
                        {
                            lookupField.Value = "activityid";
                        }

                        complexTypeDictionary.Add(lookupField.Value, entity[lookupField.Value]);
                    }
                }
            }
        }
Exemple #33
0
        private static void Initialize()
        {
            const string        schemaName  = "__schemaName__";
            const string        entityName  = "__entityName__";
            const string        logicalName = "__logicalName__";
            const EntityFilters filters     = EntityFilters.All;
            var id = new Guid("ffffffff-ffff-ffff-ffff-ffffffffffff");

            var retrieveRequest = new RetrieveRequest {
                ColumnSet = new ColumnSet(true), Target = new EntityReference(logicalName, id)
            };

            _serializedRetrieveRequestFormat = SerializeForFormat(retrieveRequest)
                                               .Replace(logicalName, @"{0}")
                                               .Replace(id.ToString(), @"{1}");

            var relationship = new Relationship(schemaName)
            {
                PrimaryEntityRole = EntityRole.Referencing
            };
            var query = new RelationshipQueryCollection {
                { relationship, new QueryExpression(entityName)
                  {
                      ColumnSet = new ColumnSet(true)
                  } }
            };
            var retrieveRequestWithRelatedQuery = new RetrieveRequest {
                ColumnSet = new ColumnSet(), Target = new EntityReference(logicalName, id), RelatedEntitiesQuery = query
            };

            _serializedRetrieveRequestWithRelatedQueryFormat = SerializeForFormat(retrieveRequestWithRelatedQuery)
                                                               .Replace(logicalName, @"{0}")
                                                               .Replace(id.ToString(), @"{1}")
                                                               .Replace(schemaName, @"{2}")
                                                               .Replace(@"""PrimaryEntityRole"":0", @"""PrimaryEntityRole"":{3}")
                                                               .Replace(entityName, @"{4}");

            var retrieveAllEntitiesRequest = new RetrieveAllEntitiesRequest {
                EntityFilters = filters, RetrieveAsIfPublished = true
            };

            _serializedRetrieveAllEntitiesRequestFormat = SerializeForFormat(retrieveAllEntitiesRequest)
                                                          .Replace(((int)filters).ToString(), @"{0}")
                                                          .Replace("true", @"{1}");

            var retrieveEntityRequest = new RetrieveEntityRequest {
                EntityFilters = filters, LogicalName = logicalName, RetrieveAsIfPublished = true
            };

            _serializedRetrieveEntityRequestFormat = SerializeForFormat(retrieveEntityRequest)
                                                     .Replace(((int)filters).ToString(), @"{0}")
                                                     .Replace(logicalName, @"{1}")
                                                     .Replace("true", @"{2}");

            var retrieveMultipleRequest = new RetrieveMultipleRequest {
                Query = new QueryExpression(logicalName)
                {
                    Distinct = true
                }
            };

            _serializedRetrieveMultipleRequestFormat = SerializeForFormat(retrieveMultipleRequest)
                                                       .Replace(logicalName, @"{0}")
                                                       .Replace("true", @"{1}");

            var retrieveRelationshipRequest = new RetrieveRelationshipRequest {
                Name = logicalName, RetrieveAsIfPublished = true
            };

            _serializedRetrieveRelationshipRequestFormat = SerializeForFormat(retrieveRelationshipRequest)
                                                           .Replace(logicalName, @"{0}")
                                                           .Replace("true", @"{1}");
        }
        protected override void Execute(CodeActivityContext context)
        {
            #region Tracing Object
            //Tracing Object
            ITracingService traceObj = context.GetExtension <ITracingService>();
            #endregion

            #region Workflow Instance
            //Workflow Context Object
            IWorkflowContext workflowConext = context.GetExtension <IWorkflowContext>();
            #endregion

            #region Organization Details
            //Organization Service Factory
            IOrganizationServiceFactory orgServiceFactory = context.GetExtension <IOrganizationServiceFactory>();
            //ORganization Service Context
            IOrganizationService orgServiceConext = orgServiceFactory.CreateOrganizationService(workflowConext.UserId);
            #endregion

            try
            {
                traceObj.Trace("Workflow Starts successfully");


                Guid Contactid = this.Contact.Get(context).Id;

                RetrieveRequest getContactBirthdayDate = new RetrieveRequest()
                {
                    ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "birthdate" }),
                    Target    = new EntityReference(this.Contact.Get(context).LogicalName, Contactid)
                };
                Entity EntityResponse = (Entity)((RetrieveResponse)orgServiceConext.Execute(getContactBirthdayDate)).Entity;

                DateTime?birthdate;
                if (EntityResponse.Contains("birthdate"))
                {
                    birthdate = (DateTime?)EntityResponse["birthdate"];
                }
                else
                {
                    birthdate = null;
                }

                if (birthdate == null)
                {
                    return;
                }
                DateTime nextBirthdate = CalculateNextBirthday(birthdate.Value);

                //Update the next birthday field on the entity
                Entity updateEntity = new Entity(this.Contact.Get(context).LogicalName);
                updateEntity.Id = Contactid;
                updateEntity["new_nextbirthday"] = nextBirthdate;

                orgServiceConext.Update(updateEntity);

                traceObj.Trace("Workflow End successfully");
            }
            catch (Exception e)
            {
                traceObj.Trace("Workflow Ends with Error");
                throw new InvalidPluginExecutionException("Error it is " + e.Message);
            }
        }
Exemple #35
0
        public static void Should_Retrieve_A_Correct_Entity_With_1_To_N_Related_Records()
        {
            var account1 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 1"
            };

            var account2 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 2"
            };

            var account3 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 3"
            };

            var contact1 = new Contact
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Contact 1",
                ParentCustomerId = account2.ToEntityReference()
            };

            var contact2 = new Contact
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Contact 2",
                ParentCustomerId = account1.ToEntityReference()
            };

            var contact3 = new Contact
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Contact 3",
                ParentCustomerId = account2.ToEntityReference()
            };

            var contact4 = new Contact
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Contact 4",
                ParentCustomerId = account3.ToEntityReference()
            };

            var contact5 = new Contact
            {
                Id        = Guid.NewGuid(),
                FirstName = "Contact 5"
            };

            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

            fakedContext.Initialize(new Entity[] { account1, account2, account3, contact1, contact2, contact3, contact4, contact5 });
            fakedContext.AddRelationship("contact_customer_accounts", new XrmFakedRelationship
                                         (
                                             entity1LogicalName: Contact.EntityLogicalName,
                                             entity1Attribute: "parentcustomerid",
                                             entity2LogicalName: Account.EntityLogicalName,
                                             entity2Attribute: "accountid"
                                         ));

            var request = new RetrieveRequest
            {
                ColumnSet            = new ColumnSet("name"),
                Target               = account2.ToEntityReference(),
                RelatedEntitiesQuery = new RelationshipQueryCollection
                {
                    {
                        new Relationship("contact_customer_accounts"),
                        new QueryExpression
                        {
                            ColumnSet  = new ColumnSet("firstname"),
                            EntityName = Contact.EntityLogicalName
                        }
                    }
                }
            };

            var result = (RetrieveResponse)fakedService.Execute(request);

            Assert.NotNull(result.Entity);

            //check account
            var resultAccount = result.Entity.ToEntity <Account>();

            Assert.Equal(account2.Id, resultAccount.Id);
            Assert.Equal(account2.Name, resultAccount.Name);

            //check relationship
            Assert.NotNull(resultAccount.contact_customer_accounts);
            Assert.Equal(2, resultAccount.contact_customer_accounts.Count());

            //check that contacts are retrieved
            var resultRelatedRecordsList = resultAccount.contact_customer_accounts;

            Assert.True(resultRelatedRecordsList.Any(x => x.Id == contact1.Id));
            Assert.True(resultRelatedRecordsList.Any(x => x.Id == contact3.Id));

            //check contacts (optional check)
            Assert.Equal(contact1.FirstName, resultRelatedRecordsList.First(x => x.Id == contact1.Id).FirstName);
            Assert.Equal(contact3.FirstName, resultRelatedRecordsList.First(x => x.Id == contact3.Id).FirstName);
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            //Check to see if the EntityReference has been set
            EntityReference loanApplication = this.LoanApplication.Get(executionContext);
            if (loanApplication == null)
            {
                throw new InvalidOperationException("Loan Application has not been specified", new ArgumentNullException("Loan Application"));
            }
            else if (loanApplication.LogicalName != CustomEntity)
            {
                throw new InvalidOperationException("Loan Application must reference a Loan Application entity",
                    new ArgumentException("Loan Application must be of type Loan Application", "Loan Application"));
            }

            //Retrieve the CrmService so that we can retrieve the loan application
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.InitiatingUserId);

            //Retrieve the Loan Application Entity
            Entity loanEntity;
            {
                //Create a request
                RetrieveRequest retrieveRequest = new RetrieveRequest();
                retrieveRequest.ColumnSet = new ColumnSet(new string[] { "new_loanapplicationid", "new_loanapplicantid" });
                retrieveRequest.Target = loanApplication;

                //Execute the request
                RetrieveResponse retrieveResponse = (RetrieveResponse)service.Execute(retrieveRequest);

                //Retrieve the Loan Application Entity
                loanEntity = retrieveResponse.Entity as Entity;
            }

            //Retrieve the Contact Entity
            Entity contactEntity;
            {
                //Create a request
                EntityReference loanApplicantId = (EntityReference)loanEntity["new_loanapplicantid"];

                RetrieveRequest retrieveRequest = new RetrieveRequest();
                retrieveRequest.ColumnSet = new ColumnSet(new string[] { "fullname", "new_ssn", "birthdate" });
                retrieveRequest.Target = loanApplicantId;

                //Execute the request
                RetrieveResponse retrieveResponse = (RetrieveResponse)service.Execute(retrieveRequest);

                //Retrieve the Loan Application Entity
                contactEntity = retrieveResponse.Entity as Entity;
            }

            //Retrieve the needed properties
            string ssn = (string)contactEntity["new_ssn"];
            string name = (string)contactEntity[ContactAttributes.FullName];
            DateTime? birthdate = (DateTime?)contactEntity[ContactAttributes.Birthdate];
            int creditScore;

            //This is where the logic for retrieving the credit score would be inserted
            //We are simply going to return a random number
            creditScore = (new Random()).Next(0, 1000);

            //Set the credit score property
            this.CreditScore.Set(executionContext, creditScore);

            //Check to see if the credit score should be saved to the entity
            //If the value of the property has not been set or it is set to true
            if (null != this.UpdateEntity && this.UpdateEntity.Get(executionContext))
            {
                //Create the entity
                Entity updateEntity = new Entity(loanApplication.LogicalName);
                updateEntity["new_loanapplicationid"] = loanEntity["new_loanapplicationid"];
                updateEntity["new_creditscore"] = this.CreditScore.Get(executionContext);

                //Update the entity
                service.Update(updateEntity);
            }
        }
        /// <summary>
        /// Demonstrates how to use the Deployment Web Service to create an organization 
        /// and poll the status of the job.
        /// </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 = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords(serverConfig, promptforDelete);

		    //<snippetUseAsyncDeploymentServiceMessages1>
                    // Instantiate DeploymentServiceClient for calling the service.
                    client =
                        ProxyClientHelper.CreateClient(
                        new Uri(serverConfig.DiscoveryUri.ToString()
                            .Replace("Services", "Deployment")
                            .Replace("Discovery", "Deployment")));

                    // Setting credentials from the current security context. 
                    if (serverConfig.Credentials == null)
                    {
                        client.ClientCredentials.Windows.ClientCredential =
                            CredentialCache.DefaultNetworkCredentials;
                    }
                    else
                    {
                        client.ClientCredentials.Windows.ClientCredential =
                            serverConfig.Credentials.Windows.ClientCredential;
                    }

                    using (client)
                    {
                        // Set properties for the new organization
                        Microsoft.Xrm.Sdk.Deployment.Organization organization = 
                            new Microsoft.Xrm.Sdk.Deployment.Organization
                        {
                            BaseCurrencyCode = "USD",
                            BaseCurrencyName = "US Dollar",
                            BaseCurrencyPrecision = 2,
                            BaseCurrencySymbol = "$",
                            BaseLanguageCode = 1033,
                            FriendlyName = _friendlyName,
                            UniqueName = _uniqueName,
                            SqlCollation = "Latin1_General_CI_AI",
                            SqlServerName = _sqlServerName,
                            SrsUrl = _srsUrl,
                            SqmIsEnabled = false
                        };

                        // Create a request for the deployment web service
                        // CRM server app pool must have permissions on SQL server
                        BeginCreateOrganizationRequest request = 
                            new BeginCreateOrganizationRequest
                        {
                            Organization = organization,
                            SysAdminName = _sysAdminName
                        };

                        // Execute the request
                        BeginCreateOrganizationResponse response = 
                            (BeginCreateOrganizationResponse)client.Execute(request);

                        // The operation is asynchronous, so the response object contains
                        // a unique identifier for the operation
                        Guid operationId = response.OperationId;

                        // Retrieve the Operation using the OperationId
                        RetrieveRequest retrieveOperationStatus = new RetrieveRequest();
                        retrieveOperationStatus.EntityType = 
                            DeploymentEntityType.DeferredOperationStatus;
                        retrieveOperationStatus.InstanceTag = 
                            new EntityInstanceId { Id = operationId };

                        RetrieveResponse retrieveResponse;
                        DeferredOperationStatus deferredOperationStatus;

                        Console.WriteLine("Retrieving state of the job...");

                        // Retrieve the Operation State until Organization is created
                        do
                        {
                            // Wait 3 secs to not overload server
                            Thread.Sleep(3000);

                            retrieveResponse =
                            (RetrieveResponse)client.Execute(retrieveOperationStatus);

                            deferredOperationStatus = 
                                ((DeferredOperationStatus)retrieveResponse.Entity);
                        }
                        while (deferredOperationStatus.State != 
                            DeferredOperationState.Processing &&
                            deferredOperationStatus.State != 
                            DeferredOperationState.Completed);

                        // Poll OrganizationStatusRequest
                        RetrieveRequest retrieveReqServer = new RetrieveRequest();
                        retrieveReqServer.EntityType = DeploymentEntityType.Organization;
                        retrieveReqServer.InstanceTag = new EntityInstanceId();
                        retrieveReqServer.InstanceTag.Name = organization.UniqueName;

                        RetrieveResponse retrieveRespServer;
                        OrganizationState orgState;

                        Console.WriteLine("Retrieving state of the organization...");

                        // Retrieve and check the Organization State until is enabled
                        do
                        {
                            retrieveRespServer =
                                (RetrieveResponse)client.Execute(retrieveReqServer);
                            _organizationID = 
                                ((Microsoft.Xrm.Sdk.Deployment.Organization)retrieveRespServer.Entity).Id;
                            orgState =
                                ((Microsoft.Xrm.Sdk.Deployment.Organization)retrieveRespServer.Entity).State;

                            // Wait 5 secs to not overload server
                            Thread.Sleep(5000);
                        }
                        while (orgState != OrganizationState.Enabled);

                        Console.WriteLine("Organization has been created!");

         		    //</snippetUseAsyncDeploymentServiceMessages1>
                        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>
        /// This method first connects to the Deployment service. Then,
        /// uses RetrieveRequest, UpdateRequest and UpdateAdvancedSettingsRequest.
        /// </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 = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {

                    // Instantiate DeploymentServiceClient for calling the service.
                    DeploymentServiceClient serviceClient =
                        ProxyClientHelper.CreateClient(
                        new Uri(serverConfig.DiscoveryUri.ToString()
                            .Replace("Services", "Deployment")
                            .Replace("Discovery", "Deployment")));

                    // Setting credentials from the current security context. 
                    if (serverConfig.Credentials != null)
                    {
                        serviceClient.ClientCredentials.Windows.ClientCredential =
                            serverConfig.Credentials.Windows.ClientCredential;
                    }
                    else
                    {
                        serviceClient.ClientCredentials.Windows.ClientCredential =
                            CredentialCache.DefaultNetworkCredentials;
                    }

                    #region RetrieveRequest
                    
                    // Retrieve all servers available in the deployment
                    Console.WriteLine("\nRetrieving list of servers...\n");
                    var servers =
                        serviceClient.RetrieveAll(DeploymentEntityType.Server);
                    
                    // Print list of all retrieved servers.
                    Console.WriteLine("Servers in your deployment");
                    Console.WriteLine("================================");
                    foreach (var server in servers)
                    {
                        Console.WriteLine(server.Name);
                    }
                    Console.WriteLine("<End of Listing>");
                    Console.WriteLine();                    

                    // Retrieve details of first (other than current server) or default server from previous call.
                    var serverId = servers.FirstOrDefault(x => x.Name.ToLowerInvariant() != serverConfig.ServerAddress.ToLowerInvariant());
                    // If no other server exists then default to existing one.
                    if (serverId == null)
                        serverId = servers.FirstOrDefault();

                    Console.WriteLine("\nRetrieving details of one server...\n");
                    RetrieveRequest retrieveReqServer = new RetrieveRequest();
                    retrieveReqServer.EntityType = DeploymentEntityType.Server;
                    retrieveReqServer.InstanceTag = serverId;
                    RetrieveResponse retrieveRespServer = 
                        (RetrieveResponse)serviceClient.Execute(retrieveReqServer);
                    Server serverToUpdate = 
                        (Server)retrieveRespServer.Entity;

                    Console.WriteLine("================================");
                    Console.WriteLine("Name: " + serverToUpdate.Name);
                    Console.WriteLine("State: " + serverToUpdate.State);
                    Console.WriteLine();

                    #endregion RetrieveRequest

                    #region UpdateRequest
                    // Avoid updating current server as it would disrupt the further sample execution.
                    if (servers.Count > 1)
                    {
                        // Modified the property we want to update
                        serverToUpdate.State = ServerState.Disabled;

                        // Update the deployment record
                        Console.WriteLine("\nUpdating server...\n");
                        UpdateRequest updateReq = new UpdateRequest();
                        updateReq.Entity = serverToUpdate;
                        UpdateResponse uptRes =
                            (UpdateResponse)serviceClient.Execute(updateReq);

                        // Retrieve server details again to check if it is updated
                        RetrieveResponse retrieveRespServerUpdated =
                            (RetrieveResponse)serviceClient.Execute(retrieveReqServer);
                        Server serverUpdated =
                            (Server)retrieveRespServerUpdated.Entity;

                        Console.WriteLine("Server Updated");
                        Console.WriteLine("================================");
                        Console.WriteLine("Name: " + serverUpdated.Name);
                        Console.WriteLine("State: " + serverUpdated.State);
                        Console.WriteLine();

                        // Revert change
                        serverUpdated.State = ServerState.Enabled;

                        Console.WriteLine("\nReverting change made in server...\n");
                        UpdateRequest updateReqRevert = new UpdateRequest();
                        updateReqRevert.Entity = serverUpdated;
                        UpdateResponse uptResRev =
                            (UpdateResponse)serviceClient.Execute(updateReqRevert);

                        RetrieveResponse retrieveRespServerReverted =
                            (RetrieveResponse)serviceClient.Execute(retrieveReqServer);
                        Server serverReverted =
                            (Server)retrieveRespServerReverted.Entity;

                        Console.WriteLine("Server Reverted");
                        Console.WriteLine("================================");
                        Console.WriteLine("Name: " + serverReverted.Name);
                        Console.WriteLine("State: " + serverReverted.State);
                        Console.WriteLine();
                    }
                    else
                        Console.WriteLine("\nMulti-server environment missing." 
                            + "\nSkipping server update request to avoid disruption in the sample execution.");
                    #endregion UpdateRequest

                    #region UpdateAdvanceRequest
                    
                    // Retrieve Advanced Settings for your organization.
                    Console.WriteLine("\nRetrieving Advanced Settings...\n");
                    RetrieveAdvancedSettingsRequest requestAdvSettings =
                        new RetrieveAdvancedSettingsRequest
                        {
                            ConfigurationEntityName = "Deployment",
                            ColumnSet = new ColumnSet("Id")
                        };
                    ConfigurationEntity configuration =
                        ((RetrieveAdvancedSettingsResponse)
                        serviceClient.Execute(requestAdvSettings)).Entity;

                    // Print out all advanced settings where IsWritable==true.
                    Console.WriteLine("Advanced deployment settings that can be updated");
                    Console.WriteLine("================================================");
                    foreach (var setting in configuration.Attributes)
                    {
                        if (setting.Key != "Id")
                        {
                            Console.WriteLine(
                                String.Format("{0}: {1}",
                                    setting.Key,
                                    setting.Value));
                        }
                    }
                    Console.WriteLine();

                    // Create the Configuration Entity with the values to update
                    ConfigurationEntity configEntity = new ConfigurationEntity();
                    configEntity.LogicalName = "Deployment";
                    configEntity.Attributes = new AttributeCollection();
                    configEntity.Attributes.Add
                        (new KeyValuePair<string, object>
                            ("AutomaticallyInstallDatabaseUpdates", true));

                    // Update Advanced Settings
                    Console.WriteLine("\nUpdating Advanced Settings...\n");
                    UpdateAdvancedSettingsRequest updateAdvanceReq = 
                        new UpdateAdvancedSettingsRequest();
                    updateAdvanceReq.Entity = configEntity;
                    serviceClient.Execute(updateAdvanceReq);

                    // Retrieve Advanced Settings to check if they have been updated
                    ConfigurationEntity configurationUpdated =
                        ((RetrieveAdvancedSettingsResponse)
                        serviceClient.Execute(requestAdvSettings)).Entity;

                    Console.WriteLine("Advanced deployment settings updated");
                    Console.WriteLine("================================================");
                    foreach (var setting in configurationUpdated.Attributes)
                    {
                        if (setting.Key != "Id")
                        {
                            Console.WriteLine(
                                String.Format("{0}: {1}",
                                    setting.Key,
                                    setting.Value));
                        }
                    }
                    Console.WriteLine();

                    // Revert change
                    ConfigurationEntity entityRevert = new ConfigurationEntity();
                    entityRevert.LogicalName = "Deployment";
                    entityRevert.Attributes = new AttributeCollection();
                    entityRevert.Attributes.Add
                        (new KeyValuePair<string, object>
                            ("AutomaticallyInstallDatabaseUpdates", false));

                    Console.WriteLine("\nReverting Advanced Settings...\n");
                    UpdateAdvancedSettingsRequest requestRevert = 
                        new UpdateAdvancedSettingsRequest();
                    requestRevert.Entity = entityRevert;
                    serviceClient.Execute(requestRevert);

                    ConfigurationEntity configurationReverted =
                        ((RetrieveAdvancedSettingsResponse)
                        serviceClient.Execute(requestAdvSettings)).Entity;
                    Console.WriteLine("Advanced deployment settings reverted");
                    Console.WriteLine("================================================");
                    foreach (var setting in configurationReverted.Attributes)
                    {
                        if (setting.Key != "Id")
                        {
                            Console.WriteLine(
                                String.Format("{0}: {1}",
                                    setting.Key,
                                    setting.Value));
                        }
                    }
                    Console.WriteLine();
                    #endregion UpdateAdvanceRequest
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<DeploymentServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Exemple #39
0
        public bool campaignExists(string campaignID)
        {
            try
            {
                isconnected();

                ArrayList arrayResults = new ArrayList();
                // Create the retrieve target.
                TargetRetrieveDynamic targetRetrieve = new TargetRetrieveDynamic();

                // Set the properties of the target.
                targetRetrieve.EntityName = "campaign";
                targetRetrieve.EntityId = new Guid(campaignID);

                // Create the request object.
                RetrieveRequest retrieve = new RetrieveRequest();
                ColumnSet col = new ColumnSet();

                // Set the properties of the request object.
                retrieve.Target = targetRetrieve;
                col.AddColumn("name");

                retrieve.ColumnSet = col;

                // Indicate that the BusinessEntity should be retrieved as a
                // DynamicEntity.
                retrieve.ReturnDynamicEntities = true;

                // Execute the request.
                RetrieveResponse retrieved = (RetrieveResponse)m_crmService.Execute(retrieve);

                // Extract the DynamicEntity from the request.
                DynamicEntity entity = (DynamicEntity)retrieved.BusinessEntity;
                if (entity.Properties["name"].Equals(null)) return false;
                return true;
             }
            catch (Exception)
            {
                return false;
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                // Local Variables.
                APIObject[] results = null;
                String requestId = null;
                String SOAPEndPoint = context.Session["SOAPEndPoint"].ToString();
                String internalOauthToken = context.Session["internalOauthToken"].ToString();
                String search = context.Request.QueryString["search"].ToString().Trim();

                // Create the SOAP binding for call.
                BasicHttpBinding binding = new BasicHttpBinding();
                binding.Name = "UserNameSoapBinding";
                binding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential;
                binding.MaxReceivedMessageSize = 2147483647;
                var client = new SoapClient(binding, new EndpointAddress(new Uri(SOAPEndPoint)));
                client.ClientCredentials.UserName.UserName = "******";
                client.ClientCredentials.UserName.Password = "******";

                using (var scope = new OperationContextScope(client.InnerChannel))
                {
                    // Add oAuth token to SOAP header.
                    XNamespace ns = "http://exacttarget.com";
                    var oauthElement = new XElement(ns + "oAuthToken", internalOauthToken);
                    var xmlHeader = MessageHeader.CreateHeader("oAuth", "http://exacttarget.com", oauthElement);
                    OperationContext.Current.OutgoingMessageHeaders.Add(xmlHeader);

                    // Setup RetrieveRequest for Subscriber object.
                    RetrieveRequest retrieveRequest = new RetrieveRequest();
                    retrieveRequest.ObjectType = "Subscriber";
                    String[] props = { "ID", "EmailAddress", "SubscriberKey", "Status" };
                    retrieveRequest.Properties = props;

                    // Query filter using Simplefilter.
                    SimpleFilterPart sfp = new SimpleFilterPart();
                    sfp.Property = "SubscriberKey";
                    sfp.SimpleOperator = SimpleOperators.like;
                    sfp.Value = new String[] { search.Trim() };

                    // Query filter using Simplefilter.
                    SimpleFilterPart sfp2 = new SimpleFilterPart();
                    sfp2.Property = "EmailAddress";
                    sfp2.SimpleOperator = SimpleOperators.like;
                    sfp2.Value = new String[] { search.Trim() };

                    // Complexfilter to OR the two SimpleFilters.
                    ComplexFilterPart cfp = new ComplexFilterPart();
                    cfp.LeftOperand = sfp;
                    cfp.RightOperand = sfp2;
                    cfp.LogicalOperator = LogicalOperators.OR;

                    // Use the ComplexFilter in RetrieveRequest.
                    retrieveRequest.Filter = cfp;

                    // Retrieve the subscribers.
                    String response = client.Retrieve(retrieveRequest, out requestId, out results);

                    // If results returned, loop through them a convert to JSON.
                    if (response != null && response.ToLower().Equals("ok"))
                    {
                        String strResults = string.Empty;
                        strResults += @"{""subscribers"": [";

                        if (results != null && results.Length > 0)
                        {
                            int i = 1;
                            foreach (Subscriber sub in results)
                            {
                                // Converting desired properties into JSON.
                                strResults += @"{""ID"":" + JsonConvert.SerializeObject(sub.ID).ToString().Trim() + ", ";
                                strResults += @"""EmailAddress"":" + JsonConvert.SerializeObject(sub.EmailAddress).ToString().Trim() + ", ";
                                strResults += @"""SubscriberKey"":" + JsonConvert.SerializeObject(sub.SubscriberKey).ToString().Trim() + ", ";
                                strResults += @"""Status"":" + JsonConvert.SerializeObject(sub.Status.ToString()).ToString().Trim() + " }";
                                if (i < results.Length)
                                    strResults += ", ";
                                i++;
                            }
                            strResults += " ]}";
                            // Return the resulting JSON from handler.
                            context.Response.Write(strResults);
                        }
                        else
                            context.Response.Write(@"{""subscribers"": []}");
                    }
                    else
                    {
                        context.Response.Write(@"{""subscribers"": []}");
                    }
                }
            }
            catch (Exception ex)
            {
                context.Response.Write(ex);
            }
        }
Exemple #41
0
 public static jQueryXmlHttpRequest Retrieve(RetrieveRequest request, Action <RetrieveResponse <UnitRow> > onSuccess, ServiceCallOptions options = null)
 {
     return(Q.ServiceRequest("TvHastanesi/Unit/Retrieve", request, onSuccess, options));
 }
Exemple #42
0
 public Entity Retrieve(string entityName, Guid id, ColumnSet columnSet)
 {
     var request = new RetrieveRequest
     {
         ColumnSet = columnSet,
         Target = CreateLookup(entityName, id)
     };
     return ((RetrieveResponse) Execute(request)).Entity;
 }
Exemple #43
0
        public static void Should_Retrieve_A_Correct_Entity_With_Relationship_Early_Bound()
        {
            var account1 = new Entity("account")
            {
                Id         = Guid.NewGuid(),
                Attributes =
                {
                    { "name", "Account 1" }
                }
            };

            var account2 = new Entity("account")
            {
                Id         = Guid.NewGuid(),
                Attributes =
                {
                    { "name", "Account 2" }
                }
            };

            var contact1 = new Entity("contact")
            {
                Id         = Guid.NewGuid(),
                Attributes =
                {
                    { "firstname",        "Contact 1"                  },
                    { "parentcustomerid", account2.ToEntityReference() }
                }
            };

            var contact2 = new Entity("contact")
            {
                Id         = Guid.NewGuid(),
                Attributes =
                {
                    { "firstname",        "Contact 2"                  },
                    { "parentcustomerid", account1.ToEntityReference() }
                }
            };

            var contact3 = new Entity("contact")
            {
                Id         = Guid.NewGuid(),
                Attributes =
                {
                    { "firstname",        "Contact 3"                  },
                    { "parentcustomerid", account2.ToEntityReference() }
                }
            };

            var contact4 = new Entity("contact")
            {
                Id         = Guid.NewGuid(),
                Attributes =
                {
                    { "firstname", "Contact 4" }
                }
            };

            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

            fakedContext.Initialize(new[] { account1, account2, contact1, contact2, contact3, contact4 });
            fakedContext.AddRelationship("contact_customer_accounts", new XrmFakedRelationship
                                         (
                                             entity1LogicalName: "contact",
                                             entity1Attribute: "parentcustomerid",
                                             entity2LogicalName: "account",
                                             entity2Attribute: "accountid"
                                         ));

            var request = new RetrieveRequest
            {
                ColumnSet            = new ColumnSet("name"),
                Target               = account2.ToEntityReference(),
                RelatedEntitiesQuery = new RelationshipQueryCollection
                {
                    {
                        new Relationship("contact_customer_accounts"),
                        new QueryExpression
                        {
                            ColumnSet  = new ColumnSet("firstname"),
                            EntityName = "contact"
                        }
                    }
                }
            };

            var result = (RetrieveResponse)fakedService.Execute(request);

            Assert.NotNull(result.Entity);

            //check account
            var resultAccount = result.Entity;

            Assert.Equal(account2.Id, resultAccount.Id);
            Assert.Equal(account2["name"], resultAccount["name"]);

            //check relationship
            Assert.NotNull(resultAccount.RelatedEntities.FirstOrDefault(x => x.Key.SchemaName == "contact_customer_accounts"));

            var relatedEntityCollection = resultAccount.RelatedEntities.FirstOrDefault(x => x.Key.SchemaName == "contact_customer_accounts");

            Assert.NotNull(relatedEntityCollection.Value);
            Assert.NotNull(relatedEntityCollection.Value.Entities);

            var relatedEntities = relatedEntityCollection.Value.Entities;

            Assert.Equal(2, relatedEntities.Count);

            Assert.True(relatedEntities.Any(x => x.Id == contact1.Id));
            Assert.True(relatedEntities.Any(x => x.Id == contact3.Id));

            //check contacts (optional check)
            Assert.Equal(contact1["firstname"], relatedEntities.First(x => x.Id == contact1.Id)["firstname"]);
            Assert.Equal(contact3["firstname"], relatedEntities.First(x => x.Id == contact3.Id)["firstname"]);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="org"></param>
        /// <param name="sysAdminName">domain\\user</param>
        public void CreateOrganization(Organization org, string sysAdminName)
        {
            try
            {
                var service = _crmServiceProvider.GetDeploymentService();
                using (service as IDisposable)
                {
                    //
                    var request = new BeginCreateOrganizationRequest
                    {
                        Organization = org,
                        SysAdminName = sysAdminName
                    };

                    // Execute the request
                    // upgradeLog.WriteInformation("Creating new Crm Organisation: {0}", org.UniqueName);
                    var response = (BeginCreateOrganizationResponse)service.Execute(request);

                    // The operation is asynchronous, so the response object contains
                    // a unique identifier for the operation
                    Guid operationId = response.OperationId;

                    // Retrieve the Operation using the OperationId
                    var retrieveOperationStatus = new RetrieveRequest();
                    retrieveOperationStatus.EntityType = DeploymentEntityType.DeferredOperationStatus;
                    retrieveOperationStatus.InstanceTag = new EntityInstanceId { Id = operationId };

                    DeferredOperationStatus deferredOperationStatus;

                    //  _upgradeLog.WriteInformation("Retrieving state of the create organisation job...");

                    // Retrieve the Operation State until Organization is created
                    do
                    {
                        // Wait 3 secs to not overload server
                        Thread.Sleep(3000);
                        var retrieveResponse = (RetrieveResponse)service.Execute(retrieveOperationStatus);
                        deferredOperationStatus = ((DeferredOperationStatus)retrieveResponse.Entity);
                    }
                    while (deferredOperationStatus.State != DeferredOperationState.Processing
                        && deferredOperationStatus.State != DeferredOperationState.Completed);

                    // Poll OrganizationStatusRequest
                    var retrieveReqServer = new RetrieveRequest();
                    retrieveReqServer.EntityType = DeploymentEntityType.Organization;
                    retrieveReqServer.InstanceTag = new EntityInstanceId();
                    retrieveReqServer.InstanceTag.Name = org.UniqueName;

                    Microsoft.Xrm.Sdk.Deployment.OrganizationState orgState;

                    //  upgradeLog.WriteInformation("Retrieving state of the organization...");

                    // Retrieve and check the Organization State until is enabled
                    RetrieveResponse resp = null;
                    do
                    {
                        resp = (RetrieveResponse)service.Execute(retrieveReqServer);
                        //  orgId = ((Microsoft.Xrm.Sdk.Deployment.Organization)retrieveRespServer.Entity).Id;
                        orgState = ((Organization)resp.Entity).State;
                        // Wait 5 secs to not overload server
                        Thread.Sleep(5000);
                    }
                    while (orgState != OrganizationState.Enabled && orgState != OrganizationState.Failed);
                    if (orgState == OrganizationState.Enabled)
                    {
                        //      upgradeLog.WriteInformation("Organization has been created!");
                    }
                    else
                    {
                        //      upgradeLog.WriteInformation("The organization create operation failed.!");
                        throw new Exception("The organization create operation failed.!");
                    }

                }
            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                Debug.WriteLine(ex.Message);
                //upgradeLog.WriteError("The application encountered an error.");
                //upgradeLog.WriteError("Timestamp: {0}", ex.Detail.Timestamp);
                //upgradeLog.WriteError("Code: {0}", ex.Detail.ErrorCode);
                //upgradeLog.WriteError("Message: {0}", ex.Detail.Message);
                //upgradeLog.WriteError("Plugin Trace: {0}", ex.Detail.TraceText);
                //upgradeLog.WriteError("Inner Fault: {0}",
                //    null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
                throw;
            }
            catch (TimeoutException ex)
            {
                Debug.WriteLine(ex.Message);
                //upgradeLog.WriteError("The application encountered an error..");
                //upgradeLog.WriteError("Message: {0}", ex.Message);
                //upgradeLog.WriteError("Stack Trace: {0}", ex.StackTrace);
                //upgradeLog.WriteError("Inner Fault: {0}", string.IsNullOrEmpty(ex.InnerException.Message) ? "No Inner Fault" : ex.InnerException.Message);
                throw;
            }
            catch (Exception ex)
            {
                //upgradeLog.WriteError("The application encountered  an error.");
                //upgradeLog.WriteError(ex.Message);

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

                    var fe = ex.InnerException as FaultException<OrganizationServiceFault>;
                    if (fe != null)
                    {
                        // upgradeLog.WriteError("Timestamp: {0}", fe.Detail.Timestamp);
                        // upgradeLog.WriteError("Code: {0}", fe.Detail.ErrorCode);
                        // upgradeLog.WriteError("Message: {0}", fe.Detail.Message);
                        // upgradeLog.WriteError("Plugin Trace: {0}", fe.Detail.TraceText);
                        // upgradeLog.WriteError("Inner Fault: {0}",
                        // null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
                    }
                }
                throw;
            }
            // Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException,
            // SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException.
        }
Exemple #45
0
        public static void Should_Retrieve_A_Correct_Entity_With_Multiple_Related_Record_Queries()
        {
            var account1 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 1"
            };

            var account2 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 2"
            };

            var lead1 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 1"
            };

            var lead2 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 2"
            };

            var lead3 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 3"
            };

            var contact1 = new Contact
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Contact 1",
                ParentCustomerId = account2.ToEntityReference()
            };

            var contact2 = new Contact
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Contact 2",
                ParentCustomerId = account1.ToEntityReference()
            };

            var contact3 = new Contact
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Contact 3",
                ParentCustomerId = account2.ToEntityReference()
            };

            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

            var accountLeadsRelationshipName = "accountleads_association";

            //account N:N leads
            fakedContext.AddRelationship(accountLeadsRelationshipName, new XrmFakedRelationship
            {
                IntersectEntity    = "accountleads",
                Entity1LogicalName = Account.EntityLogicalName,
                Entity1Attribute   = "accountid",
                Entity2LogicalName = Lead.EntityLogicalName,
                Entity2Attribute   = "leadid"
            });

            //account 1:N contacts
            fakedContext.AddRelationship("contact_customer_accounts", new XrmFakedRelationship
                                         (
                                             entity1LogicalName: Contact.EntityLogicalName,
                                             entity1Attribute: "parentcustomerid",
                                             entity2LogicalName: Account.EntityLogicalName,
                                             entity2Attribute: "accountid"
                                         ));

            fakedContext.Initialize(new Entity[] { account1, account2, lead1, lead2, lead3, contact1, contact2, contact3 });

            //associate account N:N leads
            fakedService.Associate(Account.EntityLogicalName, account2.Id, new Relationship(accountLeadsRelationshipName),
                                   new EntityReferenceCollection()
            {
                lead1.ToEntityReference(),
                lead3.ToEntityReference(),
            });

            fakedService.Associate(Account.EntityLogicalName, account1.Id, new Relationship(accountLeadsRelationshipName),
                                   new EntityReferenceCollection()
            {
                lead2.ToEntityReference()
            });

            //build a request
            var request = new RetrieveRequest
            {
                ColumnSet            = new ColumnSet("name"),
                Target               = account2.ToEntityReference(),
                RelatedEntitiesQuery = new RelationshipQueryCollection
                {
                    {
                        new Relationship(accountLeadsRelationshipName),
                        new QueryExpression
                        {
                            ColumnSet  = new ColumnSet("subject"),
                            EntityName = Lead.EntityLogicalName
                        }
                    },
                    {
                        new Relationship("contact_customer_accounts"),
                        new QueryExpression
                        {
                            ColumnSet  = new ColumnSet("firstname"),
                            EntityName = Contact.EntityLogicalName
                        }
                    }
                }
            };

            //execute request
            var result = (RetrieveResponse)fakedService.Execute(request);

            Assert.NotNull(result.Entity);

            //check account
            var resultAccount = result.Entity.ToEntity <Account>();

            Assert.Equal(account2.Id, resultAccount.Id);

            //check first relationship
            Assert.NotNull(resultAccount.accountleads_association);
            Assert.Equal(2, resultAccount.accountleads_association.Count());

            //and check another relationship
            Assert.NotNull(resultAccount.contact_customer_accounts);
            Assert.Equal(2, resultAccount.contact_customer_accounts.Count());
        }
Exemple #46
0
 public static jQueryXmlHttpRequest Retrieve(RetrieveRequest request, Action <RetrieveResponse <TerritoryRow> > onSuccess = null, ServiceCallOptions options = null)
 {
     return(null);
 }
Exemple #47
0
        public static void Should_Retrieve_A_Correct_Entity_With_N_To_N_Related_Records_And_Related_Record_Query_Criteria()
        {
            var account1 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 1"
            };

            var account2 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 2"
            };

            var account3 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 3"
            };

            var lead1 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 1"
            };

            var lead2 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 2"
            };

            var lead3 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 3"
            };

            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

            var relationshipName = "accountleads_association";

            fakedContext.AddRelationship(relationshipName, new XrmFakedRelationship
            {
                IntersectEntity    = "accountleads",
                Entity1LogicalName = Account.EntityLogicalName,
                Entity1Attribute   = "accountid",
                Entity2LogicalName = Lead.EntityLogicalName,
                Entity2Attribute   = "leadid"
            });

            fakedContext.Initialize(new Entity[] { account1, account2, account3, lead1, lead2, lead3 });
            fakedService.Associate(Account.EntityLogicalName, account2.Id, new Relationship(relationshipName),
                                   new EntityReferenceCollection()
            {
                lead2.ToEntityReference(),
                lead3.ToEntityReference(),
            });

            fakedService.Associate(Account.EntityLogicalName, account1.Id, new Relationship(relationshipName),
                                   new EntityReferenceCollection()
            {
                lead1.ToEntityReference(),
            });

            var request = new RetrieveRequest
            {
                ColumnSet            = new ColumnSet("name"),
                Target               = account2.ToEntityReference(),
                RelatedEntitiesQuery = new RelationshipQueryCollection
                {
                    {
                        new Relationship(relationshipName),
                        new QueryExpression
                        {
                            ColumnSet  = new ColumnSet("subject"),
                            EntityName = Lead.EntityLogicalName,
                            Criteria   = new FilterExpression
                            {
                                Conditions =
                                {
                                    new ConditionExpression("subject",   ConditionOperator.Equal, "Lead 3"),
                                    new ConditionExpression("statecode", ConditionOperator.Equal, 0)
                                }
                            }
                        }
                    }
                }
            };

            var result = (RetrieveResponse)fakedService.Execute(request);

            Assert.NotNull(result.Entity);

            //check account
            var resultAccount = result.Entity.ToEntity <Account>();

            Assert.Equal(account2.Id, resultAccount.Id);

            Assert.NotNull(resultAccount.accountleads_association);
            Assert.Equal(1, resultAccount.accountleads_association.Count());
            Assert.Equal(lead3.Id, resultAccount.accountleads_association.First().Id);
        }
 public RetrieveResponse <MyRow> Retrieve(IDbConnection connection, RetrieveRequest request)
 {
     return(new MyRepository().Retrieve(connection, request));
 }
 public RetrieveResponse <MyRow> Retrieve(IDbConnection connection, RetrieveRequest request)
 {
     return(new MyRetrieveHandler().Process(connection, request));
 }
 public RetrieveResponse<MyRow> Retrieve(IDbConnection connection, RetrieveRequest request)
 {
     return new MyRepository().Retrieve(connection, request);
 }
        //</snippetGetTimeZoneCodeByLocalizedName>

        /// <summary>
        /// Retieve time zone by id
        /// </summary>
        private void RetrieveTimeZoneById()
        {
            if (!_timeZoneId.HasValue)
                return;

            // In addition to the RetrieveRequest message, 
            // you may use the IOrganizationService.Retrieve method
            var request = new RetrieveRequest
            {
                Target = new EntityReference(
                    TimeZoneDefinition.EntityLogicalName, _timeZoneId.Value),
                ColumnSet = new ColumnSet("standardname")
            };

            var response = (RetrieveResponse)_serviceProxy.Execute(request);

            Console.WriteLine(String.Concat("Retrieve request on time zone ",
                _timeZoneId.Value, ".  Name: ", response.Entity.
                ToEntity<TimeZoneDefinition>().StandardName));
        }
Exemple #52
0
        /// <summary>
        /// This method is used to get attributes from a specified entity. It returns Dictionary containing all the required attributes values.
        /// </summary>
        /// <param name="entityGuid">GUID of the entity</param>
        /// <param name="entityName_">The entity name type (contact,lead,...)</param>
        ///<param name="entityAttributes">The ArrayList containing the attributes names types you want to retrieve (firstname,lastname,...)</param>
        public Dictionary<string, string> getEntity(Guid entityGuid, string entityName_, ArrayList entityAttributes)
        {
            Dictionary<string, string> arrayData = new Dictionary<string, string>();
            try
            {
                isconnected();

                ArrayList arrayResults = new ArrayList();
                // Create the retrieve target.
                TargetRetrieveDynamic targetRetrieve = new TargetRetrieveDynamic();

                // Set the properties of the target.
                targetRetrieve.EntityName = entityName_;
                targetRetrieve.EntityId = entityGuid;

                // Create the request object.
                RetrieveRequest retrieve = new RetrieveRequest();
                ColumnSet col = new ColumnSet();

                // Set the properties of the request object.
                retrieve.Target = targetRetrieve;
                for (int i = 0; i < entityAttributes.Count; i++)
                {
                    col.AddColumn(entityAttributes[i].ToString());
                }

                retrieve.ColumnSet = col;

                // Indicate that the BusinessEntity should be retrieved as a
                // DynamicEntity.
                retrieve.ReturnDynamicEntities = true;

                // Execute the request.
                RetrieveResponse retrieved = (RetrieveResponse)m_crmService.Execute(retrieve);

                // Extract the DynamicEntity from the request.
                DynamicEntity entity = (DynamicEntity)retrieved.BusinessEntity;

                Microsoft.Crm.Sdk.CrmDateTime crmDateTimeVar = new Microsoft.Crm.Sdk.CrmDateTime();
                Microsoft.Crm.Sdk.CrmNumber crmNumberVar = new Microsoft.Crm.Sdk.CrmNumber();
                Picklist crmPickList = new Picklist();
                Guid crmGuid = new Guid();
                Microsoft.Crm.Sdk.Key keyVar = new Microsoft.Crm.Sdk.Key();
                Lookup lookupVar = new Lookup();
                Microsoft.Crm.Sdk.CrmBoolean boolVar = new Microsoft.Crm.Sdk.CrmBoolean();
                for (int i = 0; i < entityAttributes.Count; i++)
                {
                    if (entity.Properties.Contains(entityAttributes[i].ToString()))
                    {
                        if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(crmDateTimeVar.GetType()))
                        {
                            crmDateTimeVar = (Microsoft.Crm.Sdk.CrmDateTime)entity.Properties[entityAttributes[i].ToString()];
                            arrayData.Add(entityAttributes[i].ToString(),crmDateTimeVar.date.ToString());
                        }
                        else
                        {
                            if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(crmNumberVar.GetType()))
                            {
                                crmNumberVar = (Microsoft.Crm.Sdk.CrmNumber)entity.Properties[entityAttributes[i].ToString()];
                                arrayData.Add(entityAttributes[i].ToString(), crmNumberVar.Value.ToString());
                            }
                            else
                            {
                                if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(keyVar.GetType()))
                                {
                                    keyVar = (Microsoft.Crm.Sdk.Key)entity.Properties[entityAttributes[i].ToString()];
                                    arrayData.Add(entityAttributes[i].ToString(), keyVar.Value.ToString());
                                }
                                else
                                {
                                    if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(lookupVar.GetType()))
                                    {
                                        lookupVar = (Microsoft.Crm.Sdk.Lookup)entity.Properties[entityAttributes[i].ToString()];
                                        arrayData.Add(entityAttributes[i].ToString(), lookupVar.Value.ToString());
                                    }
                                    else
                                    {
                                        if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(boolVar.GetType()))
                                        {
                                            boolVar = (Microsoft.Crm.Sdk.CrmBoolean)entity.Properties[entityAttributes[i].ToString()];
                                            arrayData.Add(entityAttributes[i].ToString(), boolVar.Value.ToString());
                                        }
                                        else
                                        {
                                            if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(crmPickList.GetType()))
                                            {
                                                crmPickList = (Microsoft.Crm.Sdk.Picklist)entity.Properties[entityAttributes[i].ToString()];
                                                arrayData.Add(entityAttributes[i].ToString(), crmPickList.Value.ToString());
                                            }
                                            else
                                            {
                                                if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(crmGuid.GetType()))
                                                {
                                                    crmGuid = (Guid)entity.Properties[entityAttributes[i].ToString()];
                                                    arrayData.Add(entityAttributes[i].ToString(), crmGuid.ToString());
                                                }
                                                else
                                                {
                                                    arrayData.Add(entityAttributes[i].ToString(), entity.Properties[entityAttributes[i].ToString()].ToString());
                                                }

                                            }

                                        }
                                    }
                                }

                            }
                        }

                    }
                    else
                    {
                        arrayData.Add(entityAttributes[i].ToString(), "");
                    }
                }
                return arrayData;
            }
            catch (SoapException ex)
            {
                throw new InvalidPluginExecutionException("!SoapException!\n" + ex.Detail.SelectSingleNode("//description").InnerText);
            }
            catch (Exception ex)
            {
                throw new ESC_CRM_EX.getEntityException(ex.Message, entityName_, entityGuid);
            }
        }
 // Retrieve row request
 public static IRestResponse <RetrieveResponse <MyRow> > Retrieve <MyRow>(string baseUrl, string resource, RetrieveRequest retrieveRequest)
 {
     #region Retrieve Service Request
     IRestResponse <RetrieveResponse <MyRow> > response = new RestResponse <RetrieveResponse <MyRow> >();
     if (InternetConnection.IsConnectedToInternet() == true)
     {
         try
         {
             var restClient = new RestClient(baseUrl);
             var request    = new RestRequest(Method.POST);
             request.AddHeader("Content-Type", "application/octet-stream");
             request.AddHeader("Authorization", "Bearer " + VMMainModel.Instance.AuthToken);
             request.Resource = resource;
             request.AddJsonBody(retrieveRequest);
             request.RequestFormat = DataFormat.Json;
             response = restClient.Execute <RetrieveResponse <MyRow> >(request);
         }
         catch (Exception ex)
         {
             response.ErrorMessage   = ex.Message;
             response.ErrorException = ex.InnerException;
         }
         return(response);
     }
     else
     {
         response.ErrorMessage = "Internet connection not available. Please check connection.";
         return(response);
     }
     #endregion
 }