I am very new to Linq. But I am trying to write a function to get the most recent created subdirectory by using Directory.GetDirectories(rootPath).Where(...). Is it possible and how to I continue?
var info = new DirectoryInfo(rootPath);
var latestDirectory = info.GetDirectories()
.OrderByDescending(d => d.CreationTime)
.FirstOrDefault();
You can easily change name of DirectoryInfo class property you'd like to sort by.
DirectoryInfo.GetDirectories Method returns array of System.IO.DirectoryInfo, so you can easily order that directories by CreationTime and return the first one.
VB.NET solution:
Dim info As New DirectoryInfo(rootPath)
Dim latestDirectory As DirectoryInfo = info.GetDirectories() _
.OrderByDescending(Function(d) d.CreationTime) _
.FirstOrDefault()
You need to get specific DirectoryInfo information to determine the creation time. Try this.
DirectoryInfo di = new DirectoryInfo(rootPath);
var directory = di.GetDirectories()
.OrderByDescending(d => d.CreationTime)
.FirstOrDefault();
Related
been stuck for this for a while. I need to rename a SharePoint folder using ClientContext. I created a function like so:
Public Function renameFolder(_folders As ListItemCollection, _newFolderName As String) As Boolean
Try
Using _clientContext As New ClientContext(vSharepointSite)
AddHandler _clientContext.ExecutingWebRequest, AddressOf vClaimsHelper.clientContext_ExecutingWebRequest
Dim _folder = _folders(0)
_folder.Item("Title") = _newFolderName
_folder.Item("FileLeafRef") = _newFolderName
_folder.Item("DisplayName") = _newFolderName
_folder.Update()
_clientContext.ExecuteQuery()
End Using
Return True
Catch ex As Exception
Return False
End Try
End Function
This function takes a folder collection (actually I pass a collection of only 1 folder) and the new folder name. The function executes well. Inspecting the _folder after the ExecuteQuery, everything looks as expected. However nothing happens in SharePoint, meaning that the folder name remains the original name.
Any suggestions?
Best regards and....HAPPY NEW YEAR!!!!
Ariel
Make sure List Item ( _folder variable in your example) is associated with Folder object.
How to determine whether List Item is associated with a Folder object
Using ctx As New ClientContext(webUrl)
Dim list = ctx.Web.Lists.GetByTitle(listTitle)
Dim item = list.GetItemById(itemId)
ctx.Load(item.Folder)
ctx.ExecuteQuery()
Dim isFolderItem = Not item.Folder.ServerObjectIsNull.Value
End Using
How to rename Folder using SharePoint CSOM
The following example demonstrates how to rename a Folder:
Public Sub RenameFolder(folder As Folder, folderName As String)
Dim ctx = folder.Context
Dim folderItem = folder.ListItemAllFields
folderItem("FileLeafRef") = folderName
folderItem("Title") = folderName
folderItem.Update()
ctx.ExecuteQuery()
End Sub
Usage
Using ctx As New ClientContext(webUrl)
Dim folder = ctx.Web.GetFolderByServerRelativeUrl(folderUrl)
RenameFolder(folder, "Orders")
End Using
Use the BaseName field to rename the folder.
_folder.Item("BaseName") = _newFolderName
I am trying to use the value of <Directory> in my following piece of code:
Public Function GetFile() As String
Dim di As New DirectoryInfo(< Directory >)
Dim files As FileSystemInfo() = di.GetFileSystemInfos()
Dim newestFile = files.OrderByDescending(Function(f) f.CreationTime).First
Return newestFile.FullName
End Function
Is there any way i can call the value stored in the xml file in my code?
Andy's answer is good, but in VB it's even easier.
Dim xmlDoc As XDocument
Dim dir as String
xmlDoc = XDocument.Load("XMLFile1.xml")
dir = xmlDoc.<ServerList>.<Server>.<Directory>.First().Value;
Or even easier if the XML file will never have more than one <Directory> element that you care about:
dir = xmlDoc...<Directory>.First().Value;
To answer your comment on Andy's answer:
dir = (From server as XElement in xmlDoc...<Server>
Where server.<ServerName>.First().Value = requiredServer
Select server.<Directory>.First().Value)(0);
As you are clearly familiar with Linq, you can operate on the Xml using System.Xml.Linq.
Apologies, this is in c#.
var xDoc = XDocument.Load("XMLFile1.xml");
var dir = xDoc.Element("ServerList").Elements("Server").Elements("Directory").First().Value;
If you have the Xml stored in a string replace XDocument.Load with XDocument.Parse.
Obviously you'll have to defend against parse errors, file missing and schema inconsistencies in your production code.
You can use this http://support.microsoft.com/kb/301225
I am using the following code to copy a file:
System.IO.File.Copy(strOldFile, strNewFile)
But the trouble is that the newly-created file inherits the old file's timestamp. Is there a way to force the timestamp to update?
You can edit the CreationTime using the FileInfo class.
Dim path = Path.GetTempFileName();
Dim fi As New FileInfo(path)
fi.CreationTime = DateTime.Now;
fi.LastWriteTime = DateTime.Now;
this is my code
DropDownList1.Items.Add(new ListItem(" Prueba1"));
DropDownList2.Items.Add(new ListItem(" Prueba1"));
//string[] filePaths = Directory.GetFiles(#"\\hmfsw\web\DTCWIN107\MYSITE.com\public_html\post\");
// Make a reference to a directory.
DirectoryInfo di = new DirectoryInfo(#"\\hmfsw\web\DTCWIN107\MYSITE.com\public_html\post\");
string path = #"\\hmfsw\web\DTCWIN107\MYSITE.com\public_html\linker\linker.xml";
// Get a reference to each file in that directory.
FileInfo[] fiArr = di.GetFiles();
// Display the names of the files.
foreach (FileInfo fri in fiArr)DropDownList1.Items.Add(new ListItem(fri.Name));
System.Xml.Serialization.XmlSerializer serializer =
new System.Xml.Serialization.XmlSerializer(typeof(selector));
System.IO.TextReader reader =
new System.IO.StreamReader(path);
selector s = (selector)serializer.Deserialize(reader);
reader.Close();
OKay, The first thing is that the dropdownlist daes not update with prueba1 and prueba2
But the dropdownlist do update with info of the folder...
And the second thiing is that the serializer.Deserialize daes nothing. The dropdownlist is not been load with the xml ...
Could you plz help me?
Thanks
I don't see any association between Dropdownlist and the selector.
Is there a way to look through the cache for all objects in the cache? I'm dynamically creating objects and I need to periodically go through the list to purge out objects I'm no longer using.
var keysToClear = (from System.Collections.DictionaryEntry dict in HttpContext.Cache
let key = dict.Key.ToString()
where key.StartsWith("Something_")
select key).ToList();
foreach (var key in keysToClear)
{
HttpContext.Cache.Remove(key);
}
You can enumerate through the objects:
System.Web.HttpContext.Current.Cache.GetEnumerator()
Yes, you can either index based on the cache key, or you you can iterate over the contents:
For Each c In Cache
' Do something with c
Next
' Pardon my VB syntax if it's wrong
Here is a VB function to iterate through the Cache and return a DataTable representation.
Private Function CreateTableFromHash() As DataTable
Dim dtSource As DataTable = New DataTable
dtSource.Columns.Add("Key", System.Type.GetType("System.String"))
dtSource.Columns.Add("Value", System.Type.GetType("System.String"))
Dim htCache As Hashtable = CacheManager.GetHash()
Dim item As DictionaryEntry
If Not IsNothing(htCache) Then
For Each item In htCache
dtSource.Rows.Add(New Object() {item.Key.ToString, item.Value.ToString})
Next
End If
Return dtSource
End Function
This may be a bit late, but I used the following code to easily iterate over all cache items and perform some custom logic for removal of cache items that contain a certain string in their names.
I have provided both versions of code in VB.Net as well as C#.
VB.Net Version
Dim cacheItemsToRemove As New List(Of String)()
Dim key As String = Nothing
'loop through all cache items
For Each c As DictionaryEntry In System.Web.HttpContext.Current.Cache
key = DirectCast(c.Key, String)
If key.Contains("prg") Then
cacheItemsToRemove.Add(key)
End If
Next
'remove the selected cache items
For Each k As var In cacheItemsToRemove
System.Web.HttpContext.Current.Cache.Remove(k)
Next
C# Version
List<string> cacheItemsToRemove = new List<string>();
string key = null;
//loop through all cache items
foreach (DictionaryEntry c in System.Web.HttpContext.Current.Cache)
{
key = (string)c.Key;
if (key.Contains("prg"))
{
cacheItemsToRemove.Add(key);
}
}
//remove the selected cache items
foreach (var k in cacheItemsToRemove)
{
System.Web.HttpContext.Current.Cache.Remove(k);
}
Since you potentially want to be removing items from the Cache object, it is not terribly convenient to iterate over it (as an IEnumerable), since this doesn't allow removal during the iteration process. However, given that you cannot access items by index, it is the only solution.
A bit of LINQ can however simplify the problem. Try something like the following:
var cache = HttpContext.Current.Cache;
var itemsToRemove = cache.Where(item => myPredicateHere).ToArray();
foreach (var item in itemsToRemove)
cache.Remove(itemsToRemove.Key);
Note that each item in the iteration is of type DictionaryEntry.
Jeff, you should really look up dependencies for your cached items. That's the proper way of doing this. Logically group your cached data (items) and setup dependencies for your groups. This way when you need to expire the entire group you touch such common dependency and they're all gone.
I'm not sure I understand the List of Object part.