public static void DeployModuleFile(SPFolder folder,
            string fileUrl,
            string fileName,
            byte[] fileContent,
            bool overwrite,
            Action<SPFile> beforeProvision,
            Action<SPFile> afterProvision)
        {
            // doc libs
            SPList list = folder.DocumentLibrary;

            // fallback for the lists assuming deployment to Forms or other places
            if (list == null)
            {
                list = folder.ParentWeb.Lists[folder.ParentListId];
            }

            WithSafeFileOperation(list, folder, fileUrl, fileName, fileContent,
                overwrite,
                onBeforeFile =>
                {
                    if (beforeProvision != null)
                        beforeProvision(onBeforeFile);
                },
                onActionFile =>
                {
                    if (afterProvision != null)
                        afterProvision(onActionFile);
                });
        }
        private static bool ProcessAllSubFolders(SPFolder Folder, bool recursive, Func<SPFolder, bool> methodToCall)
        {
            IList<SPFolder> subFolders = Folder.SubFolders.Cast<SPFolder>().ToList<SPFolder>();

            foreach (SPFolder subFolder in subFolders)
            {
                //Loop through all sub webs recursively
                bool bContinue;

                bContinue = methodToCall.Invoke(subFolder);

                if (!bContinue)
                    return false;

                if (recursive && subFolder.Exists)
                {
                    bContinue = ProcessAllSubFolders(subFolder, recursive, methodToCall);

                    if (!bContinue)
                        return false;
                }
            }

            return true;
        }
 public CopyFolderCommand(SPFolder sourceFolder, string newUrl, string contentTypeId, SPWeb web)
     : base(web)
 {
     _NewUrl = newUrl;
     _SourceFolder = sourceFolder;
     _ContentTypeId = contentTypeId;
 }
        private void DeployWelcomePage(object modelHost, DefinitionBase model, SPFolder folder, WelcomePageDefinition welcomePgaeModel)
        {
            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = folder,
                ObjectType = typeof(SPFolder),
                ObjectDefinition = welcomePgaeModel,
                ModelHost = modelHost
            });

            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Changing welcome page to: [{0}]", welcomePgaeModel.Url);
            
            // https://github.com/SubPointSolutions/spmeta2/issues/431
            folder.WelcomePage = UrlUtility.RemoveStartingSlash(welcomePgaeModel.Url);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioned,
                Object = folder,
                ObjectType = typeof(SPFolder),
                ObjectDefinition = welcomePgaeModel,
                ModelHost = modelHost
            });

            folder.Update();
        }
        protected void LoadFolderNodes(SPFolder folder, TreeNode folderNode)
        {
            foreach (SPFolder childFolder in folder.SubFolders)
            {
                TreeNode childFolderNode = new TreeNode(childFolder.Name, childFolder.Name, FOLDER_IMG);
                childFolderNode.NavigateUrl = SPContext.Current.Site.MakeFullUrl(childFolder.Url);
                LoadFolderNodes(childFolder, childFolderNode);
                folderNode.ChildNodes.Add(childFolderNode);
            }

            foreach (SPFile file in folder.Files)
            {
                TreeNode fileNode;
                if (file.CustomizedPageStatus == SPCustomizedPageStatus.Uncustomized)
                {
                    fileNode = new TreeNode(file.Name, file.Name, GHOSTED_FILE_IMG);
                }
                else
                {
                    fileNode = new TreeNode(file.Name, file.Name, UNGHOSTED_FILE_IMG);
                }

                fileNode.NavigateUrl = SPContext.Current.Site.MakeFullUrl(file.Url);
                folderNode.ChildNodes.Add(fileNode);
            }
        }
        /// <summary>
        /// Checks the folders for unghosted files.
        /// </summary>
        /// <param name="folder">The folder.</param>
        /// <param name="unghostedFiles">The unghosted files.</param>
        internal static void CheckFoldersForUnghostedFiles(SPFolder folder, ref List<object> unghostedFiles, bool asString)
        {
            foreach (SPFolder sub in folder.SubFolders)
            {
                CheckFoldersForUnghostedFiles(sub, ref unghostedFiles, asString);
            }

            foreach (SPFile file in folder.Files)
            {
                if (file.CustomizedPageStatus == SPCustomizedPageStatus.Customized)
                {
                    if (asString)
                    {
                        string url = file.Web.Site.MakeFullUrl(file.ServerRelativeUrl);
                        if (!unghostedFiles.Contains(url))
                            unghostedFiles.Add(url);
                    }
                    else
                    {
                        if (!unghostedFiles.Contains(file))
                            unghostedFiles.Add(file);
                    }
                }
            }
        }
示例#7
0
文件: BUpload.cs 项目: kbelote/dummy
        public void GetPendingFiles()
        {
            SPListItemCollection items = null;
            using (SPSite site = new SPSite("http://kamlesh-lt:2013"))
            {
                using (SPWeb web = site.OpenWeb())
                {

                    try
                    {
                        SPList list = web.Lists["BulkUpload"];
                        fldErrorLogs = web.Folders["ErrorLogs"];

                        SPQuery query = new SPQuery();
                        query.Query = "<Where><Eq><FieldRef Name=\"Status\" /><Value Type=\"Choice\">Pending</Value></Eq></Where>";
                        query.ViewAttributes = "Scope='Recursive'";

                        items = list.GetItems(query);
                        for (int i = 0; i < items.Count; i++)
                        {
                            this.ProcessFile(items[i]);
                        }

                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }
示例#8
0
        public static SPFile GetFile(SPFolder folder, string relativeFilePath)
        {
            var currentFolder = folder;
            var parts = relativeFilePath.Split('/');
            var pathFolders = parts.Take(parts.Length - 1);
            var fileName = parts.Last();

            try
            {
                foreach (var folderName in pathFolders)
                {
                    if (folderName == "..")
                        currentFolder = currentFolder.ParentFolder;
                    else
                        currentFolder = currentFolder.SubFolders.OfType<SPFolder>().FirstOrDefault(f => f.Name == folderName);

                    if (currentFolder == null || !currentFolder.Exists)
                        return null;
                }
            }
            catch (Exception exception)
            {
                var message = String.Format("Error on FileUtilities#GetFile for parameters \"{0}\", \"{1}\"\n{2}",
                    folder.ServerRelativeUrl, relativeFilePath, exception);
                SPMinLoggingService.LogError(message, TraceSeverity.Unexpected);
                return null;
            }

            return currentFolder.Files.OfType<SPFile>().FirstOrDefault(f => f.Name == fileName);
        }
示例#9
0
        private static string CheckPathAndCreate(string strExportPath, SPFolder folder)
        {
            string strPath;
            strPath = string.Format("{0}\\{1}", strExportPath, folder.Url.Replace("/", "\\"));
            //strPath = "d:\\Export\\IT\\IT\\Project\\Phase 2 - Rel 1 Implementation\\90-Team Folder\\Difei\\ARS\\ARS global documents\\FY06 ARS Process Model\\6 - Enterprise Management\\6.01 - Master Data Maintenance - Retail Organization\\6.1.03 CMD Company Code and Purchase Organiz\\test";
            if (!Directory.Exists(strPath))
            {
                try
                {
                    //if (strPath.ToCharArray().Length < 248)
                    //{
                    Directory.CreateDirectory(strPath);
                    //}
                }
                catch (PathTooLongException pathTooLongException) {
                    LogInfoToRecordFile(InfoLogUNCPath, string.Format("The specific folder <{0}> path {1} is too long!",
                                                                        folder.Url,
                                                                        strPath));

                    strPath = null;
                }
            }

            return strPath;
        }
 protected void update_folder_time(SPFolder current_folder)
 {
     if (current_folder == null || !current_folder.Url.Contains("/")) return;
     current_folder.SetProperty("Name", current_folder.Name);
     current_folder.Update();
     update_folder_time(current_folder.ParentFolder);
 }
示例#11
0
        public FileContentParser(SPFile file)
        {
            this.mainFile = file;
            this.parentFolder = file.ParentFolder;
            this.mainContent = GetContent(mainFile);

            IncludedFiles = FileInclusionParser.GetIncludedFiles(mainContent);
        }
        private void DeployContentTypeOrder(object modelHost, SPList list, SPFolder folder, UniqueContentTypeOrderDefinition contentTypeOrderDefinition)
        {
            var oldContentTypeOrder = folder.ContentTypeOrder;
            var newContentTypeOrder = new List<SPContentType>();

            var listContentTypes = list.ContentTypes.OfType<SPContentType>().ToList();

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = folder,
                ObjectType = typeof(SPFolder),
                ObjectDefinition = contentTypeOrderDefinition,
                ModelHost = modelHost
            });

            // re-order
            foreach (var srcContentTypeDef in contentTypeOrderDefinition.ContentTypes)
            {
                SPContentType listContentType = null;

                if (!string.IsNullOrEmpty(srcContentTypeDef.ContentTypeName))
                    listContentType = listContentTypes.FirstOrDefault(c => c.Name == srcContentTypeDef.ContentTypeName);

                if (listContentType == null && !string.IsNullOrEmpty(srcContentTypeDef.ContentTypeId))
                    listContentType = listContentTypes.FirstOrDefault(c => c.Id.ToString().ToUpper().StartsWith(srcContentTypeDef.ContentTypeId.ToUpper()));

                if (listContentType != null && !newContentTypeOrder.Contains(listContentType))
                    newContentTypeOrder.Add(listContentType);
            }

            // filling up gapes
            foreach (var oldCt in oldContentTypeOrder)
            {
                if (newContentTypeOrder.Count(c =>
                    c.Name == oldCt.Name ||
                    c.Id.ToString().ToUpper().StartsWith(oldCt.Id.ToString().ToUpper())) == 0)
                    newContentTypeOrder.Add(oldCt);
            }

            if (newContentTypeOrder.Count() > 0)
                folder.UniqueContentTypeOrder = newContentTypeOrder;

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioned,
                Object = folder,
                ObjectType = typeof(SPFolder),
                ObjectDefinition = contentTypeOrderDefinition,
                ModelHost = modelHost
            });

            folder.Update();
        }
 public MoveFolderCommand(SPFolder folder, string newUrl, string contentTypeId, SPWeb web)
     : base(web)
 {
     _NewUrl = newUrl;
     _Folder = folder;
     _Item = _Folder.Item;
     _OldUrl = string.Format("{0}/{1}", _SPWeb.Url, _Folder.Url);
     _ContentTypeId = contentTypeId;
 }
示例#14
0
        public SPListItem CopyItem(SPListItem sourceItem, SPFolder destinationFolder)
        {
            SPListItem copiedItem = null;
            try
            {
                var destinationList = destinationFolder.ParentWeb.Lists[destinationFolder.ParentListId];

                if (destinationFolder.Item == null)
                {
                    copiedItem = destinationList.Items.Add();
                }
                else
                {
                    copiedItem = destinationFolder.Item.ListItems.Add(
                            destinationFolder.ServerRelativeUrl,
                            sourceItem.FileSystemObjectType);
                }

                foreach (string fileName in sourceItem.Attachments)
                {
                    SPFile file = sourceItem.ParentList.ParentWeb.GetFile(sourceItem.Attachments.UrlPrefix + fileName);
                    byte[] data = file.OpenBinary();
                    copiedItem.Attachments.Add(fileName, data);
                }

                for (int i = sourceItem.Versions.Count - 1; i >= 0; i--)
                {
                    foreach (SPField destinationField in destinationList.Fields)
                    {
                        SPListItemVersion version = sourceItem.Versions[i];

                        if (!version.Fields.ContainsField(destinationField.InternalName))
                            continue;

                        if ((!destinationField.ReadOnlyField) && (destinationField.Type != SPFieldType.Attachments) && !destinationField.Hidden
                            || destinationField.Id == SPBuiltInFieldId.Author || destinationField.Id == SPBuiltInFieldId.Created
                            || destinationField.Id == SPBuiltInFieldId.Editor || destinationField.Id == SPBuiltInFieldId.Modified)
                        {
                            if (destinationField.Type == SPFieldType.DateTime)
                            {
                                var dtObj = version[destinationField.InternalName];
                                copiedItem[destinationField.InternalName] = dtObj != null ?
                                    (object)destinationList.ParentWeb.RegionalSettings.TimeZone.UTCToLocalTime((DateTime)dtObj) : null;
                            }
                            else copiedItem[destinationField.Id] = version[destinationField.InternalName];
                        }
                    }
                    copiedItem.Update();
                }
                copiedItem[SPBuiltInFieldId.ContentTypeId] = sourceItem[SPBuiltInFieldId.ContentTypeId];
                copiedItem.SystemUpdate(false);
            }
            catch (Exception e)
            {}
            return copiedItem;
        }
        private void DeployPublishingPage(object modelHost, SPList list, SPFolder folder, PublishingPageLayoutDefinition definition)
        {
            var web = list.ParentWeb;
            var targetPage = GetCurrentObject(folder, definition);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = targetPage == null ? null : targetPage.File,
                ObjectType = typeof(SPFile),
                ObjectDefinition = definition,
                ModelHost = modelHost
            });

            if (targetPage == null)
                targetPage = CreateObject(modelHost, folder, definition);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioned,
                Object = targetPage.File,
                ObjectType = typeof(SPFile),
                ObjectDefinition = definition,
                ModelHost = modelHost
            });

            ModuleFileModelHandler.WithSafeFileOperation(list, folder,
                targetPage.Url,
                GetSafePageFileName(definition),
                Encoding.UTF8.GetBytes(definition.Content),
                definition.NeedOverride,
                null,
                afterFile =>
                {


                    var pageItem = afterFile.Properties;

                    pageItem["vti_title"] = definition.Title;
                    pageItem["MasterPageDescription"] = definition.Description;
                    pageItem[BuiltInInternalFieldNames.ContentTypeId] = BuiltInPublishingContentTypeId.PageLayout;

                    if (!string.IsNullOrEmpty(definition.AssociatedContentTypeId))
                    {
                        var siteContentType = web.AvailableContentTypes[new SPContentTypeId(definition.AssociatedContentTypeId)];

                        pageItem["PublishingAssociatedContentType"] = String.Format(";#{0};#{1};#",
                            siteContentType.Name,
                            siteContentType.Id.ToString());
                    }
                });
        }
        private void DeployHideContentTypeLinks(object modelHost, SPList list, SPFolder folder, HideContentTypeLinksDefinition contentTypeOrderDefinition)
        {
            var oldContentTypeOrder = folder.ContentTypeOrder;
            var newContentTypeOrder = oldContentTypeOrder;

            var listContentTypes = list.ContentTypes.OfType<SPContentType>().ToList();

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = folder,
                ObjectType = typeof(SPFolder),
                ObjectDefinition = contentTypeOrderDefinition,
                ModelHost = modelHost
            });

            // re-order
            foreach (var srcContentTypeDef in contentTypeOrderDefinition.ContentTypes)
            {
                SPContentType listContentType = null;

                if (!string.IsNullOrEmpty(srcContentTypeDef.ContentTypeName))
                    listContentType = listContentTypes.FirstOrDefault(c => c.Name == srcContentTypeDef.ContentTypeName);

                if (listContentType == null && !string.IsNullOrEmpty(srcContentTypeDef.ContentTypeId))
                    listContentType = listContentTypes.FirstOrDefault(c => c.Id.ToString().ToUpper().StartsWith(srcContentTypeDef.ContentTypeId.ToUpper()));

                if (listContentType != null)
                {
                    var existingCt = newContentTypeOrder.FirstOrDefault(ct => ct.Name == listContentType.Name || ct.Id == listContentType.Id);

                    if (existingCt != null && newContentTypeOrder.Contains(existingCt))
                        newContentTypeOrder.Remove(existingCt);
                }
            }

            if (newContentTypeOrder.Count() > 0)
                folder.UniqueContentTypeOrder = newContentTypeOrder;

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioned,
                Object = folder,
                ObjectType = typeof(SPFolder),
                ObjectDefinition = contentTypeOrderDefinition,
                ModelHost = modelHost
            });

            folder.Update();
        }
示例#17
0
        private void DeployInternall(SPList list, SPFolder folder, ListItemDefinition listItemModel)
        {
            if (IsDocumentLibray(list))
            {
                TraceService.Error((int)LogEventId.ModelProvisionCoreCall, "Please use ModuleFileDefinition to deploy files to the document libraries. Throwing SPMeta2NotImplementedException");

                throw new SPMeta2NotImplementedException("Please use ModuleFileDefinition to deploy files to the document libraries");
            }

            EnsureListItem(list, folder, listItemModel);
        }
        public static void WithSafeFileOperation(
            SPList list,
            SPFolder folder,
            string fileUrl,
            string fileName,
            byte[] fileContent,
            bool overide,
            Action<SPFile> onBeforeAction,
            Action<SPFile> onAction)
        {
            var file = list.ParentWeb.GetFile(fileUrl);

            if (onBeforeAction != null)
                onBeforeAction(file);

            // are we inside ocument libary, so that check in stuff is needed?
            var isDocumentLibrary = list != null && list.BaseType == SPBaseType.DocumentLibrary;

            if (isDocumentLibrary)
            {
                if (list != null && (file.Exists && file.CheckOutType != SPFile.SPCheckOutType.None))
                    file.UndoCheckOut();

                if (list != null && (list.EnableMinorVersions && file.Exists && file.Level == SPFileLevel.Published))
                    file.UnPublish("Provision");

                if (list != null && (file.Exists && file.CheckOutType == SPFile.SPCheckOutType.None))
                    file.CheckOut();
            }

            SPFile newFile;

            if (overide)
                newFile = folder.Files.Add(fileName, fileContent, file.Exists);
            else
                newFile = file;

            if (onAction != null)
                onAction(newFile);

            newFile.Update();

            if (isDocumentLibrary)
            {
                if (list != null && (file.Exists && file.CheckOutType != SPFile.SPCheckOutType.None))
                    newFile.CheckIn("Provision");

                if (list != null && (list.EnableMinorVersions))
                    newFile.Publish("Provision");

                if (list != null && list.EnableModeration)
                    newFile.Approve("Provision");
            }
        }
示例#19
0
        private bool DoesFolderExist(SPFolder parentFolder, string folderName)
        {
            if(string.IsNullOrEmpty(folderName))
               {
               throw new ArgumentException("folderName");
               }

               var folderCollection = parentFolder.SubFolders;
               var exists = FolderExistsImplementation(folderCollection, folderName);
               return exists;
        }
        public SPFile AddDocumentLink(SPWeb web, SPFolder targetFolder, string documentPath, string documentName, string documentUrl)
        {
            web.RequireNotNull("web");
            targetFolder.RequireNotNull("targetFolder");
            documentPath.RequireNotNullOrEmpty("documentPath");
            documentName.RequireNotNullOrEmpty("documentName");
            documentUrl.RequireNotNullOrEmpty("documentUrl");
            IServiceLocator serviceLocator = SharePointServiceLocator.GetCurrent();
            IContentTypeOperations contentTypeOps = serviceLocator.GetInstance<IContentTypeOperations>();
            string contentTypeName = "Link to a Document";

            var contentType = web.AvailableContentTypes[contentTypeName];
            SPDocumentLibrary DocLibrary = targetFolder.DocumentLibrary;
            if (null != DocLibrary)
            {
                bool LinkToDocumentApplied = false;
                foreach (SPContentType cType in DocLibrary.ContentTypes)
                {
                    if (cType.Name == contentTypeName)
                    {
                        LinkToDocumentApplied = true;
                        break;
                    }
                }

                if (!LinkToDocumentApplied)
                {
                    contentTypeOps.AddContentTypeToList(contentType, DocLibrary);
                }
            }

            var filePath = targetFolder.ServerRelativeUrl;
            if (!string.IsNullOrEmpty(documentPath))
            {
                filePath += "/" + documentPath;
            }
            var currentFolder = web.GetFolder(filePath);

            var files = currentFolder.Files;
            var urlOfFile = currentFolder.Url + "/" + documentName + ".aspx";

            var builder = new StringBuilder(aspxPageFormat.Length + 400);
            builder.AppendFormat(aspxPageFormat, typeof(SPDocumentLibrary).Assembly.FullName);

            var properties = new Hashtable();
            properties["ContentTypeId"] = contentType.Id.ToString();

            var file = files.Add(urlOfFile, new MemoryStream(new UTF8Encoding().GetBytes(builder.ToString())), properties, false, false);
            var item = file.Item;
            item["URL"] = documentUrl + ", ";
            item.UpdateOverwriteVersion();
            return file;
        }
示例#21
0
        public FolderNode(SPFolder folder)
        {
            this.Tag = folder;
            if (folder.ParentListId != Guid.Empty)
            {
                this.SPParent = folder.ParentWeb.Lists[folder.ParentListId];
            }

            this.Setup();

            this.Nodes.Add(new ExplorerNodeBase("Dummy"));
        }
        /// <summary>
        /// Sets a default for a field at a location.
        /// </summary>
        /// <param name="metadata">Provides the method to set the default value for the field</param>
        /// <param name="folder"><see cref="SPFolder"/> location at which to set the default value</param>
        /// <param name="list">List of the TaxonomyField containing the validatedString corresponding to the default value.</param>
        public void ApplyFieldOnMetadata(MetadataDefaults metadata, SPFolder folder, SPList list)
        {
            var term = this.Term;
            var labelGuidPair = term.GetDefaultLabel((int)list.ParentWeb.Language) + "|" + term.Id;
            var taxonomyField = list.Fields.GetField(this.FieldName) as TaxonomyField;
            var newTaxonomyFieldValue = new TaxonomyFieldValue(taxonomyField);

            // PopulateFromLabelGuidPair takes care of looking up the WssId value and creating a new item in the TaxonomyHiddenList if needed.
            // Reference: http://msdn.microsoft.com/en-us/library/ee567833.aspx
            newTaxonomyFieldValue.PopulateFromLabelGuidPair(labelGuidPair);

            metadata.SetFieldDefault(folder, this.FieldName, newTaxonomyFieldValue.ValidatedString);
        }
示例#23
0
        protected SPListItem FindWebPartPage(SPFolder folder, WebPartPageDefinition webpartPageModel)
        {
            var webPartPageName = GetSafeWebPartPageFileName(webpartPageModel);

            if (!webPartPageName.EndsWith(".aspx"))
                webPartPageName += ".aspx";

            foreach (SPFile file in folder.Files)
                if (file.Name.ToUpper() == webPartPageName.ToUpper())
                    return file.Item;

            return null;
        }
        private void AddFolder(ZipFileBuilder builder, SPFolder folder, string parentFolder)
        {
            string folderPath = parentFolder == string.Empty ? folder.Name : parentFolder + "\\" + folder.Name;
            builder.AddDirectory(folderPath);

            foreach (SPFile file in folder.Files)
            {
                AddFile(builder, file, folderPath);
            }

            foreach (SPFolder subFolder in folder.SubFolders)
            {
                AddFolder(builder, subFolder, folderPath);
            }
        }
        /// <summary>
        /// Applies the field on metadata.
        /// </summary>
        /// <param name="metadata">The metadata.</param>
        /// <param name="folder">The folder.</param>
        public virtual void ApplyFieldOnMetadata(MetadataDefaults metadata, SPFolder folder)
        {
            var defaultValue = string.Empty;

            if (this.Value != null)
            {
                defaultValue = this.Value.ToString();
            }

            metadata.SetFieldDefault(
                folder,
                this.FieldName,
                defaultValue);

            metadata.Update();
        }
        public string GetDefaultContentTypeId(SPFolder folder)
        {
            var contentTypeId = string.Empty;
            if (folder.Item != null)
            {
                var metadata = new MetadataDefaults(folder.Item.ParentList);

                while (string.IsNullOrEmpty(contentTypeId) && folder != null)
                {
                    contentTypeId = metadata.GetFieldDefault(folder, BuiltInFields.ContentTypeId.InternalName);
                    folder = folder.ParentFolder;
                }
            }

            return contentTypeId;
        }
        private void DeployPage(object modelHost, SPList list, SPFolder folder, ContentPageDefinitionBase definition)
        {
            var web = list.ParentWeb;
            var targetPage = GetCurrentObject(folder, definition);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = targetPage == null ? null : targetPage.File,
                ObjectType = typeof(SPFile),
                ObjectDefinition = definition,
                ModelHost = modelHost
            });

            if (targetPage == null)
                targetPage = CreateObject(modelHost, folder, definition);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioned,
                Object = targetPage.File,
                ObjectType = typeof(SPFile),
                ObjectDefinition = definition,
                ModelHost = modelHost
            });

            ModuleFileModelHandler.WithSafeFileOperation(list, folder,
                targetPage.Url,
                GetSafePageFileName(definition),
                definition.Content,
                definition.NeedOverride,
                null,
                afterFile =>
                {
                    var pageItem = afterFile.Properties;

                    pageItem["vti_title"] = definition.Title;

                    MapProperties(modelHost, pageItem, definition);

                    //pageItem.SystemUpdate();
                });
        }
示例#28
0
        protected virtual SPListItem FindListItem(SPList list, SPFolder folder, ListItemDefinition listItemModel)
        {
            var items = list.GetItems(new SPQuery
            {
                Folder = folder,
                Query = string.Format(@"<Where>
                             <Eq>
                                 <FieldRef Name='Title'/>
                                 <Value Type='Text'>{0}</Value>
                             </Eq>
                            </Where>", listItemModel.Title)
            });

            if (items.Count > 0)
                return items[0];

            return null;
        }
示例#29
0
        public void EnsureVariationsSettings(SPSite site, VariationSettingsInfo variationSettings)
        {
            var      rootWeb = site.RootWeb;
            Guid     varRelationshipsListId = new Guid(rootWeb.AllProperties["_VarRelationshipsListId"] as string);
            SPList   varRelationshipsList   = rootWeb.Lists[varRelationshipsListId];
            SPFolder rootFolder             = varRelationshipsList.RootFolder;

            // Automatic creation
            rootFolder.Properties["EnableAutoSpawnPropertyName"] = variationSettings.IsAutomaticTargetPageCreation.ToString();

            // Recreate Deleted Target Page; set to false to enable recreation
            rootFolder.Properties["AutoSpawnStopAfterDeletePropertyName"] = (!variationSettings.IsRecreateDeletedTargetPage).ToString();

            // Update Target Page Web Parts
            rootFolder.Properties["UpdateWebPartsPropertyName"] = variationSettings.IsUpdateTargetPageWebParts.ToString();

            // Resources
            rootFolder.Properties["CopyResourcesPropertyName"] = variationSettings.IsCopyResourcesToTarget.ToString();

            // Notification
            rootFolder.Properties["SendNotificationEmailPropertyName"]    = variationSettings.IsSendNotificationEmail.ToString();
            rootFolder.Properties["SourceVarRootWebTemplatePropertyName"] = variationSettings.SourceVariationTopLevelWebTemplate;
            rootFolder.Update();

            SPListItem item = null;

            if (varRelationshipsList.Items.Count > 0)
            {
                item = varRelationshipsList.Items[0];
            }
            else
            {
                item = varRelationshipsList.Items.Add();
                item["GroupGuid"] = new Guid("F68A02C8-2DCC-4894-B67D-BBAED5A066F9");
            }

            item["Deleted"]      = false;
            item["ObjectID"]     = rootWeb.ServerRelativeUrl;
            item["ParentAreaID"] = string.Empty;

            item.Update();
        }
示例#30
0
        private static bool ListContainsAttachments(SPWeb web, ListInfo listInfo)
        {
            SPFolder listFolder = null;

            // Get the list folder in the web
            var folders = listInfo.WebRelativeUrl.ToString().Split('/');

            for (var i = 0; i < folders.Count(); i++)
            {
                // If the first list folder segment, get it in the web folders collection.
                // Else, get the folder in the subfolders collection.
                if (i == 0)
                {
                    listFolder = web.Folders[folders[i]];
                }
                else if (listFolder != null)
                {
                    listFolder = listFolder.SubFolders[folders[i]];
                }
            }

            // If the list folder exists
            if (listFolder != null)
            {
                try
                {
                    // If the attachments folder exists
                    var attachmentsFolder = listFolder.SubFolders["Attachments"];
                    if (attachmentsFolder != null)
                    {
                        // Return true if any attachments folder contains a subfolder with files.
                        return(attachmentsFolder.SubFolders.Cast <SPFolder>().Any(folder => folder.Files.Count > 0));
                    }
                }
                catch (ArgumentException)
                {
                    return(false);
                }
            }

            return(false);
        }
示例#31
0
        public static SPFile SaveFilePowerLibrary(string fileName, byte[] bin)
        {
            string powerLibraryPath = PowerWebPartStore.Current.PowerLibraryUrl;

            if (String.IsNullOrEmpty(powerLibraryPath))
            {
                throw new FileNotFoundException("PowerLibrary in not configured!");
            }

            using (SPSite site = new SPSite(powerLibraryPath))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPFolder folder = web.GetFolder(powerLibraryPath);

                    SPFile file = folder.Files.Add(fileName, bin);
                    return(file);
                }
            }
        }
示例#32
0
        private void WriteFiles(string targetFolder, SPFolder folder)
        {
            if (!Directory.Exists(targetFolder))
            {
                WriteVerbose(string.Format("Creating folder {0}...", targetFolder));
                Directory.CreateDirectory(targetFolder);
            }

            foreach (SPFile file in folder.Files)
            {
                WriteFile(targetFolder, file);
            }
            if (Recursive)
            {
                foreach (SPFolder childFolder in folder.SubFolders)
                {
                    WriteFiles(Path.Combine(targetFolder, childFolder.Name), childFolder);
                }
            }
        }
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var folderModelHost = modelHost.WithAssertAndCast <FolderModelHost>("modelHost", value => value.RequireNotNull());
            var definition      = model.WithAssertAndCast <FolderDefinition>("model", value => value.RequireNotNull());

            SPFolder spObject = null;

            if (folderModelHost.CurrentLibrary != null)
            {
                spObject = GetLibraryFolder(folderModelHost, definition);
            }
            else if (folderModelHost.CurrentList != null)
            {
                spObject = GetListFolder(folderModelHost, definition);
            }

            var assert = ServiceFactory.AssertService
                         .NewAssert(definition, spObject)
                         .ShouldBeEqual(m => m.Name, o => o.Name);
        }
示例#34
0
        protected virtual SPListItem FindListItem(SPList list, SPFolder folder, ListItemDefinition listItemModel)
        {
            var items = list.GetItems(new SPQuery
            {
                Folder = folder,
                Query  = string.Format(@"<Where>
                             <Eq>
                                 <FieldRef Name='Title'/>
                                 <Value Type='Text'>{0}</Value>
                             </Eq>
                            </Where>", listItemModel.Title)
            });

            if (items.Count > 0)
            {
                return(items[0]);
            }

            return(null);
        }
        private static SPFolder GetOASLibrary(SPWeb web)
        {
            SPListTemplateType genericList = new SPListTemplateType();

            genericList = SPListTemplateType.DocumentLibrary;

            SPFolder res = (SPFolder)web.GetFolder(OAS_LIBRARY);

            if (!res.Exists)
            {
                web.AllowUnsafeUpdates = true;
                Guid listGuid             = web.Lists.Add(OAS_LIBRARY, "", genericList);
                SPDocumentLibrary oaslist = (SPDocumentLibrary)web.Lists[listGuid];
                oaslist.Hidden = true;

                oaslist.Update();
            }

            return((SPFolder)web.Folders[OAS_LIBRARY]);
        }
        private void DeleteExistingPicturesForUser(SPFolder pictureDocumentLibrary)
        {
            string userName         = GetCleanUserName(SPContext.Current.Web.CurrentUser.LoginName);
            var    picturesToDelete = new List <SPFile>();

            foreach (SPFile file in pictureDocumentLibrary.Files)
            {
                if (Path.GetFileNameWithoutExtension(file.Name) == userName)
                {
                    picturesToDelete.Add(file);
                }
            }

            foreach (SPFile file in picturesToDelete)
            {
                file.Delete();
            }

            pictureDocumentLibrary.Update();
        }
        private void addSubFolder(StringBuilder dynamicMenuXml, SPFolder subFolder)
        {
            dynamicMenuXml.Append("<FlyoutAnchor ");
            dynamicMenuXml.Append(" Id=\"Ribbon.Flyoutanchor\" ");
            dynamicMenuXml.Append(" LabelText=\"").Append(subFolder.Name).Append("\" ");
            dynamicMenuXml.Append(" Command=\"DoNothingCommand\" ");
            dynamicMenuXml.Append(" CommandType=\"IgnoredByMenu\" ");
            dynamicMenuXml.Append(" Image16by16=\"/_layouts/images/folder.gif\" ");
            dynamicMenuXml.Append(" > ");
            dynamicMenuXml.Append(" <Menu Id=\"Ribbon.Flyoutanchor.Menu\"> ");
            dynamicMenuXml.Append(" <MenuSection Id=\"Ribbon.Flyoutanchor.Menu.MenuSection  DisplayMode='Menu16'\"> ");
            dynamicMenuXml.Append("  <Controls Id=\"Ribbon.Flyoutanchor.Menu.MenuSection.Controls\"> ");

            addFolderContents(dynamicMenuXml, subFolder, false);

            dynamicMenuXml.Append("   </Controls> ");
            dynamicMenuXml.Append("   </MenuSection> ");
            dynamicMenuXml.Append("  </Menu> ");
            dynamicMenuXml.Append("   </FlyoutAnchor> ");
        }
        private static void RemoveConversionFiles(SPWeb web, string JobId)
        {
            SPList list = GetOASList(web);
            SPListItemCollection listItems = list.Items;
            int itemCount = listItems.Count;

            web.AllowUnsafeUpdates = true;
            for (int k = 0; k < itemCount; k++)
            {
                SPListItem item = listItems[k];

                if (JobId == item["JobId"].ToString())
                {
                    //source file
                    string fileid = item["FileId"].ToString();
                    //conveted file
                    string source = Path.GetFileNameWithoutExtension(fileid);

                    SPFolder lib = GetOASLibrary(web);
                    //delete result file
                    SPFile res = GetFile(lib, fileid);
                    if (res != null)
                    {
                        res.Delete();
                        lib.Update();
                    }

                    //delete source file
                    res = GetFile(lib, source);
                    if (res != null)
                    {
                        res.Delete();
                        lib.Update();
                    }

                    listItems.Delete(k);
                    break;
                }
            }
            web.AllowUnsafeUpdates = false;
        }
示例#39
0
        public static SPMObjectType IdentifyObject(object obj)
        {
            if (obj is SPFolder)
            {
                SPFolder folder = (SPFolder)obj;

                if (folder.UniqueId.Equals(folder.ParentWeb.RootFolder.UniqueId))
                {
                    return(SPMObjectType.SPWeb);
                }
                else
                {
                    SPList list = folder.ParentWeb.Lists[folder.ParentListId];
                    if (folder.UniqueId.Equals(list.RootFolder.UniqueId))
                    {
                        if (list is SPDocumentLibrary)
                        {
                            return(SPMObjectType.SPDocumentLibrary);
                        }
                        else
                        {
                            return(SPMObjectType.SPList);
                        }
                    }
                    else
                    {
                        return(SPMObjectType.SPFolder);
                    }
                }
            }
            else if (obj is SPListItem)
            {
                return(SPMObjectType.SPListItem);
            }
            else if (obj is SPFile)
            {
                return(SPMObjectType.SPFile);
            }

            return(SPMObjectType.Unknown);
        }
示例#40
0
        private static void copyTemplates(SPFolder template, SPFolder dest, bool isProtected)
        {
            foreach (SPFile f in template.Files)
            {
                Hashtable fileProperties = new Hashtable();
                fileProperties["vti_Title"] = Regex.Replace(f.Name, "[0-9]+\\s", "");

                int    intOutNr;
                string strNumber = f.Name.Substring(0, 2);
                if (int.TryParse(strNumber, out intOutNr))
                {
                    fileProperties["DocumentNumber"] = strNumber;
                }

                var templatefile = f.OpenBinaryStream(SPOpenBinaryOptions.SkipVirusScan);
                var file         = dest.Files.Add(SPUrlUtility.CombineUrl(dest.ServerRelativeUrl, f.Name), templatefile, fileProperties, true);
                if (isProtected)
                {
                    file.Item[BriefingFields.DocumentIsProtectedName] = isProtected;
                    file.Item.UpdateOverwriteVersion();
                    SPUtil.SecureBriefing(file.Item);
                }
                if (file.CheckOutType != SPFile.SPCheckOutType.None)
                {
                    file.CheckIn("");
                }
            }

            foreach (SPFolder folder in template.SubFolders)
            {
                if (folder.Item != null && folder.Name != "Forms")
                {
                    SPFolder   fld        = dest.SubFolders.Add(folder.Name);
                    SPListItem folderItem = fld.Item;
                    folderItem["ExemptPublishAll"] = folder.Item["ExemptPublishAll"];
                    folderItem.Update();

                    copyTemplates(folder, fld, isProtected);
                }
            }
        }
示例#41
0
        void ddl_Controls_SelectedIndexChanged(object sender, EventArgs e)
        {
            string control  = ddl_Controls.SelectedValue;
            SPList stylelib = SPContext.Current.Site.RootWeb.Lists.TryGetList("Style Library");

            if (!string.IsNullOrEmpty(control))
            {
                SPFolder           controlFolder = stylelib.RootFolder.SubFolders[control];
                SPFolderCollection styleFolders  = controlFolder.SubFolders;
                List <SPFolder>    empty         = new List <SPFolder>();
                foreach (SPFolder folder in controlFolder.SubFolders)
                {
                    bool found = false;
                    foreach (SPFile file in folder.Files)
                    {
                        if (string.Compare("definition.xml", file.Name, true) == 0)
                        {
                            found = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        empty.Add(folder);
                    }
                }
                ddl_Style.DataSource = styleFolders;
                ddl_Style.DataBind();

                foreach (SPFolder folder in empty)
                {
                    ddl_Style.Items.Remove(folder.Name);
                }

                if (ddl_Style.Items.Count == 0)
                {
                    ddl_Controls.Items.Remove(controlFolder.Name);
                }
            }
        }
示例#42
0
        protected void btnUpload_Click(object sender, EventArgs args)
        {
            //Find out about the file we want to archive
            SPWeb  webSite  = SPContext.Current.Web;
            string filePath = webSite.Url.ToString() + Request.QueryString["ItemUrl"].ToString();
            //This is work around for the webSite.GetFile() method.
            //I found this didn't let me get the binary bite array
            SPListItem item          = webSite.GetListItem(filePath);
            SPFolder   itemfolder    = webSite.Folders[item.ParentList.Title].SubFolders[item.Name];
            SPFile     fileToArchive = itemfolder.Files[0];

            //SPFile fileToArchive = webSite.GetFile(filePath);
            //Save the binary version to upload to Azure
            byte[] fileBinaryArray = fileToArchive.OpenBinary();
            //Make sure the archived file name is unique
            string fileNameGuid = Guid.NewGuid().ToString();
            string newBlobName  = string.Format(fileNameGuid + "_" + fileToArchive.Name.ToString());

            //Get or create the container
            blobContainer = cloudBlobClient.GetContainerReference(defaultContainerName);
            blobContainer.CreateIfNotExist();
            //Make sure the container is public
            var perms = blobContainer.GetPermissions();

            perms.PublicAccess = BlobContainerPublicAccessType.Container;
            blobContainer.SetPermissions(perms);
            //Create the blob
            cloudBlob = blobContainer.GetBlockBlobReference(newBlobName);
            try
            {
                //Upload the binary
                cloudBlob.UploadByteArray(fileBinaryArray);
                //Display the path to the blob
                resultsLabel.Text  = "Blob Location: " + cloudBlob.Uri.ToString();
                resultsLabel.Text += "<br />Try pasting the above URL into the IE address bar to download the file from Azure";
            }
            catch (Exception ex)
            {
                resultsLabel.Text = "There was an exception uploading the file: " + ex.Message;
            }
        }
示例#43
0
        protected override void CreateChildControls()
        {
            try
            {
                SPWeb    site       = SPContext.Current.Web;
                SPFolder rootFolder = site.RootFolder;
                TreeNode rootNode   = new TreeNode(site.Url, site.Url, SITE_IMG);
                LoadFolderNodes(rootFolder, rootNode);

                treeSitesFiles = new SPTreeView();
                treeSitesFiles.Nodes.Add(rootNode);
                treeSitesFiles.ExpandDepth = 1;
                Controls.Add(treeSitesFiles);

                base.CreateChildControls();
            }
            catch (Exception e)
            {
                string exp = "e.ToString";
            }
        }
        SPFolder CreateFolder(SPFolder folder, string name)
        {
            SPFolder newFolder = null;

            try
            {
                newFolder = folder.SubFolders[name];
            }
            catch (ArgumentException)
            {
            }

            if (newFolder == null)
            {
                newFolder = folder.SubFolders.Add(name);
                newFolder.Update();
                folder.Update();
            }

            return(newFolder);
        }
示例#45
0
        /// <summary>
        /// Provisions the welcome page.
        /// </summary>
        /// <param name="contentType">The content type.</param>
        /// <returns>The welcome page.</returns>
        private SPFile ProvisionWelcomePage(SPContentType contentType)
        {
            // Guard
            if (contentType == null)
            {
                throw new ArgumentNullException("contentType");
            }

            SPFile file = this.GetWelcomePage(contentType);

            if (file != null)
            {
                return(file);
            }

            byte[] buffer =
                File.ReadAllBytes(SPUtility.GetVersionedGenericSetupPath(@"Template\Features\DocumentSet\docsethomepage.aspx", 0));
            SPFolder resourceFolder = contentType.ResourceFolder;

            return(resourceFolder.Files.Add(this.DocumentSetWelcomePage, buffer, true));
        }
 internal static void RemovePages(EntitiesDataContext _edc, SPWeb _root)
 {
     Anons.WriteEntry(_edc, m_SourceClass + m_SourceRemovePages, "Remove Pages starting");
     try
     {
         SPFolder WebPartPagesFolder = _root.GetFolder(ProjectElementManagement.WebPartPagesFolder);
         if (WebPartPagesFolder.Exists)
         {
             WebPartPagesFolder.Delete();
         }
         else
         {
             Anons.WriteEntry(_edc, m_SourceClass + m_SourceRemovePages, "Failed, the folder " + WebPartPagesFolder + "dies not exist.");
         }
     }
     catch (Exception ex)
     {
         Anons.WriteEntry(_edc, m_SourceClass + m_SourceRemovePages, "Remove pages failed with exception: " + ex.Message);
     }
     Anons.WriteEntry(_edc, m_SourceClass + m_SourceRemovePages, "Remove Pages finished");
 }
        /// <summary>
        /// Writes a field value as an SPFolder's default column value
        /// </summary>
        /// <param name="folder">The folder for which we wish to update a field's default value</param>
        /// <param name="fieldValueInfo">The field and value information</param>
        public override void WriteValueToFolderDefault(SPFolder folder, FieldValueInfo fieldValueInfo)
        {
            var defaultValue  = (TaxonomyValueCollection)fieldValueInfo.Value;
            var list          = folder.ParentWeb.Lists[folder.ParentListId];
            var taxonomyField = (TaxonomyField)list.Fields[fieldValueInfo.FieldInfo.Id];
            MetadataDefaults listMetadataDefaults = new MetadataDefaults(list);

            if (defaultValue != null)
            {
                var    taxonomyFieldValueCollection = CreateSharePointTaxonomyFieldValue(taxonomyField, defaultValue, null);
                string collectionValidatedString    = taxonomyField.GetValidatedString(taxonomyFieldValueCollection);

                listMetadataDefaults.SetFieldDefault(folder, fieldValueInfo.FieldInfo.InternalName, collectionValidatedString);
            }
            else
            {
                listMetadataDefaults.RemoveFieldDefault(folder, fieldValueInfo.FieldInfo.InternalName);
            }

            listMetadataDefaults.Update();
        }
        /// <summary>
        /// Gets the name of the folder.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <param name="folder">The folder.</param>
        /// <returns>The Folder name</returns>
        private string GetFolderName(SPList list, SPFolder folder)
        {
            string value;

            if (_filter.IncludeNumberOfFiles)
            {
                if (list.BaseType == SPBaseType.DocumentLibrary)
                {
                    value = folder.Name + " (" + folder.Files.Count + ")";
                }
                else
                {
                    value = folder.Name + " (" + CountFolderItems(list, folder) + ")";
                }
            }
            else
            {
                value = folder.Name;
            }
            return(value);
        }
        public List <IItem> GetListItems(ISiteSetting siteSetting, Folder folder, IView view, string sortField, bool isAsc, int currentPageIndex, string currentListItemCollectionPositionNext, CamlFilters filters, bool isRecursive, out string listItemCollectionPositionNext, out int itemCount)
        {
            SPFolder _folder = folder as SPFolder;

            if (_folder == null)
            {
                listItemCollectionPositionNext = string.Empty;
                itemCount = 0;
                return(new List <IItem>());
            }

            ISharePointService spService  = new SharePointService();
            string             folderPath = string.Empty;

            if (folder as SPList == null)
            {
                folderPath = _folder.GetPath();
            }

            return(spService.GetListItems(siteSetting, view, sortField, isAsc, _folder.IsDocumentLibrary, _folder.WebUrl, _folder.ListName, folderPath, currentListItemCollectionPositionNext, filters, isRecursive, out listItemCollectionPositionNext, out itemCount));
        }
示例#50
0
        private SPFolder CreateFolderPathRecursive(SPFolder folder, IList <string> pathComponents)
        {
            if (pathComponents.Count == 0)
            {
                return(folder);
            }

            SPFolder newFolder;

            try
            {
                newFolder = folder.SubFolders[pathComponents.First()];
            }
            catch (ArgumentException)
            {
                newFolder = folder.SubFolders.Add(pathComponents.First());
            }

            pathComponents.RemoveAt(0);
            return(CreateFolderPathRecursive(newFolder, pathComponents));
        }
示例#51
0
        private static bool DoesPrincipalHasPermissions(SPFolder folder, SPPrincipal principal,
                                                        SPBasePermissions permissions)
        {
            var user = principal as SPUser;

            if (user != null)
            {
                return(folder.Item.DoesUserHavePermissions(user, permissions));
            }
            SPRoleAssignment assignmentByPrincipal = null;

            try
            {
                assignmentByPrincipal = folder.Item.RoleAssignments.GetAssignmentByPrincipal(principal);
            }
            catch
            {
                return(false);
            }
            return(assignmentByPrincipal.RoleDefinitionBindings.Cast <SPRoleDefinition>().Any(definition => (definition.BasePermissions & permissions) == permissions));
        }
示例#52
0
        public void DeleteUnregisterDataBaseCache()
        {
            StatusValuePair <List <ArchiveEntities> > allRecords = _archiveEntityCrud.GetListArchiveElements();

            if (!allRecords.HasValue || allRecords.Value == null)
            {
                return;
            }

            foreach (ArchiveEntities archiveEntity in allRecords.Value)
            {
                SPFolder folder = SpList.ParentWeb.GetFolder(archiveEntity.Url);
                if (folder != null && folder.Item != null)
                {
                    continue;
                }

                _manyToManyEntityCrud.Delete(archiveEntity.Id);
                _archiveEntityCrud.Delete(archiveEntity);
            }
        }
        /// <summary>
        /// Reflection crawl process of webpart properties and xml files
        /// </summary>
        /// <param name="folder"></param>
        protected void Crawl(SPFolder folder)
        {
            SPFile MyFile = null;

            if (folder != null)
            {
                foreach (SPFile CurrentFile in folder.Files)
                {
                    MyFile = CurrentFile;

                    try
                    {
                        string FileExtension = Path.GetExtension(CurrentFile.Url);

                        if (CurrentFile.InDocumentLibrary &&
                            CurrentFile.Item != null &&
                            m_Parameters.IncludeXmlFilesLibraries &&
                            XmlFileLibraryInFilteredList(CurrentFile.Item.ParentList as SPDocumentLibrary) &&
                            XmlFileLibraryInFilteredList(CurrentFile))
                        {
                            ReadXmlFile(CurrentFile);
                            continue;
                        }
                        else if (FileExtension.ToLower() == ".aspx" && m_Parameters.IncludeWebParts)
                        {
                            CrawlWebPartPage(CurrentFile);
                        }
                    }
                    catch (Exception ex)
                    {
                        OnError(ex, "ERROR: Cannot process file " + MyFile.Name);
                    }
                }

                foreach (SPFolder SubFolder in folder.SubFolders)
                {
                    Crawl(SubFolder);
                }
            }
        }
        protected override void CreateChildControls()
        {
            string s = "";

            if (string.IsNullOrEmpty(DocLibUrl))
            {
                s = string.Format(@"
Html Parametric by 
<a href=""{0}"" target=""_blank"">{1}</a>
<br />
<a id=""HtmlParametricWebPart_OpenToolPane_{2}"" href=""#"" onclick=""javascript:MSOTlPn_ShowToolPane2('Edit','{3}');"">Open the tool pane</a>
to configure this Web Part."
                                  , Helper.SGART_URL, Helper.SGART_TITLE
                                  , this.ClientID, this.ID);
            }
            else
            {
                try
                {
                    web = SPContext.Current.Web;
                    SPList list = web.GetList(docLibUrl);
                    editUrl = list.Forms[PAGETYPE.PAGE_EDITFORM].ServerRelativeUrl;
                    SPFolder folder = list.RootFolder;

                    STreeItem root = GetNode(folder, null);

                    LoadTree(folder, root);
                    s = ShowTree(root);
                }
                catch (Exception ex)
                {
                    s = string.Format("### Error: {0}", ex);
                }
            }

            lc = new LiteralControl(s);
            this.Controls.Add(lc);

            base.CreateChildControls();
        }
示例#55
0
        protected static void download(SPFolder folder, string targetf)
        {
            foreach (SPFile file in folder.Files)
            {
                string message = "";
                string fileName = file.Name;
                byte[] binfile = file.OpenBinary();
                string completePath = file.ParentFolder.ToString();
                string folderPath = System.IO.Path.Combine(targetf, getSafeFileName(completePath));
                System.IO.Directory.CreateDirectory(folderPath);

                string filePath = System.IO.Path.Combine(folderPath, fileName);

                bool response = false;

                try
                {
                    FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite);
                    BinaryWriter bw = new BinaryWriter(fs);
                    bw.Write(binfile);
                    bw.Close();
                    response = true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                if (response == true)
                {
                    message = "Copie ok: " + fileName;// +" dans " + filePath;
                }
                else
                {
                    message = "Erreur: " + fileName;
                }

                EcrireLog(message);
            }
        }
        protected override SPListItem FindListItem(SPList list, SPFolder folder, ListItemDefinition listItemModel)
        {
            var definition = listItemModel.WithAssertAndCast <ComposedLookItemDefinition>("model", value => value.RequireNotNull());

            // first by Name
            var items = list.GetItems(new SPQuery
            {
                Folder = folder,
                Query  = string.Format(@"<Where>
                             <Eq>
                                 <FieldRef Name='Name'/>
                                 <Value Type='Text'>{0}</Value>
                             </Eq>
                            </Where>", definition.Name)
            });

            if (items.Count > 0)
            {
                return(items[0]);
            }

            // by Title?
            items = list.GetItems(new SPQuery
            {
                Folder = folder,
                Query  = string.Format(@"<Where>
                             <Eq>
                                 <FieldRef Name='Title'/>
                                 <Value Type='Text'>{0}</Value>
                             </Eq>
                            </Where>", definition.Title)
            });

            if (items.Count > 0)
            {
                return(items[0]);
            }

            return(null);
        }
示例#57
0
        public ArchiveEntities CreateArchiveElement(SPFolder folder, string documentType = null, string description = null, string status = null)
        {
            if (folder == null || folder.Item == null || folder.Item[SPBuiltInFieldId.Author] == null)
            {
                return(null);
            }

            SPFieldUserValue author = new SPFieldUserValue(folder.Item.Web, folder.Item[SPBuiltInFieldId.Author].ToString());
            int      userId         = author.User.ID;
            DateTime created        = DateTime.Now;

            // создаём новую запись в БД, генерируем название папки из Id новой записи
            string editUrl = folder.Item.ParentList.DefaultEditFormUrl + "?ID=" + folder.Item.ID + "&RootFolder=/" + (folder.Item.Folder == null ? string.Empty : folder.Item.Folder.Url);

            long barcode = 0;

            if (folder.Item[Constants.BarCodeFieldName] != null)
            {
                var barcodeValue = folder.Item[Constants.BarCodeFieldName].ToString();
                BarcodeFabric.TryParse(barcodeValue, out barcode);
            }

            StatusValuePair <ArchiveEntities> archiveElement = _archiveEntityCrud.Create(folder.Url, editUrl, userId, folder.Item.ParentList.ID.ToString(), folder.Item.ID.ToString("D"), created, true, documentType, description, status, barcode > 0 ? barcode.ToString() : null);

            if (!archiveElement.HasValue)
            {
                return(null);
            }

            using (DisabledItemEventsScope scope = new DisabledItemEventsScope())
            {
                folder.Item[Constants.BarCodeFieldName] = archiveElement.Value.Barcode;
                folder.Item.Update();
            }

            List <Permissions> permissions = PermissionsHelper.GetPermissions(archiveElement.Value.Barcode, folder.Item);

            CreateOrUpdatePermissions(permissions);
            return(archiveElement);
        }
示例#58
0
        private static void ReOrderSetItemID(SPItemEventProperties properties, bool isSource)
        {
            string   urlString = null;
            SPFolder spFolder  = null;
            //This is intentionally started at 1 as we do not want a document with an ID of 0.
            int i = 1;

            //are we dealing with a source or destination library?
            if (isSource)
            {
                urlString = properties.BeforeUrl.Substring(0, properties.BeforeUrl.LastIndexOf("/"));
                spFolder  = properties.Web.GetFolder(urlString);
            }
            else
            {
                urlString = properties.AfterUrl.Substring(0, properties.AfterUrl.LastIndexOf("/"));
                spFolder  = properties.Web.GetFolder(urlString);
            }

            // reorder our SetItemID values in the source folder
            SPList  docSetList = properties.List;
            SPQuery query      = new SPQuery();

            query.Folder = spFolder;
            query.Query  = "<OrderBy><FieldRef Name='SetItemID' Ascending='FALSE' /></OrderBy>";
            SPListItemCollection items = docSetList.GetItems(query);

            if (items.Count > 0)
            {
                foreach (SPListItem item in items)
                {
                    if (item.ID != properties.ListItem.ID)
                    {
                        item["SetItemID"] = i;
                        item.Update();
                        i++;
                    }
                }
            }
        }
示例#59
0
 private static void PublishAssetInternal(string assetUrl, SPListItem sourceItem)
 {
     if (!CommonHelper.IsNullOrWhiteSpace(assetUrl))
     {
         object fileSystemObj;
         try {
             int pathEndPos = assetUrl.IndexOfAny(new[] { '?', '#' });
             if (pathEndPos >= 0)
             {
                 assetUrl = assetUrl.Substring(0, pathEndPos);
             }
             fileSystemObj = sourceItem.Web.Site.GetFileOrFolder(assetUrl);
         } catch {
             return;
         }
         try {
             if (fileSystemObj is SPFolder)
             {
                 SPFolder folder = (SPFolder)fileSystemObj;
                 if (folder.ParentListId != Guid.Empty)
                 {
                     folder.EnsureApproved();
                 }
             }
             else if (fileSystemObj is SPFile)
             {
                 SPFile file = (SPFile)fileSystemObj;
                 if (file.ParentFolder.ParentListId != Guid.Empty)
                 {
                     if (file.Item != null && file.Item.ContentTypeId.IsChildOf(SPBuiltInContentTypeId.Document) && !file.Item.ContentTypeId.IsChildOf(ContentTypeId.MasterPage.Parent) && !file.Item.ContentTypeId.IsChildOf(ContentTypeId.Page.Parent))
                     {
                         file.EnsurePublished(String.Concat("Publish linked asset from ", SPUrlUtility.CombineUrl(sourceItem.Web.ServerRelativeUrl, sourceItem.Url)));
                     }
                 }
             }
         } catch (Exception ex) {
             throw new Exception(String.Concat("Cannot approve or publish content at ", assetUrl), ex);
         }
     }
 }
        /// <summary>
        /// Sets a default for a field at a location.
        /// </summary>
        /// <param name="metadata">Provides the method to set the default value for the field</param>
        /// <param name="folder"><see cref="SPFolder"/> location at which to set the default value</param>
        /// <param name="list">List of the TaxonomyField containing the validatedString corresponding to the default value.</param>
        public void ApplyFieldOnMetadata(MetadataDefaults metadata, SPFolder folder, SPList list)
        {
            var taxonomyField = list.Fields.GetField(this.FieldName) as TaxonomyField;

            if (taxonomyField != null)
            {
                var newTaxonomyFieldValueCollection = this.GetTaxonomyFieldValueCollection(taxonomyField);

                List<string> wssIdAndLabelStrings = new List<string>();

                foreach (TaxonomyFieldValue fieldValue in newTaxonomyFieldValueCollection)
                {
                    var wssId = fieldValue.WssId;
                    var label = fieldValue.Label;

                    wssIdAndLabelStrings.Add(wssId + ";#" + label);
                }

                // Tax field value collection looks like this: "97;#Human resources;#96;#IT Services Portal" where "WSSidTerm1;#Term1Label;#WssidTerm2;#Term2Label"
                string taxFieldValueCollectionAsString = string.Join(";#", wssIdAndLabelStrings.ToArray());

                metadata.SetFieldDefault(folder, this.FieldName, taxFieldValueCollectionAsString);
            }
        }