Beispiel #1
0
 public static void SetBCSField(SPListItem item, SPBusinessDataField bcsField, string value, string finderMethodName)
 {
     try
     {
         IEntityInstance entityInst = GetEntityInstance(bcsField, value, item.ParentList.ParentWeb.Site, item, finderMethodName);
         if (entityInst != null)
         {
             SetSecondaryFields(item, bcsField, entityInst, finderMethodName);
             //item.UpdateOverwriteVersion();
             item.SystemUpdate(false);
         }
         else
         {
             throw new NullReferenceException("Null was returned from BCS FindSpecific method");
         }
     }
     catch (NullReferenceException e)
     {
         LogError("SetBCSField errored with message " + e.Message, ErrorLevel.Warning);
         throw;
     }
     catch (Exception e)
     {
         LogError("SetBCSField errored with message " + e.Message, ErrorLevel.Warning);
         throw;
     }
 }
        /// <summary>
        /// Update an SPListItem that has a BDC column, and update the secondary columns
        /// </summary>
        /// <param name="site"></param>
        /// <param name="matterNumber"></param>
        /// <param name="list"></param>
        /// <param name="item"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static SPListItem UpdateSPListItem(SPSite site, string matterNumber, SPList list, SPListItem item, SPContentType contentType)
        {
            //Set the content type of the matter item
            item["ContentTypeId"] = contentType.Id;
            //Get a reference to the BCS column
            SPBusinessDataField dataField = item.Fields["Matter Number"] as SPBusinessDataField;

            //Set all of the secondary fields underneath the primary BCS column
            SetSecondaryFields(item, dataField, GetEntityInstance(site, System.Configuration.ConfigurationManager.AppSettings["BDCNamespace"], "Litigation Matter", matterNumber));
            item.Update();
            //Set the matter site URL
            item["Matter Site"] = "/sites/litman/" + item.ID;
            item.Update();
            return(item);
        }
Beispiel #3
0
        private static void SetSecondaryFields(SPListItem listItem, SPBusinessDataField dataField, IEntityInstance entityInstance, string finderMethod)
        {
            try
            {
                // Convert the entity to a formatted datatable
                System.Data.DataTable dtBDCData = entityInstance.EntityAsFormattedDataTable;

                // Set the BCS field itself (Display Value)
                listItem[dataField.Id] = dtBDCData.Rows[0][dataField.BdcFieldName].ToString();

                // Get the specific finder method to get the columns that returns
                IMethodInstance           method       = entityInstance.Entity.GetMethodInstances(MethodInstanceType.SpecificFinder)[finderMethod];
                ITypeDescriptorCollection oDescriptors = method.GetReturnTypeDescriptor().GetChildTypeDescriptors()[0].GetChildTypeDescriptors();

                // Set the column names to the correct values
                foreach (ITypeDescriptor oType in oDescriptors)
                {
                    if (oType.ContainsLocalizedDisplayName())
                    {
                        if (dtBDCData.Columns.Contains(oType.Name))
                        {
                            dtBDCData.Columns[oType.Name].ColumnName = oType.GetLocalizedDisplayName();
                        }
                    }
                }

                // Get the secondary field display names - these should be set
                string[] sSecondaryFieldsDisplayNames = dataField.GetSecondaryFieldsNames();

                // Loop through the fields and set each column to its value
                foreach (string columnNameInt in sSecondaryFieldsDisplayNames)
                {
                    foreach (SPField field in listItem.Fields)
                    {
                        if (field.Title.StartsWith(dataField.Title) && field.GetProperty("BdcField") == columnNameInt)
                        {
                            Guid gFieldID = listItem.Fields[field.Title].Id;
                            listItem[gFieldID] = dtBDCData.Rows[0][columnNameInt].ToString();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LogError("SetSecondaryFields errored with message " + e.Message, ErrorLevel.Warning);
                throw;
            }
        }
Beispiel #4
0
        private static IEntity GetEntity(SPSite site, SPBusinessDataField dataField)
        {
            IEntity result = null;

            try
            {
                SPServiceContext context    = /*SPServiceContext.GetContext(site);*/ SPServiceContext.Current;
                IMetadataCatalog catalog    = null;
                BdcService       bdcService = SPFarm.Local.Services.GetValue <BdcService>(String.Empty);
                if (bdcService != null && dataField != null)
                {
                    catalog = bdcService.GetDatabaseBackedMetadataCatalog(context);
                    if (catalog != null)
                    {
                        result = catalog.GetEntity(dataField.EntityNamespace, dataField.EntityName);
                    }
                }
            }
            catch (Exception e)
            {
                LogError("GetEntity failed with message " + e.Message);
            }
            return(result);
        }
        /// <summary>
        /// Set the secondary fields of a BDC field
        /// </summary>
        /// <param name="listItem"></param>
        /// <param name="dataField"></param>
        /// <param name="entityInstance"></param>
        private static void SetSecondaryFields(SPListItem listItem, SPBusinessDataField dataField, IEntityInstance entityInstance)
        {
            //Copy the fieldset to a datatable
            DataTable dtBDCData = entityInstance.EntityAsFormattedDataTable;

            //Update the BDC primary field ID with the primary field in the datatable
            listItem[dataField.Id] = dtBDCData.Rows[0][dataField.BdcFieldName].ToString();

            //Get the Specific Finder method of the BDC entity and get the collection of columns/descriptors
            IMethodInstance           method       = entityInstance.Entity.GetMethodInstances(MethodInstanceType.SpecificFinder)[0].Value;
            ITypeDescriptorCollection oDescriptors = method.GetReturnTypeDescriptor().GetChildTypeDescriptors()[0].GetChildTypeDescriptors();

            //Loop through each Type Descriptor in the specific finder instance and update the local datatable column names appropriately
            foreach (ITypeDescriptor oType in oDescriptors)
            {
                if (oType.ContainsLocalizedDisplayName())
                {
                    if (dtBDCData.Columns.Contains(oType.Name))
                    {
                        dtBDCData.Columns[oType.Name].ColumnName = oType.GetLocalizedDisplayName();
                    }
                }
            }

            //Loop through each column name in the data source and update the corresponding list item column
            string[] sSecondaryFieldsDisplayNames = dataField.GetSecondaryFieldsNames();
            foreach (string columnNameint in sSecondaryFieldsDisplayNames)
            {
                Guid gFieldID = listItem.Fields[String.Format("{0}: {1}", dataField.Title, dtBDCData.Columns[columnNameint].Caption)].Id;
                listItem[gFieldID] = dtBDCData.Rows[0][columnNameint].ToString();
            }

            //Set the final values of the list item linking the item to its actual BDC Identity (allows for manually refreshing the list)
            listItem[dataField.Id]           = dtBDCData.Rows[0][dataField.BdcFieldName].ToString();
            listItem[dataField.RelatedField] = dtBDCData.Rows[0]["BdcIdentity"].ToString();
        }
Beispiel #6
0
        private static IEntityInstance GetEntityInstance(SPBusinessDataField dataField, string entityId, SPSite site, SPListItem item, string finderMethodName)
        {
            IEntityInstance entInstance = null;

            try
            {
                IEntity            entity            = GetEntity(site, dataField);
                ILobSystemInstance lobSystemInstance = entity.GetLobSystem().GetLobSystemInstances()[0].Value;

                // Get methods collection
                foreach (KeyValuePair <string, IMethod> method in entity.GetMethods())
                {
                    // Get current method's instance
                    IMethodInstance methodInstance = method.Value.GetMethodInstances()[method.Key];
                    // Execute specific finder method
                    if (methodInstance.MethodInstanceType == MethodInstanceType.SpecificFinder && methodInstance.Name == finderMethodName)
                    {
                        Identity id = null;

                        if (EntityInstanceIdEncoder.IsEncodedIdentifier(entityId))
                        {
                            object[] oIDList = EntityInstanceIdEncoder.DecodeEntityInstanceId(entityId);
                            id = new Identity(oIDList[0]);

                            // Execute specific finder method and get the entity instance
                            entInstance = entity.FindSpecific(id, methodInstance.Name, entity.GetLobSystem().GetLobSystemInstances()[0].Value);
                            item[dataField.RelatedField] = entityId.ToString();
                        }
                        else
                        {
                            object oID = GetTypedIDValue(entityId, entity);
                            id = new Identity(oID);
                            string encodedIdentifier = EntityInstanceIdEncoder.EncodeEntityInstanceId(new object[] { oID });
                            // Execute specific finder method and get the entity instance
                            entInstance = entity.FindSpecific(id, methodInstance.Name, entity.GetLobSystem().GetLobSystemInstances()[0].Value);
                            item[dataField.RelatedField] = encodedIdentifier;
                        }
                    }
                }
            }
            catch (ObjectNotFoundException notFoundException)
            {
                LogError("GetEntityInstance errored with message " + notFoundException.Message + ". Adding item to Guidewire.");
                Console.WriteLine("GetEntityInstance errored with message " + notFoundException.Message + ". Adding item to Guidewire.");
                bool   addDocumentToGuidewire = CallGuidewire(item, GuidewireOperationType.New);
                string outMessage             = "";
                if (addDocumentToGuidewire)
                {
                    outMessage = string.Format("Item with ID {0} added to Guidewire", item.ID);
                }
                else
                {
                    outMessage = string.Format("Item with ID {0} could not be added to Guidewire", item.ID);
                    if (Settings.Default.DeleteFailures)
                    {
                        try
                        {
                            // Recycle the item if it can't be added to guidewire and it's older than 30 days
                            if (DateTime.Now.AddDays(-30) > (DateTime)item[SPBuiltInFieldId.Modified])
                            {
                                item.Recycle();
                            }
                        }
                        catch
                        {
                            // Swallow this error. The item doesn't exist in Guidewire and can't be deleted in SharePoint. It has problems
                        }
                    }
                    LogError(outMessage);
                }
                Console.WriteLine(outMessage);
            }
            catch (Exception ex)
            {
                // Swallow this error
                LogError("GetEntityInstance errored with message " + ex.Message);
                Console.WriteLine("GetEntityInstance errored with message " + ex.Message);
            }
            return(entInstance);
        }
Beispiel #7
0
        private static bool ProcessWorkMatterDocuments()
        {
            inProgress = true;
            bool success = false;
            try
            {
                foreach(string libraryName in Settings.Default.LibrariesToProcess)
                {
                    using (SPSite site = new SPSite(ConfigurationManager.AppSettings["SiteUrl"], SPUserToken.SystemAccount))
                    {
                        Console.WriteLine("Successfully connected to site at " + site.Url);
                        using (SPWeb web = site.OpenWeb())
                        {
                            Console.WriteLine("Successfully opened SPWeb at " + web.Url);
                            SPList workMatterDocumentLibrary = web.Lists[libraryName];
                            SPQuery query = new SPQuery();
                            query.ViewXml = Util.GetViewQuery();
                            query.QueryThrottleMode = SPQueryThrottleOption.Override;
                            do
                            {
                                SPListItemCollection items = workMatterDocumentLibrary.GetItems(query);
                                int totalItems = items.Count;
                                Console.WriteLine("Processing items " + (query.ListItemCollectionPosition != null ? query.ListItemCollectionPosition.ToString() : "0") + " to " + query.ListItemCollectionPosition + totalItems);
                                query.ListItemCollectionPosition = items.ListItemCollectionPosition;
                                for (int i = 0; i < items.Count; i++)
                                {
                                    SPListItem item = items[i];

                                    try
                                    {
                                        web.AllowUnsafeUpdates = true;
                                        Records.BypassLocks(item, delegate (SPListItem delegateItem)
                                        {
                                            using (DisabledEventsScope scope = new DisabledEventsScope())
                                            {

                                                SPBusinessDataField field = delegateItem.Fields[Resource.FieldBCSWorkMatterDocument] as SPBusinessDataField;
                                                string documentId = Util.GetDocumentId(delegateItem);
                                                using (SPServiceContextScope ctxScope = new SPServiceContextScope(SPServiceContext.GetContext(site)))
                                                {
                                                    try
                                                    {
                                                        Util.SetBCSField(delegateItem, field, documentId, "GetWorkMatterDocumentBySPID");
                                                        Util.ClearFields(item);
                                                        if (delegateItem.Fields.ContainsField(Resource.FieldBCSWorkMatterDocumentStatus) && delegateItem[Resource.FieldBCSWorkMatterDocumentStatus] != null && delegateItem[Resource.FieldBCSWorkMatterDocumentStatus].ToString() == "Final")
                                                        {
                                                            Util.LockItem(delegateItem);
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        // Swallow the error at this level
                                                    }
                                                }

                                                Console.WriteLine("Document updated. ItemId=" + delegateItem.ID);
                                            }
                                        });
                                    }
                                    catch (Exception ex)
                                    {
                                        Util.LogError("Error updating document: " + ex.Message);
                                        Console.WriteLine("Error updating document: " + ex.Message);
                                    }
                                    finally
                                    {
                                        web.AllowUnsafeUpdates = false;
                                    }
                                }
                            }
                            while (query.ListItemCollectionPosition != null);
                        }
                    }
                }
                success = true;
            }
            catch (Exception ex)
            {
                success = false;
                Util.LogError("Error in ProcessWorkMatterDocuments(): " + ex.Message);
                Console.WriteLine("Error in ProcessWorkMatterDocuments(): " + ex.Message);
            }
            inProgress = false;
            return success;
        }
        private void CreateVendorDocumentsLibrary(SPWeb web, SPContentType vendorDocumentContentType)
        {
            SPList vendorDocumentsLibrary = web.Lists.TryGetList(Resource.VendorDocumentsLibrary);

            if (vendorDocumentsLibrary == null)
            {
                // Create library
                Guid listGuid = web.Lists.Add(Resource.VendorDocumentsLibrary, Resource.VendorDocumentsLibraryDesc, SPListTemplateType.DocumentLibrary);
                vendorDocumentsLibrary = web.Lists[listGuid];
                vendorDocumentsLibrary.ContentTypesEnabled = true;
                vendorDocumentsLibrary.EnableVersioning    = true;
                vendorDocumentsLibrary.OnQuickLaunch       = true;
                vendorDocumentsLibrary.ContentTypes.Add(vendorDocumentContentType);
                vendorDocumentsLibrary.ContentTypes["Document"].Delete();
                vendorDocumentsLibrary.Update();
            }

            if (!vendorDocumentsLibrary.Fields.ContainsField("Vendor"))
            {
                // Create the hidden note field needed for BCS
                SPField noteVendorField = vendorDocumentsLibrary.Fields.CreateNewField("Note", "Vendor_ID");
                noteVendorField.Hidden        = true;
                noteVendorField.ReadOnlyField = true;
                noteVendorField.SetCustomProperty("BdcField", "Vendor_ID");
                noteVendorField.StaticName = "Vendor_ID";
                vendorDocumentsLibrary.Fields.Add(noteVendorField);

                // Create the vendor field using BCS
                SPBusinessDataField vendorField = vendorDocumentsLibrary.Fields.CreateNewField("BusinessData", "Vendor") as SPBusinessDataField;
                vendorField.SystemInstanceName = "Guidewire";
                vendorField.EntityNamespace    = "Guidewire";
                vendorField.EntityName         = "Vendor";
                vendorField.StaticName         = "Vendor";
                vendorField.BdcFieldName       = "ContactID";
                vendorField.HasActions         = false;
                vendorField.Required           = true;
                vendorField.RelatedField       = "Vendor_ID";
                vendorDocumentsLibrary.Fields.Add(vendorField);
            }
            if (!vendorDocumentsLibrary.Fields.ContainsField("Vendor Document"))
            {
                // Create the hidden note field needed for BCS
                SPField noteVendorDocumentField = vendorDocumentsLibrary.Fields.CreateNewField("Note", "Vendor Document_ID");
                noteVendorDocumentField.Hidden        = true;
                noteVendorDocumentField.ReadOnlyField = true;
                noteVendorDocumentField.SetCustomProperty("BdcField", "Vendor Document_ID");
                noteVendorDocumentField.StaticName = "Vendor_x0020_Document_ID";

                // Create the vendor document field using BCS
                SPBusinessDataField vendorDocumentField = vendorDocumentsLibrary.Fields.CreateNewField("BusinessData", "Vendor Document") as SPBusinessDataField;
                vendorDocumentField.SystemInstanceName = "Guidewire";
                vendorDocumentField.EntityNamespace    = "Guidewire";
                vendorDocumentField.EntityName         = "Vendor Document";
                vendorDocumentField.StaticName         = "Vendor_x0020_Document";
                vendorDocumentField.BdcFieldName       = "ContactID";
                vendorDocumentField.HasActions         = false;
                vendorDocumentField.RelatedField       = "Vendor_x0020_Document_ID";
                vendorDocumentField.SetSecondaryFieldsNames(new string[] { "Category", "ContactID", "ContactName", "Status", "Subcategory", "PublicID" });
                vendorDocumentsLibrary.Fields.Add(vendorDocumentField);
            }
        }