Exemplo n.º 1
0
        /// <summary>
        /// Button to login to CRM and create a CrmService Client
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoginBtn_Click(object sender, RoutedEventArgs e)
        {
            #region Login Control
            // Establish the Login control
            CrmLogin ctrl = new CrmLogin();
            // Wire Event to login response.
            ctrl.ConnectionToCrmCompleted += ctrl_ConnectionToCrmCompleted;
            // Show the dialog.
            ctrl.ShowDialog();

            // Handel return.
            if (ctrl.CrmConnectionMgr != null && ctrl.CrmConnectionMgr.CrmSvc != null && ctrl.CrmConnectionMgr.CrmSvc.IsReady)
            {
                MessageBox.Show("Good Connect");
            }
            else
            {
                MessageBox.Show("BadConnect");
            }

            #endregion

            #region CRMServiceClient
            if (ctrl.CrmConnectionMgr != null && ctrl.CrmConnectionMgr.CrmSvc != null && ctrl.CrmConnectionMgr.CrmSvc.IsReady)
            {
                CrmServiceClient svcClient = ctrl.CrmConnectionMgr.CrmSvc;
                if (svcClient.IsReady)
                {
                    service = svcClient.OrganizationServiceProxy;
                }
            }
            #endregion
        }
Exemplo n.º 2
0
        /// <summary>
        /// Connect to Microsoft Dynamics CRM, and get an instance of CRMServiceClient
        /// </summary>

        private void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            // Create an instance of the XRM Tooling common login control
            _ctrl = new CrmLogin();

            /// Wire event to the CRM sign-in response.
            _ctrl.ConnectionToCrmCompleted += ctrl_ConnectionToCrmCompleted;
            UpdateStatus("Initiating connection to CRM...");

            /// Show the XRM Tooling common login control.
            _ctrl.ShowDialog();

            /// Validate if you are connected to CRM
            if (_ctrl.CrmConnectionMgr != null && _ctrl.CrmConnectionMgr.CrmSvc != null && _ctrl.CrmConnectionMgr.CrmSvc.IsReady)
            {
                UpdateStatus("Connected to CRM! (Version: " + _ctrl.CrmConnectionMgr.CrmSvc.ConnectedOrgVersion.ToString() +
                             "; Org: " + _ctrl.CrmConnectionMgr.CrmSvc.ConnectedOrgUniqueName.ToString() + ")");
                UpdateStatus("***************************************");
                UpdateStatus("Click Start to create, retrieve, update, and delete (optional) an account record.");
                btnSignIn.IsEnabled = false;
                btnCRUD.IsEnabled   = true;
            }
            // If you are not connected to CRM; display the last error and last CRM excption
            else
            {
                UpdateStatus("The connection to CRM failed or was cancelled by the user.");
            }
        }
Exemplo n.º 3
0
 private async void btnConnect_Click(object sender, EventArgs e)
 {
     if (!isConnecting)
     {
         isConnecting = true;
         Console.WriteLine("Trying to connect!");
         CrmLogin ctrl = new CrmLogin();
         ctrl.ConnectionToCrmCompleted += Ctrl_ConnectionToCrmCompleted;
         ctrl.Closed += Ctrl_Closed;
         ctrl.ShowDialog();
         //await Task.Run(() =>
         //{
         //    conn = new CDSConnection();
         //    orgService = conn.GetService();
         //    isConnected = true;
         //    this.BeginInvoke((Action)(() =>
         //            {
         //                tsConnectionStatus.Text = "Connected";
         //                Console.WriteLine("Connected to Organization Service!");
         //            }
         //    ));
         //    isConnecting = false;
         //});
     }
 }
Exemplo n.º 4
0
        private bool DoInteractiveLogin()
        {
            log.Trace($"Entered {nameof(DoInteractiveLogin)}()");

            bool flag = false;

            _connMgr = null;

            var loginDlg = new CrmLogin()
            {
                WindowStartupLocation = WindowStartupLocation.CenterScreen
            };

            loginDlg.ConnectionToCrmCompleted += LoginDlg_ConnectionToCrmCompleted;

            loginDlg.ShowDialog();

            loginDlg.ConnectionToCrmCompleted -= LoginDlg_ConnectionToCrmCompleted;

            try
            {
                if (loginDlg.CrmConnectionMgr != null &&
                    loginDlg.CrmConnectionMgr.CrmSvc != null &&
                    loginDlg.CrmConnectionMgr.CrmSvc.IsReady)
                {
                    _connMgr = loginDlg.CrmConnectionMgr;
                    _crmSvc  = _connMgr.CrmSvc;

                    flag = true;
                    log.Trace($"{nameof(_crmSvc)}.IsReady = true");
                }
                else
                {
                    if (loginDlg.CrmConnectionMgr != null)
                    {
                        if (!string.IsNullOrWhiteSpace(loginDlg.CrmConnectionMgr.LastError))
                        {
                            log.Error(loginDlg.CrmConnectionMgr.LastError);
                        }
                        if (loginDlg.CrmConnectionMgr.LastException != null)
                        {
                            log.Error(loginDlg.CrmConnectionMgr.LastException.Message, loginDlg.CrmConnectionMgr.LastException);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                log.Error($"Unexpected error: {exception.Message}", exception);
                flag = false;
            }

            log.Trace($"Exiting {nameof(DoInteractiveLogin)}()");
            return(flag);
        }
Exemplo n.º 5
0
        private void LoginToCRM()
        {
            // Establish the Login control
            CrmLogin ctrl = new CrmLogin();

            // Wire Event to login response.
            ctrl.ConnectionToCrmCompleted += ctrl_ConnectionToCrmCompleted;
            // Show the dialog.
            ctrl.ShowDialog();

            if (ctrl.CrmConnectionMgr != null && ctrl.CrmConnectionMgr.CrmSvc != null && ctrl.CrmConnectionMgr.CrmSvc.IsReady)
            {
                _svcClient = ctrl.CrmConnectionMgr.CrmSvc;

                ((MainWindow)Application.Current.MainWindow).Title = $"Plugin Terminator : Connected to {_svcClient.CrmConnectOrgUriActual.Host} : {_svcClient.ConnectedOrgFriendlyName}";
            }
        }
Exemplo n.º 6
0
        private async Task InitConnection(string message, ConnectionType connectionType)
        {
            // Establish the Login control
            CrmLogin ctrl = new CrmLogin();

            // Wire Event to login response.
            ctrl.ConnectionToCrmCompleted += ctrl_ConnectionToCrmCompleted;
            // Show the dialog.
            ctrl.ShowDialog();

            // Handel return.
            if (ctrl.CrmConnectionMgr != null && ctrl.CrmConnectionMgr.CrmSvc != null && ctrl.CrmConnectionMgr.CrmSvc.IsReady)
            {
                IsLoading   = true;
                LoadMessage = message;

                // Handel return.
                if (ctrl.CrmConnectionMgr != null && ctrl.CrmConnectionMgr.CrmSvc != null &&
                    ctrl.CrmConnectionMgr.CrmSvc.IsReady)
                {
                    // Assign local property
                    props.OrgUriActual           = ctrl.CrmConnectionMgr.CrmSvc.CrmConnectOrgUriActual.ToString();
                    props.ConnectedOrgUniqueName = ctrl.CrmConnectionMgr.CrmSvc.ConnectedOrgUniqueName;
                    props.OrgUri = ctrl.CrmConnectionMgr.ConnectedOrgPublishedEndpoints[EndpointType.WebApplication];

                    props.FriendlyName = ctrl.CrmConnectionMgr.CrmSvc.ConnectedOrgFriendlyName;
                    props.AuthenticationProviderType =
                        ctrl.CrmConnectionMgr.CrmSvc.OrganizationServiceProxy.ServiceConfiguration.AuthenticationType;

                    ClientCredentials credentials = ctrl.CrmConnectionMgr.CrmSvc.OrganizationServiceProxy.ClientCredentials;
                    if (credentials.UserName.UserName != null)
                    {
                        props.UserName = credentials.UserName.UserName;
                        props.Password = credentials.UserName.Password;
                    }
                    else if (credentials.Windows.ClientCredential.UserName != null)
                    {
                        props.DomainName = credentials.Windows.ClientCredential.Domain;
                        props.UserName   = credentials.Windows.ClientCredential.UserName;
                        props.Password   = credentials.Windows.ClientCredential.Password;
                    }
                    if (connectionType == ConnectionType.ChangeCredentialConnect)
                    {
                        IsLoaded = true;
                    }
                }

                if (connectionType == ConnectionType.Connect)
                {
                    // Then generate assembly
                    await Task.Run(() => LoadData());

                    // Set Context class name.
                    props._cxInfo.CustomTypeInfo.CustomTypeName = "Microsoft.Pfe.Xrm.XrmContext";
                }

                IsLoading = false;
            }
            else
            {
                MessageBox.Show("BadConnect");
            }
        }
        /// <summary>
        /// Button to login to CRM and create a CrmService Client
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            #region Login Control
            // Establish the Login control
            CrmLogin ctrl = new CrmLogin();
            // Wire Event to login response.
            ctrl.ConnectionToCrmCompleted += ctrl_ConnectionToCrmCompleted;
            // Show the dialog.
            ctrl.ShowDialog();

            // Handel return.
            if (ctrl.CrmConnectionMgr != null && ctrl.CrmConnectionMgr.CrmSvc != null && ctrl.CrmConnectionMgr.CrmSvc.IsReady)
            {
                MessageBox.Show("Good Connect");
            }
            else
            {
                MessageBox.Show("BadConnect");
            }

            #endregion

            #region CRMServiceClient
            if (ctrl.CrmConnectionMgr != null && ctrl.CrmConnectionMgr.CrmSvc != null && ctrl.CrmConnectionMgr.CrmSvc.IsReady)
            {
                //                CrmServiceClient svcClient = ctrl.CrmConnectionMgr.CrmSvc;
                //                if (svcClient.IsReady)
                //                {
                //                    // Get data from CRM .
                //                    string FetchXML =
                //                        @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                //                        <entity name='account'>
                //                            <attribute name='name' />
                //                            <attribute name='primarycontactid' />
                //                            <attribute name='telephone1' />
                //                            <attribute name='accountid' />
                //                            <order attribute='name' descending='false' />
                //                          </entity>
                //                        </fetch>";

                //                    var Result = svcClient.GetEntityDataByFetchSearchEC(FetchXML);
                //                    if (Result != null)
                //                    {
                //                        MessageBox.Show(string.Format("Found {0} records\nFirst Record name is {1}", Result.Entities.Count, Result.Entities.FirstOrDefault().GetAttributeValue<string>("name")));
                //                    }


                //                    // Core API using SDK OOTB
                //                    CreateRequest req = new CreateRequest();
                //                    Entity accENt = new Entity("account");
                //                    accENt.Attributes.Add("name", "TESTFOO");
                //                    req.Target = accENt;
                //                    CreateResponse res = (CreateResponse)svcClient.OrganizationServiceProxy.Execute(req);
                //                    //CreateResponse res = (CreateResponse)svcClient.ExecuteCrmOrganizationRequest(req, "MyAccountCreate");
                //                    MessageBox.Show(res.id.ToString());



                //                    // Using Xrm.Tooling helpers.
                //                    Dictionary<string, CrmDataTypeWrapper> newFields = new Dictionary<string, CrmDataTypeWrapper>();
                //                    // Create a new Record. - Account
                //                    newFields.Add("name", new CrmDataTypeWrapper("CrudTestAccount", CrmFieldType.String));
                //                    Guid guAcctId = svcClient.CreateNewRecord("account", newFields);

                //                    MessageBox.Show(string.Format("New Record Created {0}", guAcctId));
                //}
            }
            #endregion
        }
        /// <summary>
        /// Launch CrmLogin and let user login, then set CrmProperties.
        /// </summary>
        private async Task <bool> LoginToCrm()
        {
            bool isSuccess = false;

            // Establish the Login control
            CrmLogin ctrl = new CrmLogin();

            // Wire Event to login response.
            ctrl.ConnectionToCrmCompleted += ctrl_ConnectionToCrmCompleted;
            // Show the dialog.
            ctrl.ShowDialog();

            // Let UI go.
            await Task.Delay(1);

            if (ctrl.CrmConnectionMgr != null && ctrl.CrmConnectionMgr.CrmSvc != null && ctrl.CrmConnectionMgr.CrmSvc.IsReady)
            {
                IsLoading = true;

                LoadMessage = "Signing to Dynamics CRM....";

                // Assign local property
                props.OrgUri       = ctrl.CrmConnectionMgr.ConnectedOrgPublishedEndpoints[EndpointType.WebApplication];
                props.FriendlyName = ctrl.CrmConnectionMgr.CrmSvc.ConnectedOrgFriendlyName;
                props.AuthenticationProviderType = ctrl.CrmConnectionMgr.CrmSvc.OrganizationServiceProxy.ServiceConfiguration.AuthenticationType.ToString();

                if (props.AuthenticationProviderType == "OnlineFederation")
                {
                    props.Authority = await DiscoveryAuthority();
                }
                else if (props.AuthenticationProviderType == "Federation")
                {
                    props.Authority = ctrl.CrmConnectionMgr.CrmSvc.OrganizationServiceProxy.ServiceConfiguration.CurrentIssuer.IssuerAddress.Uri.AbsoluteUri.Replace(ctrl.CrmConnectionMgr.CrmSvc.OrganizationServiceProxy.ServiceConfiguration.CurrentIssuer.IssuerAddress.Uri.AbsolutePath, "/adfs/ls");
                }

                // Store User Credentials.
                ClientCredentials credentials = ctrl.CrmConnectionMgr.CrmSvc.OrganizationServiceProxy.ClientCredentials;
                if (credentials.UserName.UserName != null)
                {
                    props.UserName = credentials.UserName.UserName;
                    props.Password = credentials.UserName.Password;
                }
                else if (credentials.Windows.ClientCredential.UserName != null)
                {
                    props.DomainName = credentials.Windows.ClientCredential.Domain;
                    props.UserName   = credentials.Windows.ClientCredential.UserName;
                    props.Password   = credentials.Windows.ClientCredential.Password;
                }

                // Version
                if (ctrl.CrmConnectionMgr.CrmSvc.ConnectedOrgVersion != null)
                {
                    props.Version = ctrl.CrmConnectionMgr.CrmSvc.ConnectedOrgVersion.ToString();
                }
                else
                {
                    props.Version = await CheckVersion();
                }

                if (Version.Parse(props.Version).Major < 8)
                {
                    MessageBox.Show("WebAPI is available after Dynamics CRM 2016 only.");
                }
                else
                {
                    isSuccess = true;
                }

                IsLoading = false;
            }
            else
            {
                MessageBox.Show("BadConnect");
            }

            return(isSuccess);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Button to login to CRM and create a CrmService Client
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            List <EntityObj> lst = new List <EntityObj>();

            List <SystemUser> lstActiveUsr = new List <SystemUser>();


            #region Login Control
            // Establish the Login control
            CrmLogin ctrl = new CrmLogin();
            // Wire Event to login response.
            ctrl.ConnectionToCrmCompleted += ctrl_ConnectionToCrmCompleted;
            // Show the dialog.
            ctrl.ShowDialog();

            // Handel return.
            if (ctrl.CrmConnectionMgr != null && ctrl.CrmConnectionMgr.CrmSvc != null && ctrl.CrmConnectionMgr.CrmSvc.IsReady)
            {
                MessageBox.Show("Good Connect");
            }
            else
            {
                MessageBox.Show("BadConnect");
            }

            #endregion

            #region CRMServiceClient
            if (ctrl.CrmConnectionMgr != null && ctrl.CrmConnectionMgr.CrmSvc != null && ctrl.CrmConnectionMgr.CrmSvc.IsReady)
            {
                svcClient = ctrl.CrmConnectionMgr.CrmSvc;
                ctrl.Close();
                this.loginbutton.Visibility = Visibility.Hidden;


                if (svcClient.IsReady)
                {
                    this.label.Visibility    = Visibility.Visible;
                    this.comboBox.Visibility = Visibility.Visible;

                    //RetrieveEntityRequest req = new RetrieveEntityRequest()
                    //{
                    //    EntityFilters = EntityFilters.All,
                    //    RetrieveAsIfPublished=true,
                    //    LogicalName="account"
                    //};

                    //RetrieveEntityResponse res = (RetrieveEntityResponse)svcClient.OrganizationServiceProxy.Execute(req);



                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters         = EntityFilters.Entity,
                        RetrieveAsIfPublished = true
                    };

                    // Retrieve the MetaData.
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)svcClient.OrganizationServiceProxy.Execute(request);

                    foreach (EntityMetadata currentEntity in response.EntityMetadata)
                    {
                        //if (currentEntity.DisplayName.UserLocalizedLabel!=null)
                        //{
                        EntityObj obj = new EntityObj();
                        obj.EntityName = currentEntity.LogicalName;
                        obj.EntityOC   = currentEntity.ObjectTypeCode.ToString();

                        lst.Add(obj);
                        //}
                    }

                    lst = lst.OrderBy(o => o.EntityName).ToList();
                    this.comboBox.DisplayMemberPath = "EntityName";
                    this.comboBox.SelectedValuePath = "EntityOC";
                    this.comboBox.ItemsSource       = lst;
                    this.comboBox.Text = "Select Entity Name";

                    this.label3.Visibility    = Visibility.Visible;
                    this.comboBox2.Visibility = Visibility.Visible;

                    DataCollection <Entity> activeUsrsColl = MainWindow.FindEnabledUsers(svcClient.OrganizationServiceProxy);

                    foreach (Entity user in activeUsrsColl)
                    {
                        SystemUser sysUser = new SystemUser();
                        sysUser.FullName     = user["fullname"].ToString();
                        sysUser.SystemUserID = user["systemuserid"].ToString();

                        lstActiveUsr.Add(sysUser);
                    }

                    lstActiveUsr = lstActiveUsr.OrderBy(o => o.FullName).ToList();
                    this.comboBox2.DisplayMemberPath = "FullName";
                    this.comboBox2.SelectedValuePath = "SystemUserID";
                    this.comboBox2.ItemsSource       = lstActiveUsr;
                    this.comboBox2.Text = "Select Active User Name";

                    // Get data from CRM .
                    //string FetchXML =
                    //    @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                    //                    <entity name='account'>
                    //                        <attribute name='name' />
                    //                        <attribute name='primarycontactid' />
                    //                        <attribute name='telephone1' />
                    //                        <attribute name='accountid' />
                    //                        <order attribute='name' descending='false' />
                    //                      </entity>
                    //                    </fetch>";

                    //var Result = svcClient.GetEntityDataByFetchSearchEC(FetchXML);
                    //if (Result != null)
                    //{
                    //    MessageBox.Show(string.Format("Found {0} records\nFirst Record name is {1}", Result.Entities.Count, Result.Entities.FirstOrDefault().GetAttributeValue<string>("name")));
                    //}


                    //// Core API using SDK OOTB
                    //CreateRequest req = new CreateRequest();
                    //Entity accENt = new Entity("account");
                    //accENt.Attributes.Add("name", "TESTFOO");
                    //req.Target = accENt;
                    //CreateResponse res = (CreateResponse)svcClient.OrganizationServiceProxy.Execute(req);
                    ////CreateResponse res = (CreateResponse)svcClient.ExecuteCrmOrganizationRequest(req, "MyAccountCreate");
                    //MessageBox.Show(res.id.ToString());



                    //// Using Xrm.Tooling helpers.
                    //Dictionary<string, CrmDataTypeWrapper> newFields = new Dictionary<string, CrmDataTypeWrapper>();
                    //// Create a new Record. - Account
                    //newFields.Add("name", new CrmDataTypeWrapper("CrudTestAccount", CrmFieldType.String));
                    //Guid guAcctId = svcClient.CreateNewRecord("account", newFields);

                    //MessageBox.Show(string.Format("New Record Created {0}", guAcctId));
                }
            }
            #endregion
        }