Example #1
0
        /// <summary>
        /// gets a CRM connection using AppSettings["crmconnectionstring"] + AppSettings["impersonatorcredentials"]
        /// </summary>
        /// <returns></returns>
        public static Microsoft.Xrm.Client.CrmConnection GetCrmConnection()
        {
            string connectionString = ConfigurationManager.AppSettings["crmconnectionstring"] + ConfigurationManager.AppSettings["impersonatorcredentials"];

            Microsoft.Xrm.Client.CrmConnection connection = CrmConnection.Parse(connectionString);
            return(connection);
        }
        static void Main(string[] args)
        {
            string connectionString = "Url=https://dynamicscrmnext.crm5.dynamics.com; [email protected]; Password=P@$$w0rd1;";

            Microsoft.Xrm.Client.CrmConnection connection = CrmConnection.Parse(connectionString);

            try
            {
                using (OrganizationService orgService = new OrganizationService(connection))
                {
                    CrmEntityReference target = new CrmEntityReference();
                    target.Id          = new Guid("AAD1D9DD-7B98-E411-80D6-C4346BADB628");
                    target.LogicalName = Incident.EntityLogicalName;

                    MergeRequest mergeRequest = new MergeRequest();
                    mergeRequest.SubordinateId          = new Guid("ACD1D9DD-7B98-E411-80D6-C4346BADB628");
                    mergeRequest.Target                 = target;
                    mergeRequest.PerformParentingChecks = false;

                    Incident incidentUpdate = new Incident();
                    incidentUpdate.Title = "Merged2";

                    mergeRequest.UpdateContent = incidentUpdate;

                    MergeResponse mergeResponse = (MergeResponse)orgService.Execute(mergeRequest);
                    string        s             = "";
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }
Example #3
0
        /// <summary>
        /// gets a CRM connection using supplied username and password + AppSettings["crmconnectionstring"]
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static Microsoft.Xrm.Client.CrmConnection GetCrmConnection(string username, string password)
        {
            string connectionString = ConfigurationManager.AppSettings["crmconnectionstring"];

            connectionString += " Username="******"; Password=" + password;
            Microsoft.Xrm.Client.CrmConnection connection = CrmConnection.Parse(connectionString);
            return(connection);
        }
        private static void InitializeOrgService(Guid CallerId)
        {
            String connectionString = GetServiceConfiguration();

            // Establish a connection to the organization web _orgSvc using CrmConnection.
            Microsoft.Xrm.Client.CrmConnection connection = CrmConnection.Parse(connectionString);

            if (CallerId != null && CallerId != Guid.Empty)
            {
                connection.CallerId = CallerId;
            }
            _orgSvc = new OrganizationService(connection);
        }
Example #5
0
        /// <summary>
        /// Validate method to attempt to connect to CRM with supplied username/password and then execute a whoami request
        /// </summary>
        /// <param name="username">crm username</param>
        /// <param name="password">crm password</param>
        public override void Validate(string username, string password)
        {
            //get the httpcontext so we can store the user guid for impersonation later
            HttpContext context = HttpContext.Current;

            //if username or password are null, obvs we can't continue
            if (null == username || null == password)
            {
                throw new ArgumentNullException();
            }

            //get the crm connection
            Microsoft.Xrm.Client.CrmConnection connection = CrmUtils.GetCrmConnection(username, password);

            //try the whoami request
            //if it fails (user can't be authenticated, is disabled, etc.), the client will get a soap fault message
            using (OrganizationService service = new OrganizationService(connection))
            {
                try
                {
                    WhoAmIRequest  req        = new WhoAmIRequest();
                    WhoAmIResponse resp       = (WhoAmIResponse)service.Execute(req);
                    Entity         systemuser = CrmUtils.GetSystemUser(resp.UserId, service);


                    CrmIdentity crmIdentity = new CrmIdentity();
                    crmIdentity.Name      = (string)systemuser["fullname"];
                    crmIdentity.FirstName = (string)systemuser["firstname"];
                    crmIdentity.LastName  = (string)systemuser["lastname"];
                    crmIdentity.Email     = (string)systemuser["internalemailaddress"];
                    crmIdentity.UserId    = resp.UserId;
                    crmIdentity.SetAuthenticated(true);

                    List <string> roles = CrmUtils.GetUserRoles(resp.UserId, service);
                    foreach (string role in roles)
                    {
                        crmIdentity.AddRole(role);
                    }

                    context.User = new GenericPrincipal(crmIdentity, roles.ToArray());
                }
                catch (System.ServiceModel.Security.MessageSecurityException ex)
                {
                    throw new FaultException(ex.Message);
                }
                catch (Exception ex)
                {
                    throw new FaultException(ex.Message);
                }
            }
        }
Example #6
0
        /// <summary>
        /// Validate method to attempt to connect to CRM with supplied username/password and then execute a whoami request
        /// </summary>
        /// <param name="username">crm username</param>
        /// <param name="password">crm password</param>
        public override void Validate(string username, string password)
        {
            //get the httpcontext so we can store the user guid for impersonation later
            HttpContext context = HttpContext.Current;

            //if username or password are null, obvs we can't continue
            if (null == username || null == password)
            {
                throw new ArgumentNullException();
            }

            //get the crm connection using the simplified connection string method

            // the following assumes the server url is stored in the web.config appsettings collection like so:
            // <add key="crmconnectionstring" value="Url=https://crm.example.com; "/>
            string connectionString = ConfigurationManager.AppSettings["crmconnectionstring"];

            connectionString += " Username="******"; Password=" + password;

            Microsoft.Xrm.Client.CrmConnection connection = CrmConnection.Parse(connectionString);

            //try the whoami request
            //if it fails (user can't be authenticated, is disabled, etc.), the client will get a soap fault message
            using (OrganizationService service = new OrganizationService(connection))
            {
                try
                {
                    WhoAmIRequest  req   = new WhoAmIRequest();
                    WhoAmIResponse resp  = (WhoAmIResponse)service.Execute(req);
                    List <string>  roles = GetUserRoles(resp.UserId, service);
                    context.User = new GenericPrincipal(new GenericIdentity(resp.UserId.ToString()), roles.ToArray());
                }
                catch (System.ServiceModel.Security.MessageSecurityException ex)
                {
                    throw new FaultException(ex.Message);
                }
                catch (Exception ex)
                {
                    throw new FaultException(ex.Message);
                }
            }
        }
Example #7
0
 /**  Connection related  **/
 #region connection
 public void Connexion()
 {
     try
     {
         if (this.orgService == null)
         {
             // Obtient information de connexion à CRM via
             // le fichier de configuration app.config.
             String connectionString = GetServiceConfiguration();
             if (connectionString != null)
             {
                 // Établir une connexion CRM avec le service  CrmConnection.
                 Microsoft.Xrm.Client.CrmConnection connection = CrmConnection.Parse(connectionString);
                 orgService = new OrganizationService(connection);
             }
         }
     }
     catch (Exception exception)
     {
         Console.WriteLine("Exception :" + exception.Message);
     }
 }
Example #8
0
 public CrmOrganizationServiceContext(CrmConnection connection)
     : this(CrmConfigurationManager.CreateService(connection))
 {
     _shouldDisposeService = true;
 }
        /// <summary>
        /// The Run() method first connects to the Organization service. Afterwards,
        /// basic create, retrieve, update, and delete entity operations are performed.
        /// </summary>
        /// <param name="connectionString">Provides service connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(String connectionString, bool promptforDelete)
        {
            try
            {
                // Establish a connection to the organization web service using CrmConnection.
                Microsoft.Xrm.Client.CrmConnection connection = CrmConnection.Parse(connectionString);

                // Obtain an organization service proxy.
                // The using statement assures that the service proxy will be properly disposed.
                using (_orgService = new OrganizationService(connection))
                {
                    //Create any entity records this sample requires.
                    CreateRequiredRecords();

                    // Obtain information about the logged on user from the web service.
                    Guid       userid     = ((WhoAmIResponse)_orgService.Execute(new WhoAmIRequest())).UserId;
                    SystemUser systemUser = (SystemUser)_orgService.Retrieve("systemuser", userid,
                                                                             new ColumnSet(new string[] { "firstname", "lastname" }));
                    Console.WriteLine("Logged on user is {0} {1}.", systemUser.FirstName, systemUser.LastName);

                    // Retrieve the version of Microsoft Dynamics CRM.
                    RetrieveVersionRequest  versionRequest  = new RetrieveVersionRequest();
                    RetrieveVersionResponse versionResponse =
                        (RetrieveVersionResponse)_orgService.Execute(versionRequest);
                    Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version);

                    // Instantiate an account object. Note the use of option set enumerations defined in OptionSets.cs.
                    // Refer to the Entity Metadata topic in the SDK documentation to determine which attributes must
                    // be set for each entity.
                    Account account = new Account {
                        Name = "Testi Käyttäjä"
                    };
                    account.AccountCategoryCode = new OptionSetValue((int)AccountAccountCategoryCode.PreferredCustomer);
                    account.CustomerTypeCode    = new OptionSetValue((int)AccountCustomerTypeCode.Investor);

                    // Create an account record named Fourth Coffee.
                    _accountId = _orgService.Create(account);

                    Console.Write("{0} {1} created, ", account.LogicalName, account.Name);

                    // Retrieve the several attributes from the new account.
                    ColumnSet cols = new ColumnSet(
                        new String[] { "name", "address1_postalcode", "lastusedincampaign" });

                    Account retrievedAccount = (Account)_orgService.Retrieve("account", _accountId, cols);
                    Console.Write("retrieved, ");

                    // Update the postal code attribute.
                    retrievedAccount.Address1_PostalCode = "98052";

                    // The address 2 postal code was set accidentally, so set it to null.
                    retrievedAccount.Address2_PostalCode = null;

                    // Shows use of a Money value.
                    retrievedAccount.Revenue = new Money(5000000);

                    // Shows use of a Boolean value.
                    retrievedAccount.CreditOnHold = false;

                    // Update the account record.
                    _orgService.Update(retrievedAccount);
                    Console.WriteLine("and updated.");

                    // Delete any entity records this sample created.
                    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 void OnAuthenticateRequest(object source, EventArgs eventArgs)
        {
            HttpApplication app = (HttpApplication)source;

            //the Authorization header is checked if present
            string authHeader = app.Request.Headers["Authorization"];

            if (!string.IsNullOrEmpty(authHeader))
            {
                string authStr = app.Request.Headers["Authorization"];

                if (authStr == null || authStr.Length == 0)
                {
                    // No credentials; anonymous request
                    return;
                }

                authStr = authStr.Trim();
                if (authStr.IndexOf("Basic", 0) != 0)
                {
                    // header is not correct...we'll pass it along and
                    // assume someone else will handle it
                    return;
                }


                authStr = authStr.Trim();


                string encodedCredentials = authStr.Substring(6);

                byte[] decodedBytes =
                    Convert.FromBase64String(encodedCredentials);
                string s = new ASCIIEncoding().GetString(decodedBytes);

                string[] userPass = s.Split(new char[] { ':' });
                string   username = userPass[0];
                string   password = userPass[1];

                Microsoft.Xrm.Client.CrmConnection connection = GetCrmConnection(username, password);
                using (OrganizationService service = new OrganizationService(connection))
                {
                    WhoAmIRequest  req  = new WhoAmIRequest();
                    WhoAmIResponse resp = (WhoAmIResponse)service.Execute(req);
                    if (resp.Results.Count > 0)
                    {
                        app.Context.User = new GenericPrincipal(new GenericIdentity(resp.UserId.ToString()), new string [] { "none" });
                    }
                    else
                    {
                        DenyAccess(app);
                        return;
                    }
                }

                if (Membership.ValidateUser(username, password))
                {
                    string[] roles = Roles.GetRolesForUser(username);
                }
                else
                {
                }
            }
            else
            {
                app.Response.StatusCode = 401;
                app.Response.End();
            }
        }
Example #11
0
        /// <summary>
        /// This method runs the query and returns the results to the client
        /// </summary>
        /// <param name="query">Name of the query. Corresponding file will be named "query".xml</param>
        /// <param name="inputParameters">Array of parameters for substitution in the query.</param>
        /// <returns></returns>
        public List <List <ParameterItem> > Retrieve(string query, List <ParameterItem> inputParameters)
        {
            //need to get the id of the user to impersonate from the HttpContext.User object
            HttpContext context   = HttpContext.Current;
            Guid        runasuser = Guid.Empty;

            //get a reference to the custom CRM identity object
            CrmIdentity crmIdentity = (CrmIdentity)context.User.Identity;

            if (context != null)
            {
                //if we're to this point, this value should be populated. if not, we'll see an error later when we try to use a blank id
                runasuser = crmIdentity.UserId;
            }

            //instantiate the output object
            List <List <ParameterItem> > output = new List <List <ParameterItem> >();

            //get a connection to crm
            Microsoft.Xrm.Client.CrmConnection connection = CrmUtils.GetCrmConnection();

            //set callerid for impersonation
            connection.CallerId = runasuser;

            //execute the query, loop through results, format output, etc.
            using (OrganizationService service = new OrganizationService(connection))
            {
                //code to show impersonated user details - can leave commented out in prod
                //List<ParameterItem> runasitem = new List<ParameterItem>();
                //runasitem.Add(new ParameterItem { Name = "runasuser", Value = runasuser });
                //runasitem.Add(new ParameterItem { Name = "roles", Value = context.User.IsInRole("sales manager").ToString() });
                //output.Add(runasitem);

                //prepare a query to retrieve the wrapper query record from crm
                string wrapperQueryFetch = @"<fetch distinct='false' mapping='logical' output-format='xml-platform' version='1.0'>
	                <entity name='la_wrapperquery'>
		                <attribute name='la_wrapperqueryid'/>
		                <attribute name='la_name'/>
		                <attribute name='la_query'/>
		                <order descending='false' attribute='la_name'/>
		                <filter type='and'>
			                <condition attribute='statuscode' value='1' operator='eq'/>
			                <condition attribute='la_name' value='{$queryname}' operator='eq'/>
		                </filter>
	                </entity>
                </fetch>";

                wrapperQueryFetch = wrapperQueryFetch.Replace("{$queryname}", query);

                //retrieve the wrapper query record
                EntityCollection wrapperQueryCollection = service.RetrieveMultiple(new FetchExpression(wrapperQueryFetch));
                if (wrapperQueryCollection.Entities.Count == 1)
                {
                    Entity wrapperQuery = wrapperQueryCollection.Entities[0];

                    //prepare the wrapper query by doing any necessary parameter substitutions
                    string fetchXml = PrepareFetchQuery((string)wrapperQuery["la_query"], inputParameters);

                    //execute the actual query
                    EntityCollection results = service.RetrieveMultiple(new FetchExpression(fetchXml));
                    foreach (Entity entity in results.Entities)
                    {
                        //loop through the mapping key-value pairs
                        List <ParameterItem> item = new List <ParameterItem>();
                        foreach (var attribute in entity.Attributes)
                        {
                            item.Add(new ParameterItem {
                                Name = attribute.Key, Value = CrmUtils.GetAttributeValue(attribute.Value)
                            });

                            //the _name and _type fields do some user-friendly formatting
                            string attributelabel = (string)CrmUtils.GetAttributeName(attribute.Value);
                            if (attributelabel != "")
                            {
                                item.Add(new ParameterItem {
                                    Name = attribute.Key + "_name", Value = attributelabel
                                });
                            }

                            string attributeentitytype = (string)CrmUtils.GetAttributeEntityType(attribute.Value);
                            if (attributeentitytype != "")
                            {
                                item.Add(new ParameterItem {
                                    Name = attribute.Key + "_type", Value = attributeentitytype
                                });
                            }
                        }

                        //optionset labels and formatted currency values are available in the formattedvalues collection
                        foreach (var fv in entity.FormattedValues)
                        {
                            item.Add(new ParameterItem {
                                Name = fv.Key + "_formattedvalue", Value = fv.Value
                            });
                        }

                        output.Add(item);
                    }
                }
                else
                {
                    throw new Exception("Could not find active query with the supplied name.");
                }
                return(output);
            }
        }