protected ListItem SearchItemByName(List list, Folder folder, string pageName) { var context = list.Context; if (folder != null) { if (!folder.IsPropertyAvailable("ServerRelativeUrl")) { folder.Context.Load(folder, f => f.ServerRelativeUrl); folder.Context.ExecuteQueryWithTrace(); } } var dQuery = new CamlQuery(); string QueryString = "<View><Query><Where>" + "<Eq>" + "<FieldRef Name=\"FileLeafRef\"/>" + "<Value Type=\"Text\">" + pageName + "</Value>" + "</Eq>" + "</Where></Query></View>"; dQuery.ViewXml = QueryString; if (folder != null) dQuery.FolderServerRelativeUrl = folder.ServerRelativeUrl; var collListItems = list.GetItems(dQuery); context.Load(collListItems); context.ExecuteQueryWithTrace(); return collListItems.FirstOrDefault(); }
public static void Main() { var taskCalculator = new TaskCalculator(); // 1. var nodes = taskCalculator.ParseTree(); taskCalculator.FindRoot(nodes); taskCalculator.FindAllLeafs(nodes); taskCalculator.FindAllMiddleNodes(nodes); taskCalculator.FindLongestPath(nodes); taskCalculator.FindAllPathByGivenSum(nodes, 9); Console.WriteLine(); // 2. Console.WriteLine(Path); taskCalculator.TraverseWindowsDir(Path); Console.WriteLine(); // 3. To find the sum of subtree, just give subfolder from windows as a parameter var folder = new Folder { Name = @"C:\WINDOWS" }; BigInteger sum = taskCalculator.DFSRecursive(folder); Console.WriteLine("The sum of all file's size is {0}!", sum); }
void CheckOverlayWithinBounds(Feature feature) { var errors = new List<string>(); _geoArray = GeoArray.FromWellKnownText(feature.GetWellKnownText()); OnPropertyChanged("GeoArray"); #if false if (_writeKML) { var kml = new KMLRoot(); var folder = new Folder("Overlay Segment Test"); var segments = _geoArray.Segments.ToArray(); for (var segment = 0; segment < segments.Length; segment++) { segments[segment].Placemark.name = string.Format("Segment {0}", segment); folder.Add(segments[segment].Placemark); } kml.Document.Add(folder); var savePath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "Overlay Segment Tests", "OverlaySegmentTest.kml"); kml.Save(savePath); _writeKML = false; } #endif if (_geoArray.HasCrossingSegments && !AreCrossingSegmentsAllowed) errors.Add("Perimeter segments may not cross"); if (_locationBoundsRectangle != null && !_locationBoundsRectangle.Contains(feature.GetShape())) errors.Add("Perimeter must be within location bounds"); var areaStyle = errors.Count > 0 ? _errorAreaStyle : _normalAreaStyle; _wpfMap.EditOverlay.EditShapesLayer.ZoomLevelSet.ZoomLevel01.DefaultAreaStyle = areaStyle; _wpfMap.EditOverlay.EditShapesLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20; Errors = errors.Count == 0 ? string.Empty : string.Join("\n", errors); HasErrors = errors.Count > 0; if (HasErrors) Debug.WriteLine(string.Format("Errors: {0}", Errors)); }
private void CheckGroup(Folder groupFolder, List<ActivityBase> activities) { // Create for each remaining sub folder a merge activity (too much nesting). activities.AddRange(groupFolder.SubFolders .Where(FilterOtherProgramFolders) .Select(f => new MergeFolderActivity(groupFolder, f))); }
static void InitializeClientContext() { // create new client context string targetSharePointSite = ConfigurationManager.AppSettings["targetSharePointSite"]; clientContext = new ClientContext(targetSharePointSite); // get user name and secure password string userName = ConfigurationManager.AppSettings["accessAccountName"]; string pwd = ConfigurationManager.AppSettings["accessAccountPassword"]; SecureString spwd = new SecureString(); foreach (char c in pwd.ToCharArray()) { spwd.AppendChar(c); } // create credentials for SharePoint Online using Office 365 user account clientContext.Credentials = new SharePointOnlineCredentials(userName, spwd); // initlaize static variables for client context, web and site siteCollection = clientContext.Site; clientContext.Load(siteCollection); site = clientContext.Web; clientContext.Load(site); siteRootFolder = site.RootFolder; clientContext.Load(siteRootFolder); clientContext.Load(site.Lists); TopNavNodes = site.Navigation.TopNavigationBar; clientContext.Load(TopNavNodes); clientContext.ExecuteQuery(); }
static void WalkDirectoryTree(DirectoryInfo root, DirectoryTree folderTree, Folder currentFolder) { FileInfo[] files = null; DirectoryInfo[] subDirs = null; try { files = root.GetFiles("*.*"); } catch (UnauthorizedAccessException e) { log.Add(e.Message); } catch (DirectoryNotFoundException e) { Console.WriteLine(e.Message); } if (files != null) { currentFolder.Files = files.Select(f => new File(f.Name, f.Length)).ToList(); subDirs = root.GetDirectories(); currentFolder.ChildFolders = subDirs.Select(d => new Folder(d.Name)).ToList(); var i = 0; foreach (DirectoryInfo dirInfo in subDirs) { WalkDirectoryTree(dirInfo, folderTree, currentFolder.ChildFolders[i]); i++; } } }
public static bool GetTextureBytes(string fileName, Folder folder, bool skipCache, out byte[] bytes) { bytes = null; string filePath = GetFilePath(fileName, folder); if (filePath == null || !File.Exists(filePath)) { #if DEBUG Logger.LogInfo("Cannot find texture file at " + filePath); #endif return false; } if (!skipCache && sm_cachedFiles.TryGetValue(filePath, out bytes)) return true; try { bytes = File.ReadAllBytes(filePath); } catch (Exception e) { Logger.LogInfo("Unexpected " + e.GetType().Name + " reading texture file at " + filePath); return false; } sm_cachedFiles[filePath] = bytes; return true; }
private Folder CreateFolderPathRecursive(Folder f, List<string> pathComponents) { // base case if (pathComponents.Count == 0) return f; var head = pathComponents.First(); // inductive case Folder nextFolder; try { nextFolder = f.Folders.GetByUrl(head); f.Context.Load(nextFolder); f.Context.ExecuteQuery(); } catch (ServerException e) { if (e.ServerErrorTypeName == "System.IO.DirectoryNotFoundException") { nextFolder = f.Folders.Add(head); nextFolder.Update(); f.Context.ExecuteQuery(); Logger.Verbose($"Folder '{head}' created"); } else { throw; } } pathComponents.RemoveAt(0); return CreateFolderPathRecursive(nextFolder, pathComponents); }
private void RecursiveSharePointFolderVisitorInternal(Folder folder, Action<File> visit) { folder.Context.Load(folder, f => f.Files, f => f.Folders); folder.Context.ExecuteQuery(); folder.Files.ToList().ForEach(f => visit(f)); folder.Folders.ToList().ForEach(f => Execute(f, visit)); }
public Folder GetFolderRecursive(Folder folder, List<string> pathComponents) { // base case if (pathComponents.Count == 0) { return folder; } // inductive case var head = pathComponents.First(); var ctx = folder.Context; Folder nextFolder; try { nextFolder = folder.Folders.GetByUrl(head); ctx.Load(folder, f => f.Folders); ctx.ExecuteQuery(); pathComponents.RemoveAt(0); return GetFolderRecursive(nextFolder, pathComponents); } catch (ServerException e) { if (e.ServerErrorTypeName == "System.IO.DirectoryNotFoundException") { return null; } else { throw; } } }
/// <summary> /// Creates a new empty Lua script in the specified project, in the specified folder. /// </summary> /// <param name="data">The solution creation data, usually derived from the user's input in a NewSolutionForm.</param> /// <returns>A new solution that can be loaded.</returns> public override Moai.Platform.Management.File Create(string name, Project project, Folder folder) { File f = null; // Determine where to place the file. if (folder == null) { // Place the file in the root of the project f = new File(project, project.ProjectInfo.DirectoryName, name); project.AddFile(f); } else { // Place the file in the specified folder f = new File(project, project.ProjectInfo.DirectoryName, System.IO.Path.Combine(folder.FolderInfo.Name, name)); folder.Add(f); } // Write the contents of the data into the file. using (System.IO.StreamWriter writer = new System.IO.StreamWriter(f.FileInfo.FullName)) { writer.WriteLine("-- An empty script file."); writer.WriteLine(); } return f; }
public object SaveFolder(Folder folder) { if (folder == null) throw new ArgumentNullException("folder"); if (folder.ID != null) { var folderId = folder.ID; var selector = GetSelector(folderId); folder.ID = selector.ConvertId(folderId); var newFolderId = selector.GetFolderDao(folderId).SaveFolder(folder); folder.ID = folderId; return newFolderId; } if (folder.ParentFolderID != null) { var folderId = folder.ParentFolderID; var selector = GetSelector(folderId); folder.ParentFolderID = selector.ConvertId(folderId); var newFolderId = selector.GetFolderDao(folderId).SaveFolder(folder); folder.ParentFolderID = folderId; return newFolderId; } throw new ArgumentException("No folder id or parent folder id to determine provider"); }
private static Series GetSerieData(Folder folder) { var s = new Series(); s.TimeInterval = TimeInterval.Daily; foreach (var msg in folder.Messages) { var txt = msg.Body.Text; var exp = @"Pump Station Average Flow:(\s*\d{1,10}(\.){0,1}\d{0,3})\s*cfs"; Regex re = new Regex(exp); var m = Regex.Match(txt, exp); if (m.Success) { double d = Convert.ToDouble(m.Groups[1].Value); var t = Reclamation.TimeSeries.Math.RoundToNearestHour(msg.Date.Value); if (s.IndexOf(t) < 0) { s.Add(t, d); //msg.Flags.Add(ImapX.Flags.MessageFlags.Seen); msg.Flags.Add(ImapX.Flags.MessageFlags.Deleted); Console.WriteLine(t.ToString() + " " + d.ToString("F2")); } } } return s; }
static void Main() { string rootDir = @"C:\Windows"; Folder winFolder = new Folder("Windows"); FillDirectoryTree(rootDir, winFolder); PrintSize(winFolder); }
public DirectoryTree(string rootPath) { this.RootPath = rootPath; var root = Directory.GetParent(rootPath); rootFolder = new Folder(rootPath); }
private Folder DirectoryDFS(Folder folder) { try { var files = Directory.GetFiles(folder.Name); foreach (string item in files) { FileInfo fileinfo = new FileInfo(item); File file = new File(item, (int)fileinfo.Length); folder.AddFile(file); } var childFolders = Directory.GetDirectories(folder.Name); foreach (string item in childFolders) { Folder subFolder = new Folder(item); folder.AddFolder(subFolder); DirectoryDFS(subFolder); } } //catches the exceptions given if access restricted folder reached catch (UnauthorizedAccessException) { } return folder; }
private static void FillDirectoryTree(string path, Folder folder) { try { // Append files var files = Directory.GetFiles(path); foreach (var file in files) { string fileName = GetName(file); FileInfo fileInfo = new FileInfo(file); folder.AddFile(new File(fileName, fileInfo.Length)); } // Append dirs recursively var dirs = Directory.GetDirectories(path); foreach (var dir in dirs) { string dirName = GetName(dir); Folder newFolder = new Folder(dirName); folder.AddFolder(newFolder); FillDirectoryTree(dir, newFolder); } } catch (Exception e) { Console.WriteLine(e.Message); } }
//private static void ProcessNode(HtmlNode node, Stack<HtmlNode> stack) //{ // var depth = stack.Count; // var padding = String.Empty.PadLeft(depth, ' '); // stack.Push(node); // try // { // Debug.WriteLine(padding + "Node: " + node.Name); // foreach (var child in node.ChildNodes) // { // ProcessNode(child, stack); // } // } // finally // { // stack.Pop(); // } //} private void button_Click(object sender, RoutedEventArgs e) { using (var stream = File.OpenRead(@"C:\Documents\bookmarks_7_27_15.html")) { var doc = new HtmlDocument(); doc.Load(stream); var rootFolder = new Folder { Name = "<root>" }; ProcessNode(doc.DocumentNode, rootFolder); if (rootFolder.Folders.Count == 1) rootFolder = rootFolder.Folders.Single(); treeView.Items.Add(GetTree(rootFolder)); var bookmarks = rootFolder.AllBookmarks.ToList(); bookmarks.Sort( (l, r) => StringComparer.OrdinalIgnoreCase.Compare(l.Href.ToString(), r.Href.ToString())); var lookupItem = new TreeViewItem { Header = "Lookup" }; var lookup = rootFolder.AllBookmarks.ToLookup(b => b.Href.ToString(), b => b.Folder, StringComparer.OrdinalIgnoreCase); foreach (var key in lookup) { var folders = new HashSet<string>(key.Select(k => k.FullName), StringComparer.OrdinalIgnoreCase); if (folders.Count > 1) { //folders.Sort((l, r) => StringComparer.OrdinalIgnoreCase.Compare(l.FullName, r.FullName)); var keyItem = new TreeViewItem { Header = key.Key + " (" + folders.Count + ")" }; foreach (var folder in folders.OrderBy(f => f, StringComparer.OrdinalIgnoreCase)) keyItem.Items.Add(new TreeViewItem { Header = folder }); lookupItem.Items.Add(keyItem); } } lookupItem.ExpandSubtree(); treeView.Items.Add(lookupItem); var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var bookmark in rootFolder.AllBookmarks) set.Add(bookmark.ToString()); foreach (var txt in set) Debug.WriteLine(txt); using (var output = File.OpenWrite(@"C:\Documents\output.html")) { output.SetLength(0); using (var writer = new StreamWriter(output)) { writer.WriteLine(@"<!DOCTYPE NETSCAPE-Bookmark-file-1>"); writer.WriteLine(@"<!-- This is an automatically generated file."); writer.WriteLine(@" It will be read and overwritten."); writer.WriteLine(@" DO NOT EDIT! -->"); writer.WriteLine( "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html;charset=UTF-8\">"); writer.WriteLine(@"<TITLE>Bookmarks</TITLE>"); WriteFolder(rootFolder, writer, new HashSet<string>(StringComparer.OrdinalIgnoreCase), ""); } } //Debugger.Break(); } }
static SizeComparison CheckZip(Folder zip, Folder folder) { SizeComparison size = new SizeComparison(); foreach (FolderItem sItem in zip.Items()) { FolderItem dItem = null; foreach (FolderItem item in folder.Items()) if (item.Name == sItem.Name) { dItem = item; break; } if (dItem == null) continue; if (sItem.IsFolder) { if (!dItem.IsFolder) continue; Folder sFolder = sItem.GetFolder; Folder dFolder = dItem.GetFolder; SizeComparison fSize = CheckZip(sFolder, dFolder); size.sSize += fSize.sSize; size.dSize += fSize.dSize; } else { if (dItem.IsFolder) continue; size.sSize += (UInt64)sItem.Size; size.dSize += (UInt64)dItem.Size; } } return size; }
/// <summary> /// Add the folder into the media library. /// </summary> public void AddFolder(string path) { // make sure the folder isnt already in the list bool exists = false; this.Foreach (delegate (TreeModel model, TreePath tree_path, TreeIter iter) { Folder node = (Folder) model.GetValue (iter, 0); if (node.Path == path) exists = true; return exists; }); // add the folder if it isnt already in the list if (exists) library.MainPage.ThrowError ("The folder is already in the library:\n" + path); else { Folder folder = new Folder (path); this.AppendValues (root_iter, folder); library.MainPage.DataManager.AddFolder (folder); // load the files within the directory Progress progress = new Progress (library.MediaBox); progress.Start (Utils.FileCount (path)); progress.Push ("Waiting in queue: " + Utils.GetFolderName (path)); // queue process delegate_queue.Enqueue (delegate { addDirRecurse (path, progress, folder); progress.End (); }); } }
protected override void ProcessRecord() { var folder = new Folder(Title, Desc); WriteObject(folder); base.ProcessRecord(); }
public static IEnumerable<Task> GetTasks(Folder[] folders = null) { var stringOptions = new string[] { "", null, " ", "kevin", DateTime.Now.ToLongDateString(), "you rock the house with cheese" }; folders = folders ?? new Folder[] { null, new Folder("foo", Colors.Red) }; List<Folder> folderOptions = folders.ToList(); if (!folderOptions.Contains(null)) { folderOptions.Add(null); } var dateOptions = new DateTime?[] { null, DateTime.Now, DateTime.Now.AddDays((Util.Rnd.NextDouble() - .5) * 100) }; foreach (TimeSpan? estimate in new TimeSpan?[] { null, TimeSpan.FromDays(Util.Rnd.NextDouble() * 10), TimeSpan.FromDays(Util.Rnd.NextDouble() * 10) }) { foreach (bool? important in new bool?[] { true, false, null }) { foreach (var description in stringOptions) { foreach (var completeData in dateOptions) { foreach (var folder in folderOptions) { foreach (var dueDate in dateOptions) { yield return new Task() { Description = description, Due = dueDate, Folder = folder, Completed = completeData, Estimate = estimate, IsImportant = important, }; } } } } } } }
public static FindItemsResults<Item> GetAllMessages(ExchangeService service, Folder targetFolder, int start, int length) { //Create empty list for all mailbox messages: var listing = new List<EmailMessage>(); //Create ItemView with correct pagesize and offset: ItemView view = new ItemView(length, start, OffsetBasePoint.Beginning); view.PropertySet = new PropertySet(EmailMessageSchema.Id, EmailMessageSchema.Subject, EmailMessageSchema.DateTimeReceived, EmailMessageSchema.From ); view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending); FindItemsResults<Item> findResults = service.FindItems(targetFolder.Id, view); //bool MoreItems = true; //while(MoreItems) //{ //foreach (EmailMessage it in findResults.Items) //{ // listing.Add(it); //} //} //return View(listing.ToPagedList<EmailMessage>(pageNumber, pageSize)); return findResults; }
public Folder FolderForPath(string path) { Folder folder = new Folder(); if (path == null || path == "") { return folder; } folder.FolderPath = path; folder.FolderName = Path.GetFileName(path); foreach (Folder mf in MediaFolders()) { if (path.Contains(mf.FolderPath)) { folder.MediaFolderId = mf.FolderId; } } if (folder.IsMediaFolder() || serverSettings.MediaFolders == null) { int folderId = this.database.GetScalar<int>("SELECT FolderId FROM Folder WHERE FolderName = ? AND ParentFolderId IS NULL", folder.FolderName); folder.FolderId = folderId == 0 ? (int?)null : folderId; } else { folder.ParentFolderId = GetParentFolderId(folder.FolderPath); int folderId = this.database.GetScalar<int>("SELECT FolderId FROM Folder WHERE FolderName = ? AND ParentFolderId = ?", folder.FolderName, folder.ParentFolderId); folder.FolderId = folderId == 0 ? (int?)null : folderId; } return folder; }
async Task UpdateFolder(StorageFolder storageFolder) { var folder = await databaseConnection.Table<Folder>().Where(p => p.Path == storageFolder.Path).FirstOrDefaultAsync(); if (folder == null) { folder = new Folder() { LastUpdateTime = DateTime.Now, CheckedToday = true, Path = storageFolder.Path }; await databaseConnection.InsertAsync(folder); await UpdateFilesInFolder(folder.Id, storageFolder); } else { var dateChanged = (await storageFolder.GetBasicPropertiesAsync()).DateModified; if (dateChanged > folder.LastUpdateTime) { await UpdateFilesInFolder(folder.Id, storageFolder); folder.LastUpdateTime = DateTime.Now; } folder.CheckedToday = true; await databaseConnection.UpdateAsync(folder); } foreach (var subFolder in await storageFolder.GetFoldersAsync()) await UpdateFolder(subFolder); }
private static long sumFileSize(Folder rootFolder, Folder searchFolder) { long sum = 0; if (rootFolder.Name == searchFolder.Name) { sum = rootFolder.FolderSize; return sum; } foreach (var folder in rootFolder.Folders) { if (folder.Name == searchFolder.Name) { sum = folder.FolderSize; return sum; } else { sumFileSize(folder, searchFolder); } } return sum; }
public virtual void Initialize() { context = Mock.Of<ITypeDescriptorContext>(); solution = new Solution(); project = new Project { Name = "project", PhysicalPath = @"c:\projects\solution\project\project.csproj" }; folder = new Folder(); item = new Item { Data = { CustomTool = "", IncludeInVSIX = "false", CopyToOutputDirectory = CopyToOutput.DoNotCopy, ItemType = "None" }, PhysicalPath = @"c:\projects\solution\project\assets\icon.ico" }; folder.Items.Add(item); project.Items.Add(folder); project.Data.AssemblyName = "project"; solution.Items.Add(project); serviceProvider = new Mock<IServiceProvider>(); componentModel = new Mock<IComponentModel>(); picker = new Mock<ISolutionPicker>(); var uriProvider = new PackUriProvider(); var pack = new ResourcePack(item); var uriService = new Mock<IUriReferenceService>(); uriService.Setup(u => u.CreateUri<ResourcePack>(It.IsAny<ResourcePack>(), "pack")).Returns(uriProvider.CreateUri(pack)); serviceProvider.Setup(s => s.GetService(typeof(SComponentModel))).Returns(componentModel.Object); serviceProvider.Setup(s => s.GetService(typeof(ISolution))).Returns(solution); serviceProvider.Setup(s => s.GetService(typeof(IUriReferenceService))).Returns(uriService.Object); componentModel.Setup(c => c.GetService<Func<ISolutionPicker>>()).Returns(new Func<ISolutionPicker>(() => { return picker.Object; })); picker.Setup(p => p.Filter).Returns(Mock.Of<IPickerFilter>()); }
private static void TraverseDirectory(Folder currentFolder) { try { DirectoryInfo currentDirecotoryInfo = new DirectoryInfo(currentFolder.Name); DirectoryInfo[] subDirectories = currentDirecotoryInfo.GetDirectories(); foreach (var file in currentDirecotoryInfo.GetFiles()) { currentFolder.AddFile(file.Name, (int)file.Length); } foreach (var dir in subDirectories) { currentFolder.AddFolder(dir.FullName); } foreach (var child in currentFolder.ChildFolders) { TraverseDirectory(child); } } catch (UnauthorizedAccessException uae) { Console.WriteLine("Cannot access directory: {0}", uae.Message); } catch(DirectoryNotFoundException dnf) { Console.WriteLine("Directory not found: {0}", dnf.Message); } }
public override void AsyncUpload(Folder parent, string filePath) { if (!IsAuthenticated) { throw new FilesOnlineAuthenticationException("You must login before you can upload files."); } if (!System.IO.File.Exists(filePath)) { throw new FilesOnlineException("Specified upload file does not exist on this machine."); } if (parent == null) { throw new FilesOnlineException("Not all parameters were supplied or were invalid."); } if ((threadUpload != null) && threadUpload.IsAlive) { throw new FilesOnlineException( "Only one file can be upload at a time. Please wait for the current file to finish upload."); } fileUploader = new FileUploader(string.Format(Constants.BoxAPIUploadUrl, User.Sid), this) {Proxy = Proxy}; fileUploader.SetField("location", parent.Id.ToString()); fileUploading = filePath; threadUpload = new Thread(Upload); threadUpload.Start(); Busy = true; }
public DefaultKnownFolders( MigrationsFolder alter_database, MigrationsFolder up, MigrationsFolder down, MigrationsFolder run_first_after_up, MigrationsFolder functions, MigrationsFolder views, MigrationsFolder sprocs, MigrationsFolder indexes, MigrationsFolder runAfterOtherAnyTimeScripts, MigrationsFolder permissions, Folder change_drop ) { this.alter_database = alter_database; this.up = up; this.down = down; this.run_first_after_up = run_first_after_up; this.functions = functions; this.views = views; this.sprocs = sprocs; this.indexes = indexes; this.runAfterOtherAnyTimeScripts = runAfterOtherAnyTimeScripts; this.permissions = permissions; this.change_drop = change_drop; }
public override void WithResolvingModelHost(ModelHostResolveContext modelHostContext) { var modelHost = modelHostContext.ModelHost; var model = modelHostContext.Model; var childModelType = modelHostContext.ChildModelType; var action = modelHostContext.Action; var folderModelHost = modelHost as FolderModelHost; var webPartPageDefinition = model as WebPartPageDefinition; Folder folder = folderModelHost.CurrentListFolder; if (folder != null && webPartPageDefinition != null) { var context = folder.Context; var currentPage = GetCurrentWebPartPageFile(folderModelHost.CurrentList, folder, GetSafeWebPartPageFileName(webPartPageDefinition)); //var currentListItem = currentPage.ListItemAllFields; //context.Load(currentListItem); context.ExecuteQueryWithTrace(); if (typeof(WebPartDefinitionBase).IsAssignableFrom(childModelType) || childModelType == typeof(DeleteWebPartsDefinition)) { var listItemHost = ModelHostBase.Inherit <ListItemModelHost>(folderModelHost, itemHost => { itemHost.HostFolder = folderModelHost.CurrentListFolder; itemHost.HostListItem = folderModelHost.CurrentListItem; itemHost.HostFile = currentPage; itemHost.HostList = folderModelHost.CurrentList; }); action(listItemHost); //currentListItem.Update(); } else if (typeof(BreakRoleInheritanceDefinition).IsAssignableFrom(childModelType) || typeof(SecurityGroupLinkDefinition).IsAssignableFrom(childModelType)) { var currentListItem = currentPage.ListItemAllFields; context.Load(currentListItem); context.ExecuteQueryWithTrace(); var listItemHost = ModelHostBase.Inherit <ListItemModelHost>(folderModelHost, itemHost => { itemHost.HostListItem = currentListItem; }); action(listItemHost); } else { action(currentPage); } context.ExecuteQueryWithTrace(); } else { action(modelHost); } }
public OperationContext Move(Folder target) { LoadTestFile().MoveTo(target); return(this); }
void IUtilityCommand.Run(Utility utility, string[] args) { // HACK: The engine code assumes that Game.modData is set. var modData = Game.ModData = utility.ModData; // HACK: We know that maps can only be oramap or folders, which are ReadWrite var folder = new Folder(Platform.EngineDir); if (!(folder.OpenPackage(args[1], modData.ModFiles) is IReadWritePackage package)) { throw new FileNotFoundException(args[1]); } IEnumerable <UpdateRule> rules = null; if (args.Length > 2) { rules = UpdatePath.FromSource(modData.ObjectCreator, args[2]); } if (rules == null) { Console.WriteLine("--update-map MAP SOURCE [--detailed] [--apply]"); if (args.Length > 2) { Console.WriteLine("Unknown source: " + args[2]); } Console.WriteLine("Valid sources are:"); var ruleGroups = new Dictionary <string, List <string> >(); // Print known tags Console.WriteLine(" Update Paths:"); foreach (var p in UpdatePath.KnownPaths) { Console.WriteLine(" " + p); ruleGroups[p] = UpdatePath.FromSource(modData.ObjectCreator, p, false) .Select(r => r.GetType().Name) .Where(r => !ruleGroups.Values.Any(g => g.Contains(r))) .ToList(); } // Print known rules Console.WriteLine(" Individual Rules:"); foreach (var kv in ruleGroups) { if (!kv.Value.Any()) { continue; } Console.WriteLine(" " + kv.Key + ":"); foreach (var r in kv.Value) { Console.WriteLine(" " + r); } } var other = UpdatePath.KnownRules(modData.ObjectCreator) .Where(r => !ruleGroups.Values.Any(g => g.Contains(r))); if (other.Any()) { Console.WriteLine(" Other:"); foreach (var r in other) { Console.WriteLine(" " + r); } } return; } if (args.Contains("--apply")) { ApplyRules(modData, package, rules); } else { UpdateModCommand.PrintSummary(rules, args.Contains("--detailed")); } }
/// <summary> /// Converts a GeoJSON geometry to a KML element and adds it to the KML folder. /// </summary> /// <param name="folder">KML folder</param> /// <param name="elementName">name of element to create</param> /// <param name="geometry">GeoJSON geometry</param> private void ConvertGeometryToKml( Folder folder, string elementName, Geometry geometry) { switch (geometry) { case PointGeometry pointGeometry: this.AddPointPlacemark( folder, elementName, pointGeometry.Coordinates); break; case MultiPointGeometry multiPointGeometry: foreach (var pointCollection in multiPointGeometry.Coordinates) { this.AddPointPlacemark( folder, elementName, pointCollection); } break; case LineStringGeometry lineStringGeometry: this.AddLineStringPlacemark( folder, elementName, lineStringGeometry.Coordinates); break; case MultiLineStringGeometry multiLineStringGeometry: foreach (var lineStringCollection in multiLineStringGeometry.Coordinates) { this.AddLineStringPlacemark(folder, elementName, lineStringCollection); } break; case PolygonGeometry polygonGeometry: foreach (var polygonCollection in polygonGeometry.Coordinates) { this.AddPolygonPlacemark(folder, elementName, polygonCollection); } break; case MultiPolygonGeometry multiPolygonGeometry: foreach (var multiPolygonCollection in multiPolygonGeometry.Coordinates) { foreach (var polygonCollection in multiPolygonCollection) { this.AddPolygonPlacemark(folder, elementName, polygonCollection); } } break; default: throw new FormatException("invalid geometry type"); } }
public async Task <int> Update(Folder folder) { return(await Context.SaveChangesAsync()); }
//public async Task<bool> CheckEmptyFolder(int? folderId) //{ // if (!folderId.HasValue) // { // folderId = -1; // } // List<FolderViewModel> list = await GetAllFolder(folderId); // //kiem tra them file co trong folder khong // return list.Count == 0; //} public async Task <int> Insert(Folder folder) { _folderRepository.Create(folder); return(await Context.SaveChangesAsync()); }
public TextureCompositor ComposeTextureMap(Folder characterAssets, WebBodyColors bodyColors) { Contract.Requires(characterAssets != null && bodyColors != null); TextureCompositor compositor = new TextureCompositor(AvatarType.R15, 1024, 568); // Append BodyColors compositor.AppendColor(bodyColors.HeadColorId, RECT_HEAD); compositor.AppendColor(bodyColors.TorsoColorId, RECT_TORSO); compositor.AppendColor(bodyColors.LeftArmColorId, RECT_LEFT_ARM); compositor.AppendColor(bodyColors.LeftLegColorId, RECT_LEFT_LEG); compositor.AppendColor(bodyColors.RightArmColorId, RECT_RIGHT_ARM); compositor.AppendColor(bodyColors.RightLegColorId, RECT_RIGHT_LEG); // Append Face Asset face = GetAvatarFace(characterAssets); compositor.AppendTexture(face, RECT_HEAD, 1); // Append Shirt Shirt shirt = characterAssets.FindFirstChildOfClass <Shirt>(); if (shirt != null) { Asset shirtTemplate = Asset.GetByAssetId(shirt.ShirtTemplate); compositor.AppendTexture(shirtTemplate, COMPOSIT_TORSO, RECT_TORSO, 2); compositor.AppendTexture(shirtTemplate, COMPOSIT_LEFT_LIMB, RECT_LEFT_ARM, 1); compositor.AppendTexture(shirtTemplate, COMPOSIT_RIGHT_LIMB, RECT_RIGHT_ARM, 1); } // Append Pants Pants pants = characterAssets.FindFirstChildOfClass <Pants>(); if (pants != null) { Asset pantsTemplate = Asset.GetByAssetId(pants.PantsTemplate); compositor.AppendTexture(pantsTemplate, COMPOSIT_TORSO, RECT_TORSO, 1); compositor.AppendTexture(pantsTemplate, COMPOSIT_LEFT_LIMB, RECT_LEFT_LEG, 1); compositor.AppendTexture(pantsTemplate, COMPOSIT_RIGHT_LIMB, RECT_RIGHT_LEG, 1); } // Append T-Shirt ShirtGraphic tshirt = characterAssets.FindFirstChildOfClass <ShirtGraphic>(); if (tshirt != null) { Asset graphic = Asset.GetByAssetId(tshirt.Graphic); compositor.AppendTexture(graphic, RECT_TSHIRT, 4); } // Append Package Overlays Folder avatarParts = characterAssets.FindFirstChild <Folder>("ASSEMBLY"); List <BodyPart> overlainLimbs = new List <BodyPart>(); foreach (MeshPart part in avatarParts.GetChildrenOfType <MeshPart>()) { BodyPart?maybeLimb = GetLimb(part); if (!maybeLimb.HasValue) { continue; } BodyPart limb = maybeLimb.Value; string textureId = part.TextureID; if (textureId != null && textureId.Length > 0 && !overlainLimbs.Contains(limb)) { Asset overlay = Asset.GetByAssetId(textureId); Rectangle crop = UVCrops[limb]; compositor.AppendTexture(overlay, crop, 3); overlainLimbs.Add(limb); } } return(compositor); }
public StudioMdlWriter AssembleModel(Folder characterAssets, AvatarScale scale, bool collisionModel = false) { Contract.Requires(characterAssets != null); StudioMdlWriter meshBuilder = new StudioMdlWriter(); // Build Character var import = R15AssemblyAsset.OpenAsModel(); Folder assembly = import.FindFirstChild <Folder>("ASSEMBLY"); BasePart head = assembly.FindFirstChild <BasePart>("Head"); assembly.Parent = characterAssets; foreach (Instance asset in characterAssets.GetChildren()) { if (asset is BasePart) { BasePart existing = assembly.FindFirstChild <BasePart>(asset.Name); if (existing != null) { existing.Destroy(); } asset.Parent = assembly; } else if (asset is Folder && asset.Name == "R15ArtistIntent") { foreach (BasePart child in asset.GetChildrenOfType <BasePart>()) { BasePart existing = assembly.FindFirstChild <BasePart>(child.Name); if (existing != null) { existing.Destroy(); } child.Parent = assembly; } } else if (asset is Accoutrement && !collisionModel) { PrepareAccessory(asset, assembly); } else if (asset is DataModelMesh) { OverwriteHead(asset as DataModelMesh, head); } } // Apply limb scaling var parts = assembly.GetChildrenOfType <BasePart>(); var attachMap = new Dictionary <string, Attachment>(); var avatarParts = parts.Where((part) => { var limb = GetLimb(part); return(limb.HasValue); }); var accessoryParts = parts.Except(avatarParts); foreach (BasePart avatarPart in avatarParts) { Vector3 limbScale = ComputeLimbScale(scale, avatarPart); foreach (Attachment att in avatarPart.GetChildrenOfType <Attachment>()) { attachMap[att.Name] = att; } ScalePart(avatarPart, limbScale); } // Apply accessory scaling foreach (BasePart handle in accessoryParts) { Attachment handleAtt = handle.FindFirstChildOfClass <Attachment>(); if (handleAtt != null) { string attName = handleAtt.Name; if (attachMap.ContainsKey(attName)) { Attachment avatarAtt = attachMap[attName]; BasePart avatarPart = avatarAtt.Parent as BasePart; Vector3 accessoryScale = ComputeAccessoryScale(scale, avatarPart, handle); ScalePart(handle, accessoryScale); } } } BasePart torso = assembly.FindFirstChild <BasePart>("LowerTorso"); torso.CFrame = new CFrame(); BoneKeyframe keyframe = AssembleBones(meshBuilder, torso); List <StudioBone> bones = keyframe.Bones; // Build File Data. Rbx2Source.Print("Building Geometry..."); Rbx2Source.IncrementStack(); foreach (StudioBone bone in bones) { BuildAvatarGeometry(meshBuilder, bone); } Rbx2Source.DecrementStack(); return(meshBuilder); }
private MultiItemResolverResult ResolveVideos <T>(Folder parent, IEnumerable <FileSystemMetadata> fileSystemEntries, IDirectoryService directoryService, bool suppportMultiEditions, string collectionType, bool parseName) where T : Video, new() { var files = new List <FileSystemMetadata>(); var videos = new List <BaseItem>(); var leftOver = new List <FileSystemMetadata>(); // Loop through each child file/folder and see if we find a video foreach (var child in fileSystemEntries) { // This is a hack but currently no better way to resolve a sometimes ambiguous situation if (string.IsNullOrWhiteSpace(collectionType)) { if (string.Equals(child.Name, "tvshow.nfo", StringComparison.OrdinalIgnoreCase) || string.Equals(child.Name, "season.nfo", StringComparison.OrdinalIgnoreCase)) { return(null); } } if (child.IsDirectory) { leftOver.Add(child); } else if (IsIgnored(child.Name)) { } else { files.Add(child); } } var namingOptions = ((LibraryManager)LibraryManager).GetNamingOptions(); var resolver = new VideoListResolver(namingOptions); var resolverResult = resolver.Resolve(files, suppportMultiEditions).ToList(); var result = new MultiItemResolverResult { ExtraFiles = leftOver, Items = videos }; var isInMixedFolder = resolverResult.Count > 1 || (parent != null && parent.IsTopParent); foreach (var video in resolverResult) { var firstVideo = video.Files.First(); var videoItem = new T { Path = video.Files[0].Path, IsInMixedFolder = isInMixedFolder, ProductionYear = video.Year, Name = parseName ? video.Name : Path.GetFileNameWithoutExtension(video.Files[0].Path), AdditionalParts = video.Files.Skip(1).Select(i => i.Path).ToArray(), LocalAlternateVersions = video.AlternateVersions.Select(i => i.Path).ToArray() }; SetVideoType(videoItem, firstVideo); Set3DFormat(videoItem, firstVideo); result.Items.Add(videoItem); } result.ExtraFiles.AddRange(files.Where(i => !ContainsFile(resolverResult, i))); return(result); }
/// <summary> /// Finds a movie based on a child file system entries /// </summary> /// <typeparam name="T"></typeparam> /// <returns>Movie.</returns> private T FindMovie <T>(ItemResolveArgs args, string path, Folder parent, List <FileSystemMetadata> fileSystemEntries, IDirectoryService directoryService, string collectionType, bool parseName) where T : Video, new() { var multiDiscFolders = new List <FileSystemMetadata>(); var libraryOptions = args.GetLibraryOptions(); var supportPhotos = string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) && libraryOptions.EnablePhotos; var photos = new List <FileSystemMetadata>(); // Search for a folder rip foreach (var child in fileSystemEntries) { var filename = child.Name; if (child.IsDirectory) { if (IsDvdDirectory(child.FullName, filename, directoryService)) { var movie = new T { Path = path, VideoType = VideoType.Dvd }; Set3DFormat(movie); return(movie); } if (IsBluRayDirectory(child.FullName, filename, directoryService)) { var movie = new T { Path = path, VideoType = VideoType.BluRay }; Set3DFormat(movie); return(movie); } multiDiscFolders.Add(child); } else if (IsDvdFile(filename)) { var movie = new T { Path = path, VideoType = VideoType.Dvd }; Set3DFormat(movie); return(movie); } else if (supportPhotos && !child.IsHidden && PhotoResolver.IsImageFile(child.FullName, _imageProcessor)) { photos.Add(child); } } // TODO: Allow GetMultiDiscMovie in here var supportsMultiVersion = !string.Equals(collectionType, CollectionType.HomeVideos) && !string.Equals(collectionType, CollectionType.Photos) && !string.Equals(collectionType, CollectionType.MusicVideos); var result = ResolveVideos <T>(parent, fileSystemEntries, directoryService, supportsMultiVersion, collectionType, parseName) ?? new MultiItemResolverResult(); if (result.Items.Count == 1) { var videoPath = result.Items[0].Path; var hasPhotos = photos.Any(i => !PhotoResolver.IsOwnedByResolvedMedia(LibraryManager, libraryOptions, videoPath, i.Name)); if (!hasPhotos) { var movie = (T)result.Items[0]; movie.IsInMixedFolder = false; movie.Name = Path.GetFileName(movie.ContainingFolderPath); return(movie); } } if (result.Items.Count == 0 && multiDiscFolders.Count > 0) { return(GetMultiDiscMovie <T>(multiDiscFolders, directoryService)); } return(null); }
public SaveMapLogic(Widget widget, ModData modData, Action <string> onSave, Action onExit, Map map, List <MiniYamlNode> playerDefinitions, List <MiniYamlNode> actorDefinitions) { var title = widget.Get <TextFieldWidget>("TITLE"); title.Text = map.Title; var author = widget.Get <TextFieldWidget>("AUTHOR"); author.Text = map.Author; var visibilityPanel = Ui.LoadWidget("MAP_SAVE_VISIBILITY_PANEL", null, new WidgetArgs()); var visOptionTemplate = visibilityPanel.Get <CheckboxWidget>("VISIBILITY_TEMPLATE"); visibilityPanel.RemoveChildren(); foreach (MapVisibility visibilityOption in Enum.GetValues(typeof(MapVisibility))) { // To prevent users from breaking the game only show the 'Shellmap' option when it is already set. if (visibilityOption == MapVisibility.Shellmap && !map.Visibility.HasFlag(visibilityOption)) { continue; } var checkbox = (CheckboxWidget)visOptionTemplate.Clone(); checkbox.GetText = () => visibilityOption.ToString(); checkbox.IsChecked = () => map.Visibility.HasFlag(visibilityOption); checkbox.OnClick = () => map.Visibility ^= visibilityOption; visibilityPanel.AddChild(checkbox); } var visibilityDropdown = widget.Get <DropDownButtonWidget>("VISIBILITY_DROPDOWN"); visibilityDropdown.OnMouseDown = _ => { visibilityDropdown.RemovePanel(); visibilityDropdown.AttachPanel(visibilityPanel); }; var writableDirectories = new List <SaveDirectory>(); SaveDirectory selectedDirectory = null; var directoryDropdown = widget.Get <DropDownButtonWidget>("DIRECTORY_DROPDOWN"); { Func <SaveDirectory, ScrollItemWidget, ScrollItemWidget> setupItem = (option, template) => { var item = ScrollItemWidget.Setup(template, () => selectedDirectory == option, () => selectedDirectory = option); item.Get <LabelWidget>("LABEL").GetText = () => option.DisplayName; return(item); }; foreach (var kv in modData.MapCache.MapLocations) { var folder = kv.Key as Folder; if (folder == null) { continue; } try { using (var fs = File.Create(Path.Combine(folder.Name, ".testwritable"), 1, FileOptions.DeleteOnClose)) { // Do nothing: we just want to test whether we can create the file } writableDirectories.Add(new SaveDirectory(folder, kv.Value.ToString(), kv.Value)); } catch { // Directory is not writable } } if (map.Package != null) { selectedDirectory = writableDirectories.FirstOrDefault(k => k.Folder.Contains(map.Package.Name)); } // Prioritize MapClassification.User directories over system directories if (selectedDirectory == null) { selectedDirectory = writableDirectories.OrderByDescending(kv => kv.Classification).First(); } directoryDropdown.GetText = () => selectedDirectory?.DisplayName ?? ""; directoryDropdown.OnClick = () => directoryDropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 210, writableDirectories, setupItem); } var mapIsUnpacked = map.Package != null && map.Package is Folder; var filename = widget.Get <TextFieldWidget>("FILENAME"); filename.Text = map.Package == null ? "" : mapIsUnpacked?Path.GetFileName(map.Package.Name) : Path.GetFileNameWithoutExtension(map.Package.Name); var fileType = mapIsUnpacked ? MapFileType.Unpacked : MapFileType.OraMap; var fileTypes = new Dictionary <MapFileType, MapFileTypeInfo>() { { MapFileType.OraMap, new MapFileTypeInfo { Extension = ".oramap", UiLabel = ".oramap" } }, { MapFileType.Unpacked, new MapFileTypeInfo { Extension = "", UiLabel = "(unpacked)" } } }; var typeDropdown = widget.Get <DropDownButtonWidget>("TYPE_DROPDOWN"); { Func <KeyValuePair <MapFileType, MapFileTypeInfo>, ScrollItemWidget, ScrollItemWidget> setupItem = (option, template) => { var item = ScrollItemWidget.Setup(template, () => fileType == option.Key, () => { typeDropdown.Text = option.Value.UiLabel; fileType = option.Key; }); item.Get <LabelWidget>("LABEL").GetText = () => option.Value.UiLabel; return(item); }; typeDropdown.Text = fileTypes[fileType].UiLabel; typeDropdown.OnClick = () => typeDropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 210, fileTypes, setupItem); } var close = widget.Get <ButtonWidget>("BACK_BUTTON"); close.OnClick = () => { Ui.CloseWindow(); onExit(); }; var save = widget.Get <ButtonWidget>("SAVE_BUTTON"); save.OnClick = () => { if (string.IsNullOrEmpty(filename.Text)) { return; } map.Title = title.Text; map.Author = author.Text; if (actorDefinitions != null) { map.ActorDefinitions = actorDefinitions; } if (playerDefinitions != null) { map.PlayerDefinitions = playerDefinitions; } map.RequiresMod = modData.Manifest.Id; var combinedPath = Platform.ResolvePath(Path.Combine(selectedDirectory.Folder.Name, filename.Text + fileTypes[fileType].Extension)); // Invalidate the old map metadata if (map.Uid != null && map.Package != null && map.Package.Name == combinedPath) { modData.MapCache[map.Uid].Invalidate(); } try { if (!(map.Package is IReadWritePackage package) || package.Name != combinedPath) { selectedDirectory.Folder.Delete(combinedPath); if (fileType == MapFileType.OraMap) { package = ZipFileLoader.Create(combinedPath); } else { package = new Folder(combinedPath); } } map.Save(package); // Update the map cache so it can be loaded without restarting the game modData.MapCache[map.Uid].UpdateFromMap(map.Package, selectedDirectory.Folder, selectedDirectory.Classification, null, map.Grid.Type); Console.WriteLine("Saved current map at {0}", combinedPath); Ui.CloseWindow(); onSave(map.Uid); } catch (Exception e) { Log.Write("debug", "Failed to save map at {0}: {1}", combinedPath, e.Message); Log.Write("debug", "{0}", e.StackTrace); ConfirmationDialogs.ButtonPrompt( title: "Failed to save map", text: "See debug.log for details.", onConfirm: () => { }, confirmText: "Ok"); } }; }
private VirtualTreeNode AddFolderNode(Folder folder) { return(AddNode(folder.Name, Images.GetIconFor(folder), false, folder)); }
private XmlNode CreateChangeNode(XmlDocument doc, string nameSpaceUri, ChangeType changeType, FolderTree fullFolderTree, ISyncItemId mailboxSyncId, HierarchySyncOperation op, string shortId, string parentShortId, ref bool sendWatson) { XmlNode xmlNode = null; switch (changeType) { case ChangeType.Add: xmlNode = doc.CreateElement("Add", nameSpaceUri); base.ProtocolLogger.IncrementValue("F", PerFolderProtocolLoggerData.ServerAdds); break; case ChangeType.Change: xmlNode = doc.CreateElement("Update", nameSpaceUri); base.ProtocolLogger.IncrementValue("F", PerFolderProtocolLoggerData.ServerChanges); break; } AirSyncDiagnostics.TraceDebug <string, string, string>(ExTraceGlobals.AlgorithmTracer, this, "FolderSyncCommand.CreateChangeNode(). <{0}> node for folder {1} with short ID {2} will be sent to client.", Enum.GetName(typeof(ChangeType), changeType), op.DisplayName, shortId); XmlNode xmlNode2 = doc.CreateElement("ServerId", nameSpaceUri); xmlNode2.InnerText = shortId; xmlNode.AppendChild(xmlNode2); XmlNode xmlNode3 = doc.CreateElement("ParentId", nameSpaceUri); xmlNode3.InnerText = (string.IsNullOrEmpty(parentShortId) ? "0" : parentShortId); xmlNode.AppendChild(xmlNode3); XmlNode xmlNode4 = doc.CreateElement("DisplayName", nameSpaceUri); if (op.DisplayName.Length < 255) { xmlNode4.InnerText = op.DisplayName; } else { using (Folder folder = op.GetFolder()) { xmlNode4.InnerText = folder.DisplayName; } } xmlNode.AppendChild(xmlNode4); XmlNode xmlNode5 = doc.CreateElement("Type", nameSpaceUri); xmlNode5.InnerText = AirSyncUtility.GetAirSyncFolderType(base.MailboxSession, fullFolderTree.IsSharedFolder(mailboxSyncId), op.ItemId, op.ClassName); xmlNode.AppendChild(xmlNode5); SyncPermissions permissions = fullFolderTree.GetPermissions(mailboxSyncId); if (permissions != SyncPermissions.FullAccess) { if (base.Version < 140) { sendWatson = true; AirSyncDiagnostics.TraceError <string, SyncPermissions>(ExTraceGlobals.RequestsTracer, this, "Error trying to change folder {0} with permissions {1}. Permissions must be FullAccess.", op.DisplayName, permissions); } else { XmlNode xmlNode6 = doc.CreateElement("Permissions", nameSpaceUri); XmlNode xmlNode7 = xmlNode6; int num = (int)permissions; xmlNode7.InnerText = num.ToString(CultureInfo.InvariantCulture); xmlNode.AppendChild(xmlNode6); } } if (fullFolderTree.IsSharedFolder(mailboxSyncId)) { string owner = fullFolderTree.GetOwner(mailboxSyncId); if (base.Version < 140) { sendWatson = true; AirSyncDiagnostics.TraceError <string, string>(ExTraceGlobals.RequestsTracer, this, "Folder {0} with owner {1} is marked as shared in a version lower than 14.", op.DisplayName, owner); } else { XmlNode xmlNode8 = doc.CreateElement("Owner", nameSpaceUri); xmlNode8.InnerText = owner; xmlNode.AppendChild(xmlNode8); } } return(xmlNode); }
public SaveDirectory(Folder folder, string displayName, MapClassification classification) { Folder = folder; DisplayName = displayName; Classification = classification; }
internal void ExecMarkFileAsNew <T>(AsyncTaskData <T> obj) { TenantManager.SetCurrentTenant(Convert.ToInt32(obj.TenantID)); var folderDao = DaoFactory.GetFolderDao <T>(); T parentFolderId; if (obj.FileEntry.FileEntryType == FileEntryType.File) { parentFolderId = ((File <T>)obj.FileEntry).FolderID; } else { parentFolderId = ((Folder <T>)obj.FileEntry).ID; } var parentFolders = folderDao.GetParentFolders(parentFolderId); parentFolders.Reverse(); var userIDs = obj.UserIDs; var userEntriesData = new Dictionary <Guid, List <FileEntry> >(); if (obj.FileEntry.RootFolderType == FolderType.BUNCH) { if (!userIDs.Any()) { return; } parentFolders.Add(folderDao.GetFolder(GlobalFolder.GetFolderProjects <T>(DaoFactory))); var entries = new List <FileEntry> { obj.FileEntry }; entries = entries.Concat(parentFolders).ToList(); userIDs.ForEach(userID => { if (userEntriesData.ContainsKey(userID)) { userEntriesData[userID].AddRange(entries); } else { userEntriesData.Add(userID, entries); } RemoveFromCahce(GlobalFolder.GetFolderProjects(DaoFactory), userID); }); } else { var filesSecurity = FileSecurity; if (!userIDs.Any()) { userIDs = filesSecurity.WhoCanRead(obj.FileEntry).Where(x => x != obj.CurrentAccountId).ToList(); } if (obj.FileEntry.ProviderEntry) { userIDs = userIDs.Where(u => !UserManager.GetUsers(u).IsVisitor(UserManager)).ToList(); } parentFolders.ForEach(parentFolder => filesSecurity .WhoCanRead(parentFolder) .Where(userID => userIDs.Contains(userID) && userID != obj.CurrentAccountId) .ToList() .ForEach(userID => { if (userEntriesData.ContainsKey(userID)) { userEntriesData[userID].Add(parentFolder); } else { userEntriesData.Add(userID, new List <FileEntry> { parentFolder }); } }) ); if (obj.FileEntry.RootFolderType == FolderType.USER) { var folderDaoInt = DaoFactory.GetFolderDao <int>(); var folderShare = folderDaoInt.GetFolder(GlobalFolder.GetFolderShare(DaoFactory)); foreach (var userID in userIDs) { var userFolderId = GlobalFolder.GetFolderMy(this, DaoFactory); if (Equals(userFolderId, 0)) { continue; } Folder <int> rootFolder = null; if (obj.FileEntry.ProviderEntry) { rootFolder = obj.FileEntry.RootFolderCreator == userID ? folderDaoInt.GetFolder(userFolderId) : folderShare; } else if (!Equals(obj.FileEntry.RootFolderId, userFolderId)) { rootFolder = folderShare; } else { RemoveFromCahce(userFolderId, userID); } if (rootFolder == null) { continue; } if (userEntriesData.ContainsKey(userID)) { userEntriesData[userID].Add(rootFolder); } else { userEntriesData.Add(userID, new List <FileEntry> { rootFolder }); } RemoveFromCahce(rootFolder.ID, userID); } } else if (obj.FileEntry.RootFolderType == FolderType.COMMON) { userIDs.ForEach(userID => RemoveFromCahce(GlobalFolder.GetFolderCommon(this, DaoFactory), userID)); if (obj.FileEntry.ProviderEntry) { var commonFolder = folderDao.GetFolder(GlobalFolder.GetFolderCommon <T>(this, DaoFactory)); userIDs.ForEach(userID => { if (userEntriesData.ContainsKey(userID)) { userEntriesData[userID].Add(commonFolder); } else { userEntriesData.Add(userID, new List <FileEntry> { commonFolder }); } RemoveFromCahce(GlobalFolder.GetFolderCommon(this, DaoFactory), userID); }); } } else if (obj.FileEntry.RootFolderType == FolderType.Privacy) { foreach (var userID in userIDs) { var privacyFolderId = folderDao.GetFolderIDPrivacy(false, userID); if (Equals(privacyFolderId, 0)) { continue; } var rootFolder = folderDao.GetFolder(privacyFolderId); if (rootFolder == null) { continue; } if (userEntriesData.ContainsKey(userID)) { userEntriesData[userID].Add(rootFolder); } else { userEntriesData.Add(userID, new List <FileEntry> { rootFolder }); } RemoveFromCahce(rootFolder.ID, userID); } } userIDs.ForEach(userID => { if (userEntriesData.ContainsKey(userID)) { userEntriesData[userID].Add(obj.FileEntry); } else { userEntriesData.Add(userID, new List <FileEntry> { obj.FileEntry }); } }); } var tagDao = DaoFactory.GetTagDao <T>(); var newTags = new List <Tag>(); var updateTags = new List <Tag>(); foreach (var userID in userEntriesData.Keys) { if (tagDao.GetNewTags(userID, obj.FileEntry).Any()) { continue; } var entries = userEntriesData[userID].Distinct().ToList(); GetNewTags(userID, entries.OfType <FileEntry <int> >().ToList()); GetNewTags(userID, entries.OfType <FileEntry <string> >().ToList()); } if (updateTags.Any()) { tagDao.UpdateNewTags(updateTags); } if (newTags.Any()) { tagDao.SaveTags(newTags); } void GetNewTags <T1>(Guid userID, List <FileEntry <T1> > entries) { var tagDao1 = DaoFactory.GetTagDao <T1>(); var exist = tagDao1.GetNewTags(userID, entries).ToList(); var update = exist.Where(t => t.EntryType == FileEntryType.Folder).ToList(); update.ForEach(t => t.Count++); updateTags.AddRange(update); entries.ForEach(entry => { if (entry != null && exist.All(tag => tag != null && !tag.EntryId.Equals(entry.ID))) { newTags.Add(Tag.New(userID, entry)); } }); } }
public void UpdateFieldGroup(Field field) { Folder folder = this.CurrentFolder; if (folder != null) { if (field.Group) { this.AddGroupMenuItem(folder, field); } else { ToolStripMenuItem find = null; foreach (ToolStripMenuItem item in toolGroup.DropDownItems) { if ((Field)item.Tag == field) { find = item; break; } } if (find != null) { ToolStripMenuItem ch = null; foreach (ToolStripMenuItem item in find.DropDownItems) { if (item.Checked) { ch = item; break; } } if (find.Checked || ch != null) { ((ToolStripMenuItem)toolGroup.DropDownItems[0]).Checked = true; } toolGroup.DropDownItems.Remove(find); } } } foreach (TreeNode node in this.treeObjects.Nodes[0].Nodes) { Folder f = (Folder)node.Tag; if (f.Group == field) { f.Group = null; Database.Folders.Update(f); if (node.Nodes.Contains(this.treeObjects.SelectedNode)) { this.treeObjects.SelectedNode = node; } this.CreateGroupFolders(node, f); } } }
public FoldersControllerModel(string rootPath) { _folder = new Folder(rootPath); }
public override Folder CreateInDbAsAdmin(Folder folder) => DefaultRepository.SaveAsAdmin <ContentFolder, ContentFolderDAL>((ContentFolder)folder);
// Token: 0x06001354 RID: 4948 RVA: 0x0007788C File Offset: 0x00075A8C public static QueryFilter Execute(string searchString, bool isContentIndexingEnabled, CultureInfo userCultureInfo, IPolicyTagProvider policyTagProvider, Folder folder, SearchScope searchScope, QueryFilter advancedQueryFilter) { SearchFilterGenerator searchFilterGenerator = new SearchFilterGenerator(advancedQueryFilter, userCultureInfo, policyTagProvider); return(searchFilterGenerator.Execute(searchString, isContentIndexingEnabled, folder, searchScope)); }
protected File SearchFileByName(List list, Folder folder, string pageName) { var context = list.Context; if (folder != null) { if (!folder.IsPropertyAvailable("ServerRelativeUrl") // || !folder.IsPropertyAvailable("Properties")) ) { folder.Context.Load(folder, f => f.ServerRelativeUrl); //folder.Context.Load(folder, f => f.Properties); folder.Context.ExecuteQueryWithTrace(); } } // one more time.. var dQuery = new CamlQuery(); string QueryString = "<View><Query><Where>" + "<Eq>" + "<FieldRef Name=\"FileLeafRef\"/>" + "<Value Type=\"Text\">" + pageName + "</Value>" + "</Eq>" + "</Where></Query></View>"; dQuery.ViewXml = QueryString; if (folder != null) { dQuery.FolderServerRelativeUrl = folder.ServerRelativeUrl; } var collListItems = list.GetItems(dQuery); context.Load(collListItems); context.ExecuteQueryWithTrace(); var item = collListItems.FirstOrDefault(); if (item != null) { return(item.File); } //one more time // by full path var fileServerRelativePath = UrlUtility.CombineUrl(folder.ServerRelativeUrl, pageName); File file = null; var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { file = list.ParentWeb.GetFileByServerRelativeUrl(fileServerRelativePath); context.Load(file); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); // Forms folder im the libraries // otherwise pure list items search if (!scope.HasException && file != null && file.ServerObjectIsNull != null) { context.Load(file); context.Load(file, f => f.Exists); context.ExecuteQueryWithTrace(); if (file.Exists) { return(file); } } return(null); }
private static void Main(string[] args) { var inputPath = args[0]; var outputPath = args[1]; var fileRoot = XDocument.Load(inputPath); Console.WriteLine("Loaded XML."); var outputObject = new BitwardenRoot(); var groupsToProcess = new Queue <KeyValuePair <string, XElement> >(); if (fileRoot.Root == null) { throw new Exception("Root element missing"); } groupsToProcess.Enqueue(new KeyValuePair <string, XElement>("", fileRoot.Root.Descendants("Group").First())); while (groupsToProcess.TryDequeue(out var valuePair)) { var groupKey = valuePair.Key; var element = valuePair.Value; string folderId = null; if (groupKey != "") { folderId = Guid.NewGuid().ToString(); var newFolder = new Folder { Id = folderId, Name = groupKey }; outputObject.Folders.Add(newFolder); } var childElements = element.Elements("Group"); foreach (var childElement in childElements) { var childGroupName = childElement.Element("Name")?.Value; if (childGroupName == null) { throw new Exception("Found group with no name, malformed file"); } if (_blacklistedFolders.Contains(childGroupName)) { childGroupName = ""; } var newGroupKey = $"{groupKey}/{childGroupName}"; if (groupKey == "") { newGroupKey = childGroupName; } Console.WriteLine($"Found group '{newGroupKey}'"); groupsToProcess.Enqueue(new KeyValuePair <string, XElement>(newGroupKey, childElement)); } var childEntries = element.Elements("Entry"); foreach (var entry in childEntries) { var fields = entry.Elements("String").ToArray(); var title = fields.Where(x => x.Element("Key")?.Value == "Title").Select(x => x.Element("Value")?.Value) .First(); if (_blacklistedFields.Contains(title)) { continue; } var notes = fields.Where(x => x.Element("Key")?.Value == "Notes").Select(x => x.Element("Value")?.Value) .First(); var username = fields.Where(x => x.Element("Key")?.Value == "UserName").Select(x => x.Element("Value")?.Value) .First(); var password = fields.Where(x => x.Element("Key")?.Value == "Password").Select(x => x.Element("Value")?.Value) .First(); var url = fields.Where(x => x.Element("Key")?.Value == "URL").Select(x => x.Element("Value")?.Value) .First(); var newEntry = new Item { Id = Guid.NewGuid().ToString(), Name = title, Type = ItemType.Login, FolderId = folderId, Notes = notes, Login = new ItemLogin { Username = username, Password = password, Totp = null, Uris = new List <ItemLoginUri> { new ItemLoginUri { Match = null, Uri = url } } }, CollectionIds = null, Favorite = false, Fields = fields.Where(x => { var key = x.Element("Key")?.Value; return(key != "Title" && key != "Notes" && key != "UserName" && key != "Password" && key != "URL" && !_blacklistedFields.Contains(key)); }).Select(x => new ItemField { Name = x.Element("Key")?.Value, Type = x.Element("Value")?.Attribute("ProtectInMemory")?.Value == "True" ? ItemFieldType.HiddenText : ItemFieldType.Text, Value = x.Element("Value")?.Value }).ToList() }; outputObject.Items.Add(newEntry); } } Console.WriteLine("Serializing output file..."); var contractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy() }; var output = JsonConvert.SerializeObject(outputObject, new JsonSerializerSettings { ContractResolver = contractResolver, Formatting = Formatting.Indented }); Console.WriteLine("Writing output file..."); using (var file = File.OpenWrite(outputPath)) { file.Write(Encoding.UTF8.GetBytes(output)); } Console.WriteLine("Done!"); }
/// <summary> /// Event handler for checkbox for 'Include in documentation' menu item. /// </summary> public bool ShowPageOfGraphsChecked() { Folder folder = Apsim.Get(explorerPresenter.ApsimXFile, explorerPresenter.CurrentNodePath) as Folder; return((folder != null) ? folder.ShowPageOfGraphs : false); }
//public FileContentResult DownloadKMLTimeLine2(int id = 0) //{ // var route = db.Flights.Where(r => r.FlightID == id).Select(r => r.RouteID).FirstOrDefault(); // if (route == null) route = id; //patch if route is for some reason empty // var flights = db.Flights.Where(r => r.RouteID == route).Select(r => new { r.FlightID }).ToList(); // var doc = new Document(); // doc.Id = "Route"; // doc.Name = "Route"; // foreach (var f in flights) // { // var folder = new Folder(); // folder.Id = f.FlightID.ToString(); // folder.Name = "Flight " + f.FlightID; // var i = flights.IndexOf(f); // var flightPointStylesHide = new FlightPointStyles(i,0); // var flightPointStylesShow = new FlightPointStyles(i,1); // //var docStyle = flightPointStylesHide.style; // folder.AddStyle(flightPointStylesHide.style); // folder.AddStyle(flightPointStylesShow.style); // var styleMap = new StyleMap(flightPointStylesHide.style, flightPointStylesShow.style).styleMap; // folder.AddStyle(styleMap); // var placemarkSet = new FlightPlacemarkPoint(); // placemarkSet.styleUrlRef = styleMap.Id; // placemarkSet.getFlightPlacemarkPoints(f.FlightID); // foreach (var p in placemarkSet.placemarks) // { // folder.AddFeature(p); // } // doc.AddFeature(folder); // } // var kml = new Kml(); // kml.Feature = doc; // KmlFile kmlFile = KmlFile.Create(kml, true); // //using (var stream = System.IO.File.OpenWrite("C:/temp/kmlfile.kml")) // //{ // // kmlFile.Save(stream); // //}; // using (var stream = new System.IO.MemoryStream()) // { // kmlFile.Save(stream); // var kmlFileName = "Flight_" + id + ".kml"; // var fileBytes = new System.Text.UTF8Encoding().GetBytes(new System.Text.UTF8Encoding().GetString(stream.ToArray())); // return File(fileBytes, "application/vnd.google-earth.kml+xml", kmlFileName); // }; //} public FileContentResult DownloadKMLTimeLine(int id = 0) { var route = db.Flights.Where(r => r.FlightID == id).Select(r => r.RouteID).FirstOrDefault(); if (route == null) { route = id; //patch if route is for some reason empty } var flights = db.Flights.Where(r => r.RouteID == route).Select(r => new { r.FlightID }).ToList(); var doc = new Document(); doc.Id = "Route" + id; doc.Name = "Route " + id; foreach (var f in flights) { var folder = new Folder(); folder.Id = f.FlightID.ToString(); folder.Name = "Flight " + f.FlightID; var i = flights.IndexOf(f); var flightPointStylesHide = new FlightPointStyles(i, 0); var flightPointStylesShow = new FlightPointStyles(i, 1); //var docStyle = flightPointStylesHide.style; folder.AddStyle(flightPointStylesHide.style); folder.AddStyle(flightPointStylesShow.style); var styleMap = new StyleMap(flightPointStylesHide.style, flightPointStylesShow.style).styleMap; folder.AddStyle(styleMap); var flightLineStyles = new FlightLineStyles(i); var docStyleLine = flightLineStyles.style; folder.AddStyle(docStyleLine); var placemarkSet = new FlightPlacemarkPoint(); placemarkSet.styleUrlRef = styleMap.Id; placemarkSet.getFlightPlacemarkPoints(f.FlightID); foreach (var p in placemarkSet.placemarks) { folder.AddFeature(p); } var placemarkLineString = new FlightPlacemarkLineString(f.FlightID); placemarkLineString.styleUrlRef = docStyleLine.Id; folder.AddFeature(placemarkLineString.placemark); doc.AddFeature(folder); } var kml = new Kml(); kml.Feature = doc; KmlFile kmlFile = KmlFile.Create(kml, true); //using (var stream = System.IO.File.OpenWrite("C:/temp/kmlfile.kml")) //{ // kmlFile.Save(stream); //}; using (var stream = new System.IO.MemoryStream()) { kmlFile.Save(stream); var kmlFileName = "Flight_" + id + ".kml"; var fileBytes = new System.Text.UTF8Encoding().GetBytes(new System.Text.UTF8Encoding().GetString(stream.ToArray())); return(File(fileBytes, "application/vnd.google-earth.kml+xml", kmlFileName)); }; }
public override void DeployModel(object modelHost, DefinitionBase model) { var folderModelHost = modelHost as FolderModelHost; var definition = model as WebPartPageDefinition; var contentTypeId = string.Empty; // pre load content type if (!string.IsNullOrEmpty(definition.ContentTypeId)) { contentTypeId = definition.ContentTypeId; } else if (!string.IsNullOrEmpty(definition.ContentTypeName)) { contentTypeId = ContentTypeLookupService .LookupContentTypeByName(folderModelHost.CurrentList, definition.ContentTypeName) .Id.ToString(); } Folder folder = folderModelHost.CurrentListFolder; //if (!string.IsNullOrEmpty(webPartPageModel.FolderUrl)) // throw new NotImplementedException("FolderUrl for the web part page model is not supported yet"); var context = folder.Context; // #SPBug // it turns out that there is no support for the web part page creating via CMOM // we we need to get a byte array to 'hack' this pages out.. // http://stackoverflow.com/questions/6199990/creating-a-sharepoint-2010-page-via-the-client-object-model // http://social.technet.microsoft.com/forums/en-US/sharepointgeneralprevious/thread/6565bac1-daf0-4215-96b2-c3b64270ec08 var currentPage = GetCurrentWebPartPageFile(folderModelHost.CurrentList, folder, GetSafeWebPartPageFileName(definition)); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentPage, ObjectType = typeof(File), ObjectDefinition = definition, ModelHost = modelHost }); if ((currentPage == null) || (currentPage != null && definition.NeedOverride)) { if (definition.NeedOverride) { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing web part page"); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "NeedOverride = true. Replacing web part page."); } else { TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new web part page"); } var file = new FileCreationInformation(); var pageContent = string.Empty; if (!string.IsNullOrEmpty(definition.CustomPageLayout)) { pageContent = definition.CustomPageLayout; } else { pageContent = GetWebPartTemplateContent(definition); } var fileName = GetSafeWebPartPageFileName(definition); file.Url = fileName; file.Content = Encoding.UTF8.GetBytes(pageContent); file.Overwrite = definition.NeedOverride; var newFile = folder.Files.Add(file); FieldLookupService.EnsureDefaultValues(newFile.ListItemAllFields, definition.DefaultValues); if (!string.IsNullOrEmpty(contentTypeId)) { newFile.ListItemAllFields[BuiltInInternalFieldNames.ContentTypeId] = contentTypeId; } FieldLookupService.EnsureValues(newFile.ListItemAllFields, definition.Values, true); if (definition.Values.Any() || definition.DefaultValues.Any() || !string.IsNullOrEmpty(contentTypeId)) { newFile.ListItemAllFields.Update(); context.ExecuteQueryWithTrace(); } InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = newFile, ObjectType = typeof(File), ObjectDefinition = definition, ModelHost = modelHost }); context.Load(newFile); context.ExecuteQueryWithTrace(); } else { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing web part page"); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "NeedOverride = false. Skipping replacing web part page."); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentPage, ObjectType = typeof(File), ObjectDefinition = definition, ModelHost = modelHost }); } }
public string GetFolder(Folder folder) { return(parent.GetFolder(folder)); }
public List <EntityVersion <string, DateTime> > QueryContactItemFolder(NameSpace session, Folder folder, string expectedFolderId, string filter) { return(_strategy.QueryContactItemFolder(session, folder, expectedFolderId, filter)); }
public List <AppointmentSlim> QueryAppointmentFolder(NameSpace session, Folder folder, string filter) { return(_strategy.QueryAppointmentFolder(session, folder, filter)); }
public RollFolderView(Row row) { this.row = row; folder = row.Components.Get <FolderRow>().Folder; label = new ThemedSimpleText { ForceUncutText = false, VAlignment = VAlignment.Center, OverflowMode = TextOverflowMode.Ellipsis, LayoutCell = new LayoutCell(Alignment.LeftCenter, float.MaxValue) }; editBox = new ThemedEditBox { LayoutCell = new LayoutCell(Alignment.Center, stretchX: float.MaxValue) }; nodeIcon = new Image(IconPool.GetTexture("Tools.NewFolder")) { HitTestTarget = true, MinMaxSize = new Vector2(16, 16) }; expandButton = CreateExpandButton(); var expandButtonContainer = new Widget { Layout = new StackLayout { IgnoreHidden = false }, LayoutCell = new LayoutCell(Alignment.Center), Visible = true, Nodes = { expandButton } }; eyeButton = CreateEyeButton(); lockButton = CreateLockButton(); widget = new Widget { Padding = new Thickness { Left = 4, Right = 2 }, MinHeight = TimelineMetrics.DefaultRowHeight, Layout = new HBoxLayout { DefaultCell = new DefaultLayoutCell(Alignment.Center) }, HitTestTarget = true, Nodes = { (spacer = new Widget()), expandButtonContainer, nodeIcon, Spacer.HSpacer(3), label, editBox, new Widget(), eyeButton, lockButton, }, }; widget.Components.Add(new AwakeBehavior()); label.HitTestTarget = true; label.AddChangeWatcher(() => folder.Id, s => label.Text = folder.Id); label.Gestures.Add(new DoubleClickGesture(() => { Document.Current.History.DoTransaction(() => { var labelExtent = label.MeasureUncutText(); if (label.LocalMousePosition().X < labelExtent.X) { Rename(); } else { Document.Current.History.DoTransaction(ExpandOrCollapse); } }); })); widget.Gestures.Add(new ClickGesture(1, ShowContextMenu)); widget.CompoundPresenter.Push(new SyncDelegatePresenter <Widget>(RenderBackground)); editBox.Visible = false; }
public string ProcessingField(ListItem Item, Field oField, string PropertyName) { string FieldValue = ""; var FieldValueObject = Item[oField.InternalName]; if (FieldValueObject == null) { Folder ValuedFolder = null; this.ParentFolders.ForEach(ParentFolder => { var ParentFolderValue = ParentFolder.ListItemAllFields[oField.InternalName]; if (!String.IsNullOrEmpty(ParentFolderValue.StringValueOrEmpty())) { if (ValuedFolder == null) { ValuedFolder = ParentFolder; } } }); if (ValuedFolder != null) { FieldValue = ProcessingField(ValuedFolder.ListItemAllFields, oField, PropertyName); } } else { switch (oField.FieldTypeKind) { case FieldType.Lookup: FieldLookupValue[] LookupValues = new FieldLookupValue[] { }; if (FieldValueObject.GetType() != LookupValues.GetType()) { LookupValues = new FieldLookupValue[] { FieldValueObject as FieldLookupValue }; } foreach (FieldLookupValue LookupValue in LookupValues) { if (LookupValue != null) { if (PropertyName == "LookupId") { FieldValue += LookupValue.LookupId + "; "; continue; } FieldValue += LookupValue.LookupValue + "; "; } } if (!String.IsNullOrEmpty(FieldValue)) { FieldValue = FieldValue.Substring(0, FieldValue.Length - 2); } break; case FieldType.User: FieldUserValue[] UserValues = new FieldUserValue[] { }; if (FieldValueObject.GetType() != UserValues.GetType()) { UserValues = new FieldUserValue[] { FieldValueObject as FieldUserValue }; } foreach (FieldUserValue UserValue in UserValues) { if (UserValue != null) { if (PropertyName == "LookupId") { FieldValue += UserValue.LookupId + "; "; continue; } FieldValue += UserValue.LookupValue + "; "; } } if (!String.IsNullOrEmpty(FieldValue)) { FieldValue = FieldValue.Substring(0, FieldValue.Length - 2); } break; case FieldType.Boolean: bool BoolValue = Convert.ToBoolean(FieldValueObject); if (BoolValue) { FieldValue = "Yes"; if (this.Item.ParentList.ParentWeb.Language == 1049) { FieldValue = "Да"; } } else { FieldValue = "No"; if (this.Item.ParentList.ParentWeb.Language == 1049) { FieldValue = "Нет"; } } break; case FieldType.URL: FieldUrlValue UrlValue = FieldValueObject as FieldUrlValue; FieldValue = UrlValue.Url; if (PropertyName == "Description") { FieldValue = UrlValue.Description; } break; case FieldType.DateTime: var DateTimeValue = FieldValueObject; FieldValue = DateTimeValue.DateTimeValueOrEmpty(PropertyName); //format break; case FieldType.Note: string ServerUrl = this.Item.ParentList.ParentWeb.Url.Replace(this.Item.ParentList.ParentWeb.ServerRelativeUrl, ""); FieldValue = FieldValueObject.StringValueOrEmpty(); FieldValue = FieldValue.Replace("src=\"/", "src=\"" + ServerUrl + "/"); FieldValue = FieldValue.Replace("href=\"/", "href=\"" + ServerUrl + "/"); break; default: FieldValue = FieldValueObject.StringValueOrEmpty(); break; } } return(FieldValue); }
// Token: 0x06001355 RID: 4949 RVA: 0x000778B0 File Offset: 0x00075AB0 public QueryFilter Execute(string searchString, bool isContentIndexingEnabled, Folder folder, SearchScope searchScope) { this.searchScope = searchScope; this.folderClass = folder.ClassName; if (searchString != null) { this.queryFilter = AqsParser.ParseAndBuildQuery(searchString, SearchFilterGenerator.GetAqsParseOption(folder, isContentIndexingEnabled), this.userCultureInfo, RescopedAll.Default, null, this.policyTagProvider); } if (this.advancedQueryFilter != null) { if (this.queryFilter == null) { this.queryFilter = this.advancedQueryFilter; } else { this.queryFilter = new AndFilter(new QueryFilter[] { this.queryFilter, this.advancedQueryFilter }); } } if (this.queryFilter == null) { return(null); } this.AddItemTypeFilter(); return(this.queryFilter); }