Esempio n. 1
0
    //ProjectTeamDataSet ds = new ProjectTeamDataSet();
    //ProjectTeamDataSet.ProjectTeamRow row = ds.ProjectTeam.NewProjectTeamRow();
    //row.PROJ_UID = projectGuid;
    //row.RES_UID = resourceGuid;
    //row.NEW_RES_UID = resourceGuid;
    //ds.ProjectTeam.AddProjectTeamRow(row);
    public void QueueUpdateProjectTeam(Guid sessionUid, Guid projectUid, ProjectTeamDataSet dataset)
    {
        Guid jobUid = Guid.NewGuid();

        try
        {
            this.projectSvc.QueueUpdateProjectTeam(jobUid, sessionUid, projectUid, dataset);
        }
        catch (SoapException soapException)
        {
            List <string> queueErrors = new List <string>();
            queueErrors.Add(soapException.Message);
            Library.PSClientError clientError = new Library.PSClientError(soapException);
            Library.PSErrorInfo[] errors      = clientError.GetAllErrors();
            foreach (Library.PSErrorInfo error in errors)
            {
                queueErrors.Add(error.ErrId.ToString());
            }
        }
    }
        public static string HandleSoapException(SoapException ex)
        {
            PSLibrary.PSClientError error  = new PSLibrary.PSClientError(ex);
            PSLibrary.PSErrorInfo[] errors = error.GetAllErrors();
            string errMess = "==============================\r\nError: \r\n";

            for (int i = 0; i < errors.Length; i++)
            {
                errMess += "\n" + ex.Message.ToString() + "\r\n";
                errMess += "".PadRight(30, '=') + "\r\nPSCLientError Output:\r\n \r\n";
                errMess += errors[i].ErrId.ToString() + "\n";

                for (int j = 0; j < errors[i].ErrorAttributes.Length; j++)
                {
                    errMess += "\r\n\t" + errors[i].ErrorAttributeNames()[j] + ": "
                               + errors[i].ErrorAttributes[j];
                }
                errMess += "\r\n".PadRight(30, '=');
            }
            return(errMess);
        }
Esempio n. 3
0
        /// <summary>
        /// Extract a PSClientError object from the ServiceModel.FaultException,
        /// for use in output of the GetPSClientError stack of errors.
        /// </summary>
        /// <param name="e"></param>
        /// <param name="errOut">Shows that FaultException has more information 
        /// about the errors than PSClientError has. FaultException can also contain 
        /// other types of errors, such as failure to connect to the server.</param>
        /// <returns>PSClientError object, for enumerating errors.</returns>
        public static PSLibrary.PSClientError GetPSClientError(FaultException e, 
                                                               out string errOut)
        {
            const string PREFIX = "GetPSClientError() returns null: ";
            errOut = string.Empty;
            PSLibrary.PSClientError psClientError = null;

            if (e == null)
            {
                errOut = PREFIX + "Null parameter (FaultException e) passed in.";
                psClientError = null;
            }
            else
            {
                // Get a ServiceModel.MessageFault object.
                var messageFault = e.CreateMessageFault();

                if (messageFault.HasDetail)
                {
                    using (var xmlReader = messageFault.GetReaderAtDetailContents())
                    {
                        var xml = new XmlDocument();
                        xml.Load(xmlReader);

                        var serverExecutionFault = xml["ServerExecutionFault"];
                        if (serverExecutionFault != null)
                        {
                            var exceptionDetails = serverExecutionFault["ExceptionDetails"];
                            if (exceptionDetails != null)
                            {
                                try
                                {
                                    errOut = exceptionDetails.InnerXml + "\r\n";
                                    psClientError =
                                        new PSLibrary.PSClientError(exceptionDetails.InnerXml);
                                }
                                catch (InvalidOperationException ex)
                                {
                                    errOut = PREFIX + "Unable to convert fault exception info ";
                                    errOut += "a valid Project Server error message. Message: \n\t";
                                    errOut += ex.Message;
                                    psClientError = null;
                                }
                            }
                            else
                            {
                                errOut = PREFIX + "The FaultException e is a ServerExecutionFault, "
                                    + "but does not have ExceptionDetails.";
                            }
                        }
                        else
                        {
                            errOut = PREFIX + "The FaultException e is not a ServerExecutionFault.";
                        }
                    }
                }
                else // No detail in the MessageFault.
                {
                    errOut = PREFIX + "The FaultException e does not have any detail.";
                }
            }
            errOut += "\r\n" + e.ToString() + "\r\n";
            return psClientError;
        }
Esempio n. 4
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    // Get the template Guid from the selected item in the list
                    Guid templateGuid = new Guid(ListBox1.SelectedValue);

                    SPWeb spWeb = SPContext.Current.Web;
                    {
                        // Create instance of Project
                        WebSvcProject.Project project = new WebSvcProject.Project();
                        project.Url = ViewState["siteURL"] + "/_vti_bin/psi/project.asmx";
                        project.UseDefaultCredentials = true;

                        // Guid for new project
                        Guid newProjectGuid = Guid.NewGuid();

                        if (templateGuid == Guid.Empty)
                        {
                            WebSvcProject.ProjectDataSet dsProjectDataSet      = new WebSvcProject.ProjectDataSet();
                            WebSvcProject.ProjectDataSet.ProjectRow projectRow = dsProjectDataSet.Project.NewProjectRow();
                            projectRow.PROJ_UID             = newProjectGuid;
                            projectRow.PROJ_NAME            = ViewState["projectName"].ToString();
                            projectRow.PROJ_INFO_START_DATE = System.DateTime.Now;
                            projectRow.PROJ_TYPE            = 0; //0 is for project and 1 is for template
                            dsProjectDataSet.Project.AddProjectRow(projectRow);

                            //create a project
                            Guid job = Guid.NewGuid();
                            project.QueueCreateProject(job, dsProjectDataSet, false);
                            WaitForQueue(job);

                            job = Guid.NewGuid();
                            project.QueuePublish(job, newProjectGuid, true, spWeb.Url);
                            WaitForQueue(job);
                        }
                        else
                        {
                            SPSecurity.RunWithElevatedPrivileges(delegate()
                            {
                                Guid owner     = getResourceUid();
                                newProjectGuid = project.CreateProjectFromTemplate(templateGuid, ViewState["projectName"].ToString());

                                WebSvcProject.ProjectDataSet templateProject;
                                Guid jobGuid     = Guid.NewGuid();
                                Guid sessionGuid = Guid.NewGuid();

                                project.CheckOutProject(newProjectGuid, sessionGuid, "");
                                templateProject = project.ReadProject(newProjectGuid, WebSvcProject.DataStoreEnum.WorkingStore);
                                WebSvcProject.ProjectDataSet temp = ((WebSvcProject.ProjectDataSet)(templateProject.Copy()));


                                temp.Tables[temp.Project.TableName].Rows[0][temp.Project.ProjectOwnerIDColumn] = owner;
                                WebSvcProject.ProjectDataSet updateProjectDataSet = new WebSvcProject.ProjectDataSet();
                                updateProjectDataSet.Project.Merge(temp.Tables[temp.Project.TableName], true);
                                updateProjectDataSet = ((WebSvcProject.ProjectDataSet)updateProjectDataSet.GetChanges(DataRowState.Modified));

                                project.QueueUpdateProject(jobGuid, sessionGuid, updateProjectDataSet, false);
                                WaitForQueue(jobGuid);

                                jobGuid = Guid.NewGuid();
                                project.QueueCheckInProject(jobGuid, newProjectGuid, true, sessionGuid, "");
                                WaitForQueue(jobGuid);
                            });
                        }

                        SPList list = spWeb.Lists["Project Center"];
                        spWeb.AllowUnsafeUpdates = true;
                        // Find the item by ID
                        SPListItem item = list.Items.GetItemById(itemId);
                        // Set the new project Guid in the List
                        item["projectguid"] = newProjectGuid;
                        item.SystemUpdate();
                        pwaUrl      = ViewState["siteURL"].ToString();
                        projectName = item.Title;
                        // Add record to PublisherCheck Table
                        InsertRowIntoPublisherCheck(newProjectGuid);

                        pnlOpenProject.Visible = true;
                        pnlNewProject.Visible  = false;

                        string url    = pwaUrl + "/Project%20Detail%20Pages/Schedule.aspx?ProjUid=" + newProjectGuid + "&isDlg=1";
                        string source = Request["source"];
                        if (source != null && source != "")
                        {
                            if (url.Contains("?"))
                            {
                                url += "&source=" + source;
                            }
                            else
                            {
                                url += "?source=" + source;
                            }
                        }
                        Response.Redirect(url);
                    }
                }
                catch (SoapException ex)
                {
                    PSLibrary.PSClientError error  = new PSLibrary.PSClientError(ex);
                    PSLibrary.PSErrorInfo[] errors = error.GetAllErrors();
                    string errMess = "Error: ";
                    for (int i = 0; i < errors.Length; i++)
                    {
                        errMess += ex.Message.ToString() + "  ";
                        errMess += "PSCLientError Output: ";
                        errMess += errors[i].ErrId.ToString() + "  ";

                        for (int j = 0; j < errors[i].ErrorAttributes.Length; j++)
                        {
                            errMess += "  " + errors[i].ErrorAttributeNames()[j] + ": " + errors[i].ErrorAttributes[j];
                        }
                    }
                    lblError.Text = errMess;
                }
                catch (WebException ex)
                {
                    string errMess = ex.Message.ToString() +
                                     "\n\nLog on, or check the Project Server Queuing Service";
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "Error", "<script language='javascript'>alert('" + errMess + "');</script>");
                }
                catch (Exception ex)
                {
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "Error", "<script language='javascript'>alert('" + ex.Message + "');</script>");
                }
            });
        }
Esempio n. 5
0
        internal static void UpdateLookupTables(LookupTableDataSet lookupTableDataSet)
        {
            using (OperationContextScope scope = new OperationContextScope(lookupTableClient.InnerChannel))
            {
                try
                {
                    WcfHelpers.UseCorrectHeaders(true);
                    lookupTableClient.CheckOutLookupTables(new Guid[] { new Guid(Constants.LOOKUP_ENTITY_ID) });
                    lookupTableClient.UpdateLookupTables(lookupTableDataSet, false, true, 1033);
                    //lookupTableClient.CheckInLookupTables(new Guid[] { new Guid(Constants.LOOKUP_ENTITY_ID) },true);
                }
                catch (SoapException ex)
                {
                    string errMess = "";
                    // Pass the exception to the PSClientError constructor to get
                    // all error information.
                    PSLib.PSClientError psiError = new PSLib.PSClientError(ex);
                    PSLib.PSErrorInfo[] psiErrors = psiError.GetAllErrors();

                    for (int j = 0; j < psiErrors.Length; j++)
                    {
                        errMess += psiErrors[j].ErrId.ToString() + "\n";
                    }
                    errMess += "\n" + ex.Message.ToString();
                    // Send error string to console or message box.
                }
            }
        }
        public void CreateEnterpriseProjectType(string pwaOrigem, string pwaDestino, string nameProjecType, Guid Uid)
        {
            //SvcWorkflow.WorkflowDataSet.EnterpriseProjectTypeDataTable dt = new SvcWorkflow.WorkflowDataSet.EnterpriseProjectTypeDataTable();
            try
            {
                SvcWorkflow.WorkflowClient clientWorkflowOrigem = new SvcWorkflow.WorkflowClient(Binding, endPointAdress(pwaOrigem, "/_vti_bin/psi/Workflow.asmx"));
                clientWorkflowOrigem.ClientCredentials.Windows.ClientCredential = new NetworkCredential(this.User, this.PassWord, this.Domain);

                SvcWorkflow.WorkflowClient clientWorkflowDestino = new SvcWorkflow.WorkflowClient(Binding, endPointAdress(pwaDestino, "/_vti_bin/psi/Workflow.asmx"));
                clientWorkflowDestino.ClientCredentials.Windows.ClientCredential = new NetworkCredential(this.User, this.PassWord, this.Domain);

                SvcWorkflow.WorkflowDataSet dsEnterpriseOrigem   = clientWorkflowOrigem.ReadEnterpriseProjectType(Uid);
                SvcWorkflow.WorkflowDataSet dsEnterpriseDestino  = new SvcWorkflow.WorkflowDataSet();
                SvcWorkflow.WorkflowDataSet dsEnterpriseDestino2 = clientWorkflowDestino.ReadEnterpriseProjectTypeList();

                //SvcWorkflow.WorkflowDataSet.EnterpriseProjectTypePDPsDataTable dtPDP = clientWorkflowOrigem.read

                Guid ENTERPRISE_PROJECT_TYPE_UID = Guid.Empty;

                foreach (SvcWorkflow.WorkflowDataSet.EnterpriseProjectTypeRow itemEnterprise in dsEnterpriseOrigem.EnterpriseProjectType.Rows)
                {
                    SvcWorkflow.WorkflowDataSet.EnterpriseProjectTypeRow oRow = dsEnterpriseDestino.EnterpriseProjectType.NewEnterpriseProjectTypeRow();
                    foreach (DataColumn itemColumn in dsEnterpriseOrigem.EnterpriseProjectType.Columns)
                    {
                        if (!dsEnterpriseDestino.EnterpriseProjectType.Columns.Contains(itemColumn.ToString()))
                        {
                            continue;
                        }

                        if (itemColumn.ToString().Equals("WORKFLOW_ASSOCIATION_UID") || itemColumn.ToString().Equals("WORKFLOW_ASSOCIATION_NAME"))
                        {
                            continue;
                        }

                        var dnsEquals = GetDnsName(pwaOrigem) == GetDnsName(pwaDestino);

                        if (nameProjecType.Length > 0 && itemColumn.ToString().Equals("ENTERPRISE_PROJECT_TYPE_NAME"))
                        {
                            oRow[itemColumn.ToString()] = nameProjecType;
                            continue;
                        }

                        if (itemColumn.ToString().Equals("ENTERPRISE_PROJECT_TYPE_UID"))
                        {
                            ENTERPRISE_PROJECT_TYPE_UID = Guid.Parse(itemEnterprise[itemColumn.ToString()].ToString());
                        }

                        if (itemColumn.ToString().Equals("ENTERPRISE_PROJECT_TYPE_UID") && dnsEquals)
                        {
                            ENTERPRISE_PROJECT_TYPE_UID = Guid.NewGuid();
                            oRow[itemColumn.ToString()] = ENTERPRISE_PROJECT_TYPE_UID;
                            continue;
                        }

                        if (itemColumn.ToString().Equals("ENTERPRISE_PROJECT_WORKSPACE_TEMPLATE_NAME"))
                        {
                            oRow[itemColumn.ToString()] = "ProjectSite#0";
                            continue;
                        }

                        if (itemColumn.ToString().Equals("ENTERPRISE_PROJECT_TYPE_IMAGE_URL"))
                        {
                            oRow[itemColumn.ToString()] = string.Format("/_layouts/15/inc/{0}/images/CenterNormalProject.png", GetPwaName(pwaDestino).Replace("/", string.Empty));
                            continue;
                        }

                        //EnterpriseProjectTypeInvalidWorkspaceTemplateName

                        if (itemEnterprise[itemColumn.ToString()] != null && !itemColumn.ReadOnly)
                        {
                            oRow[itemColumn.ToString()] = itemEnterprise[itemColumn.ToString()];
                        }
                    }
                    dsEnterpriseDestino.EnterpriseProjectType.AddEnterpriseProjectTypeRow(oRow);
                    //dsWorkflow.EnterpriseProjectType.AddEnterpriseProjectTypeRow(oRow);
                }

                foreach (SvcWorkflow.WorkflowDataSet.EnterpriseProjectTypePDPsRow itemPDPs in dsEnterpriseOrigem.EnterpriseProjectTypePDPs.Rows)
                {
                    SvcWorkflow.WorkflowDataSet.EnterpriseProjectTypePDPsRow oRowPDP = dsEnterpriseDestino.EnterpriseProjectTypePDPs.NewEnterpriseProjectTypePDPsRow();
                    foreach (DataColumn itemColumn in dsEnterpriseOrigem.EnterpriseProjectTypePDPs.Columns)
                    {
                        if (itemColumn.ToString().Equals("PDP_UID"))
                        {
                            continue;
                        }

                        if (itemColumn.ToString().Equals("PDP_NAME"))
                        {
                            var oDataRow = dsEnterpriseDestino2.EnterpriseProjectTypePDPs.Select(string.Format("PDP_NAME = '{0}'", itemPDPs[itemColumn.ToString()])).FirstOrDefault();
                            if (oDataRow != null)
                            {
                                oRowPDP["PDP_UID"] = oDataRow["PDP_UID"];
                            }
                            else
                            {
                                var oDataRow2 = dsEnterpriseDestino2.EnterpriseProjectTypePDPs.Select().FirstOrDefault();
                                oRowPDP["PDP_UID"] = oDataRow2["PDP_UID"];
                            }
                        }

                        if (itemColumn.ToString().Equals("ENTERPRISE_PROJECT_TYPE_UID"))
                        {
                            oRowPDP[itemColumn.ToString()] = ENTERPRISE_PROJECT_TYPE_UID;
                            continue;
                        }

                        if (itemPDPs[itemColumn.ToString()] != null && !itemColumn.ReadOnly)
                        {
                            oRowPDP[itemColumn.ToString()] = itemPDPs[itemColumn.ToString()];
                        }
                    }
                    dsEnterpriseDestino.EnterpriseProjectTypePDPs.AddEnterpriseProjectTypePDPsRow(oRowPDP);
                }
                //dsWorkflow.EnterpriseProjectType.AcceptChanges();
                //dsWorkflow.EnterpriseProjectTypePDPs.AcceptChanges();
                clientWorkflowDestino.CreateEnterpriseProjectType(dsEnterpriseDestino);
            }
            catch (SoapException ex)
            {
                string errMess = "";
                // Pass the exception to the PSClientError constructor to
                // get all error information.
                PSLibrary.PSClientError psiError  = new PSLibrary.PSClientError(ex);
                PSLibrary.PSErrorInfo[] psiErrors = psiError.GetAllErrors();

                for (int j = 0; j < psiErrors.Length; j++)
                {
                    errMess += psiErrors[j].ErrId.ToString() + "\n";
                }
                errMess += "\n" + ex.Message.ToString();

                MessageBox.Show(errMess);
                // Send error string to console or message box.
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Metodo para criar as Lookuptable e suas dependencias
        /// </summary>
        /// <param name="pwaDestino">Destino</param>
        /// <param name="itemRow">Item CustomField</param>
        /// <param name="ds">Data Set LookupTable</param>
        public void CreateLooukupTable(string pwaOrigem, string pwaDestino, string pLT_NAME)
        {
            try
            {
                //verificando se já existe a lookuptable no destino
                dsLookupTableDestino = GetLookupTable(pwaDestino);

                DataRow[] dataRowDestino = dsLookupTableDestino.Tables[0].Select("LT_NAME = '" + pLT_NAME + "'");

                if (dataRowDestino.Count() > 0)
                {
                    return;
                }

                if (dsLookupTableOrigem == null)
                {
                    dsLookupTableOrigem = GetLookupTable(pwaOrigem);
                }

                DataRow[] dataRow = dsLookupTableOrigem.Tables[0].Select("LT_NAME = '" + pLT_NAME + "'");

                SvcLookupTable.LookupTableDataSet ltDS = new LookupTableDataSet();

                SvcLookupTable.LookupTableClient clientLookupTable = new LookupTableClient(Binding, endPointAdress(pwaDestino, "/_vti_bin/psi/LookupTable.asmx"));
                clientLookupTable.ClientCredentials.Windows.ClientCredential = new NetworkCredential(this.User, this.PassWord, this.Domain);

                foreach (SvcLookupTable.LookupTableDataSet.LookupTablesRow item in dataRow)
                {
                    SvcLookupTable.LookupTableDataSet.LookupTablesRow ltRow = ltDS.LookupTables.NewLookupTablesRow();
                    Guid LT_UID = Guid.NewGuid();

                    ltRow.LT_UID = LT_UID;

                    ltRow.LT_FILL_ALL_LEVELS = item.LT_FILL_ALL_LEVELS;
                    ltRow.LT_NAME            = item.LT_NAME;

                    if (!item.IsAPP_ENTITY_UIDNull())
                    {
                        ltRow.APP_ENTITY_UID = item.APP_ENTITY_UID;
                    }

                    if (!item.IsLT_PRIMARY_LCIDNull())
                    {
                        ltRow.LT_PRIMARY_LCID = item.LT_PRIMARY_LCID;
                    }

                    if (!item.IsLT_SORT_ORDER_ENUMNull())
                    {
                        ltRow.LT_SORT_ORDER_ENUM = item.LT_SORT_ORDER_ENUM;
                    }

                    ltDS.LookupTables.Rows.Add(ltRow);


                    foreach (SvcLookupTable.LookupTableDataSet.LookupTableMasksRow itemMaskRow in dsLookupTableOrigem.LookupTableMasks.Select("LT_UID = '" + item.LT_UID + "'"))
                    {
                        SvcLookupTable.LookupTableDataSet.LookupTableMasksRow ltMasksRow = ltDS.LookupTableMasks.NewLookupTableMasksRow();
                        foreach (DataColumn itemColumn in dsLookupTableOrigem.LookupTableMasks.Columns)
                        {
                            if (!ltDS.LookupTableMasks.Columns.Contains(itemColumn.ToString()))
                            {
                                continue;
                            }

                            if (itemColumn.ToString() == "LT_UID")
                            {
                                ltMasksRow[itemColumn.ToString()] = LT_UID;
                                continue;
                            }

                            if (itemMaskRow[itemColumn.ToString()] != null && !itemColumn.ReadOnly)
                            {
                                ltMasksRow[itemColumn.ToString()] = itemMaskRow[itemColumn.ToString()];
                            }
                        }

                        //ltMasksRow.LT_MASK_STRUCT_LEVEL = itemMaskRow.LT_MASK_STRUCT_LEVEL;
                        //ltMasksRow.LT_MASK_STRUCT_TYPE_ENUM = itemMaskRow.LT_MASK_STRUCT_TYPE_ENUM;
                        //ltMasksRow.LT_MASK_STRUCT_LENGTH = itemMaskRow.LT_MASK_STRUCT_LENGTH;
                        //ltMasksRow.LT_MASK_VALUE_SEPARATOR = itemMaskRow.LT_MASK_VALUE_SEPARATOR;

                        ltDS.LookupTableMasks.Rows.Add(ltMasksRow);
                    }



                    foreach (SvcLookupTable.LookupTableDataSet.LookupTableTreesRow itemTreesRow in dsLookupTableOrigem.LookupTableTrees.Select("LT_UID = '" + item.LT_UID + "'"))
                    {
                        //ltTreesRow.LT_UID = ltDS.LookupTables[0].LT_UID;
                        SvcLookupTable.LookupTableDataSet.LookupTableTreesRow ltTreesRow = ltDS.LookupTableTrees.NewLookupTableTreesRow();
                        foreach (DataColumn itemColumn in dsLookupTableOrigem.LookupTableTrees.Columns)
                        {
                            if (!ltDS.LookupTableTrees.Columns.Contains(itemColumn.ToString()))
                            {
                                continue;
                            }

                            //if (itemColumn.ToString() == "LT_STRUCT_UID")
                            //{
                            //    ltTreesRow[itemColumn.ToString()] = Guid.NewGuid();
                            //    continue;
                            //}

                            if (itemColumn.ToString() == "LT_UID")
                            {
                                ltTreesRow[itemColumn.ToString()] = LT_UID;
                                continue;
                            }


                            if (itemTreesRow[itemColumn.ToString()] != null && !itemColumn.ReadOnly)
                            {
                                ltTreesRow[itemColumn.ToString()] = itemTreesRow[itemColumn.ToString()];
                            }
                        }

                        ltDS.LookupTableTrees.Rows.Add(ltTreesRow);
                    }

                    try
                    {
                        bool validateOnly = false;
                        bool autoCheckIn  = true;

                        clientLookupTable.CreateLookupTables(ltDS, validateOnly, autoCheckIn);
                    }
                    catch (SoapException ex)
                    {
                        string errMess = "";
                        // Pass the exception to the PSClientError constructor to
                        // get all error information.
                        PSLibrary.PSClientError psiError  = new PSLibrary.PSClientError(ex);
                        PSLibrary.PSErrorInfo[] psiErrors = psiError.GetAllErrors();

                        for (int j = 0; j < psiErrors.Length; j++)
                        {
                            errMess += psiErrors[j].ErrId.ToString() + "\n";
                        }
                        errMess += "\n" + ex.Message.ToString();

                        MessageBox.Show(errMess);
                        // Send error string to console or message box.
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Metodo para criar o Custom Field no Detino
        /// </summary>
        /// <param name="source">Origem</param>
        /// <param name="target">Destino</param>
        /// <param name="field">Nome CustomField</param>
        public void CreateCustomField(string source, string target, string field, string lookupTable)
        {
            CustomFieldDataSet cfDS = new CustomFieldDataSet();
            var RowField            = this.dsGenerico.Tables[0].Select("MD_PROP_NAME ='" + field + "'").CopyToDataTable();

            SvcCustomFields.CustomFieldsClient fieldTarget = new CustomFieldsClient(Binding, endPointAdress(target, "/_vti_bin/psi/CustomFields.asmx"));
            fieldTarget.ClientCredentials.Windows.ClientCredential = new NetworkCredential(this.User, this.PassWord, this.Domain);

            Guid cfUid = Guid.NewGuid();

            foreach (DataRow item in RowField.Rows)
            {
                SvcCustomFields.CustomFieldDataSet.CustomFieldsRow cfRow = cfDS.CustomFields.NewCustomFieldsRow();

                foreach (DataColumn itemColumn in RowField.Columns)
                {
                    if (!cfDS.CustomFields.Columns.Contains(itemColumn.ToString()))
                    {
                        continue;
                    }

                    if (itemColumn.ToString() == "MD_LOOKUP_TABLE_UID" && lookupTable != string.Empty)
                    {
                        var  lt     = GetLookupTable(target).Tables[0].Select("LT_NAME ='" + lookupTable + "'").CopyToDataTable();
                        Guid lt_Uid = Guid.Parse(lt.Rows[0]["LT_UID"].ToString());
                        cfRow[itemColumn.ToString()] = lt_Uid;
                        continue;
                    }

                    if (itemColumn.ToString().Equals("MD_PROP_UID"))
                    {
                        cfRow[itemColumn.ToString()] = cfUid;
                        continue;
                    }

                    if (itemColumn.ToString().Equals("MD_PROP_DEFAULT_VALUE"))
                    {
                        continue;
                    }

                    if (item[itemColumn.ToString()] != null && !itemColumn.ReadOnly)
                    {
                        cfRow[itemColumn.ToString()] = item[itemColumn.ToString()];
                    }
                }
                cfDS.CustomFields.Rows.Add(cfRow);
            }

            try
            {
                bool validateOnly = false;
                bool autoCheckIn  = true;
                fieldTarget.CreateCustomFields(cfDS, validateOnly, autoCheckIn);
            }
            catch (SoapException ex)
            {
                string errMess = "";
                PSLibrary.PSClientError psiError  = new PSLibrary.PSClientError(ex);
                PSLibrary.PSErrorInfo[] psiErrors = psiError.GetAllErrors();

                for (int j = 0; j < psiErrors.Length; j++)
                {
                    errMess += psiErrors[j].ErrId.ToString() + "\n";
                }
                errMess += "\n" + ex.Message.ToString();
                throw ex;
            }
        }
        /// <summary>
        /// Create a hierarchical text lookup table, with code masks and values.
        /// </summary>
        /// <param name="lookupTable">SvcLookupTable.LookupTable object</param>
        /// <param name="ltName">Name of the lookup table</param>
        /// <param name="maskSequence">Array of code mask sequences and separator characters</param>
        /// <param name="maskValues"></param>
        /// <param name="ltValues">Array of lookup table values: Name, description, level, default</param>
        /// <param name="ltRowDefaultUid">GUID of default value (out)</param>
        /// <returns>GUID of lookup table</returns>
        public Guid CreateLookupTable(
            SvcLookupTable.LookupTable lookupTable,
            string ltName,
            byte[] maskSequence,
            string[,] maskValues,
            string[,] ltValues,
            out Guid ltRowDefaultUid)
        {
            // Além região variáveis ​​método, há três regiões
            // Com um bloco try-catch:
            // 1. Criar linhas de tabela de pesquisa com máscaras de código em um LookupTableDataSet
            // 2 Adicionar valores herarchical para cada linha na tabela de pesquisa
            // 3. CreateLookupTables chamada com o LookupTableDataSet

            const string ANY     = "any";
            const string DEFAULT = "default";

            #region Method variables
            int    levelLength;
            string sLevelLength;
            bool   error = false;

            // Save the return GUIDS for lookup table and default value (if any)
            Guid[] returnIds = new Guid[2];
            int    numLtRows = ltValues.Length / 4;   // There are 4 strings for each lookup table row
            int    maxLevels = maskValues.Length / 2; // There are 2 strings for each mask level

            if (maxLevels != maskSequence.Length || maxLevels > 5)
            {
                // Error: The number of rows in the maskSequence and maskValues arrays must be the same.
                //        The hierarchical levels can't be more than five levels deep.
                ltRowDefaultUid = Guid.Empty;
                return(Guid.Empty);
            }
            int[]  parentIndex = new int[numLtRows];  // Index of each lookup table row parent
            Guid[] parentUid   = new Guid[numLtRows]; // Parent GUIDs of lookup table tree rows

            for (int i = 0; i < numLtRows; i++)
            {
                parentIndex[i] = Convert.ToInt32(ltValues[i, 2]);
            }

            SvcLookupTable.LookupTableDataSet lookupTableDataSet =
                new SvcLookupTable.LookupTableDataSet();
            #endregion

            #region Criar uma linha da tabela de pesquisa com máscaras de código
            try
            {
                //Criar uma linha da tabela de pesquisa a partir da instância LookupTableDataSet
                SvcLookupTable.LookupTableDataSet.LookupTablesRow lookupTableRow =
                    lookupTableDataSet.LookupTables.NewLookupTablesRow();

                Guid lookupTableGuid = Guid.NewGuid();
                // Set the lookup table ID
                returnIds[0] = lookupTableGuid;

                lookupTableRow.LT_UID             = lookupTableGuid;
                lookupTableRow.LT_NAME            = ltName;
                lookupTableRow.LT_SORT_ORDER_ENUM =
                    (byte)PSLibrary.LookupTables.SortOrder.Ascending;

                lookupTableDataSet.LookupTables.Rows.Add(lookupTableRow);

                // Create the code mask and rows
                SvcLookupTable.LookupTableDataSet.LookupTableMasksDataTable masksDataTable =
                    new SvcLookupTable.LookupTableDataSet.LookupTableMasksDataTable();

                SvcLookupTable.LookupTableDataSet.LookupTableMasksRow ltMasksRow =
                    masksDataTable.NewLookupTableMasksRow();

                for (int level = 0; level < maxLevels; level++)
                {
                    sLevelLength = maskValues[level, 0];
                    if (string.Compare(sLevelLength, ANY, true) == 0)
                    {
                        levelLength = PSLibrary.LookupTables.ANY_LENGTH_SEQUENCE;
                    }
                    else
                    {
                        levelLength = Convert.ToInt32(maskValues[level, 0]);
                    }

                    ltMasksRow = CreateLookupTableMasksRow(
                        lookupTableDataSet,
                        level + 1,
                        maskSequence[level],
                        levelLength,
                        maskValues[level, 1]);
                    lookupTableDataSet.LookupTableMasks.Rows.Add(ltMasksRow);
                }
            }
            catch (DataException ex)
            {
                // Add exception handler for ex
                error = true;
            }
            catch (SoapException ex)
            {
                // Add exception handler for ex
                error = true;
            }
            #endregion

            #region Add values to each row
            // Add the lookup table values
            try
            {
                SvcLookupTable.LookupTableDataSet.LookupTableTreesRow ltTreeRow =
                    lookupTableDataSet.LookupTableTrees.NewLookupTableTreesRow();

                if (!error)
                {
                    int    thisNode;
                    int    nextNode;
                    int    indexDiff;                      // Difference in levels between nodes
                    int    rowLevel;                       // Level of the current row
                    Guid   rowUid;                         // GUID of the current level
                    Guid[] previousLevelUid = new Guid[4]; // GUIDs of up to five previous levels
                                                           //     [0]: level 1; ... ; [4]: level 5
                    parentUid[0] = Guid.Empty;             // Initialize the first parentUid

                    for (int row = 0; row < numLtRows; row++)
                    {
                        rowUid   = Guid.NewGuid();
                        thisNode = row;
                        nextNode = thisNode + 1;
                        rowLevel = parentIndex[row];
                        previousLevelUid[rowLevel] = rowUid;  // Reset the previous level

                        ltTreeRow = AddLookupTableValues(
                            lookupTableDataSet,
                            parentUid[row],        // Parent GUID
                            rowUid,                // Current row GUID
                            ltValues[row, 0],      // Value
                            ltValues[row, 1]       // Description
                            );
                        // Set the parentUid of the next node.
                        if (row < numLtRows - 1)
                        {
                            if (parentIndex[nextNode] == 0)
                            {
                                parentUid[nextNode] = Guid.Empty;
                            }
                            else
                            {
                                indexDiff = parentIndex[nextNode] - parentIndex[thisNode];
                                switch (indexDiff)
                                {
                                case 1:
                                    parentUid[nextNode] = rowUid;
                                    break;

                                case 0:
                                    parentUid[nextNode] = parentUid[thisNode];
                                    break;

                                case -1:
                                case -2:
                                case -3:
                                    indexDiff          -= 1;
                                    parentUid[nextNode] = previousLevelUid[rowLevel + indexDiff];
                                    break;
                                }
                            }
                        }
                        // Check for the default GUID
                        if (ltValues[row, 3] == DEFAULT)
                        {
                            returnIds[1] = rowUid;
                        }
                        lookupTableDataSet.LookupTableTrees.Rows.Add(ltTreeRow);
                    }
                }
            }
            catch (SoapException ex)
            {
                // Add exception handler for ex
                error = true;
            }
            catch (Exception ex)
            {
                // Add exception handler for ex
                error = true;
            }
            #endregion

            #region Create and return the lookup table
            try
            {
                if (!error)
                {
                    bool validateOnly = false;
                    bool autoCheckIn  = true;
                    lookupTable.CreateLookupTables(lookupTableDataSet,
                                                   validateOnly, autoCheckIn);
                }
            }
            catch (SoapException ex)
            {
                string errMess = "";
                // Pass the exception to the PSClientError constructor to get
                // all error information.
                PSLibrary.PSClientError psiError  = new PSLibrary.PSClientError(ex);
                PSLibrary.PSErrorInfo[] psiErrors = psiError.GetAllErrors();

                for (int j = 0; j < psiErrors.Length; j++)
                {
                    errMess += psiErrors[j].ErrId.ToString() + "\n";
                }
                errMess += "\n" + ex.Message.ToString();
                // Send error string to console or message box.

                error = true;
            }
            if (error)
            {
                returnIds[0] = Guid.Empty;
                returnIds[1] = Guid.Empty;
            }
            ltRowDefaultUid = returnIds[1];
            return(returnIds[0]);

            #endregion
        }