Rename Sharepoint folder using ClientContext - asp.net

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

Related

Search files based on the date modified entered by user in console application VB.NET

i been given a assignment to create one console application using VB.NET. The assignment will able to open the file that based on the date modified entered by user. can anyone help me to solve my problem. I'm new in vb.net and most of the tutorial are using C# . together i put the latest code i has already done but still if i put the date modified the error file will display .
Thank you in advance
Imports System.IO
Module Module3
Sub Main()
While True
' Read value.
Dim s As DateTime = Console.ReadLine()
' Test the value.
If s = File.GetLastWriteTime("path") Then
Dim p As New Process()
p.StartInfo = New ProcessStartInfo("notepad.exe", "path")
p.Start()
Else
Dim p As New Process()
p.StartInfo = New ProcessStartInfo("notepad.exe", "path2")
p.Start()
End If
' Write the value.
Console.WriteLine("You typed " + s)
End While
End Sub
End Module
in the code snippet you are not searching for a file you are setting the time last modified which isn't what you want to do.
you will need to search through each file until you find the date modified information which is inputted by the user:-
dim s as datetime = console.readline()
'Target Directory
Dim directory = "C:\Users\Peter\Desktop\TestFolder\"
For Each filename As String In IO.Directory.GetFiles(directory, "*", IO.SearchOption.AllDirectories)
Dim fName As String = IO.Path.GetExtension(filename)
dim datemod as string = File.GetLastWriteTime(directory & fname)
If s = datemod Then
Dim p As New Process()
p.StartInfo = New ProcessStartInfo("notepad.exe", directory & fname)
p.Start()
Else
'do something else
endif
next
things that you will need to add are, what to do when it doesn't find a file with that variable.
hope this gets you a little further.

How to get the most recent created subdirectory by using linq?

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();

How to get Description of Youtube embeded videos in my asp.net application?

I am using the below code to get the Title and description of the youtube video embeded in my asp.net application. I am able to see the Title, but not description.
I use Atomfeed to do this...
Problem is i get the Description as "Google.GData.Client.AtomTextConstruct" for all my videos.
Private Function GetTitle(ByVal myFeed As AtomFeed) As String
Dim strTitle As String = ""
For Each entry As AtomEntry In myFeed.Entries
strTitle = entry.Title.Text
Next
Return strTitle
End Function
Private Function GetDesc(ByVal myFeed As AtomFeed) As String
Dim strDesc As String = ""
For Each entry As AtomEntry In myFeed.Entries
strDesc = entry.Summary.ToString()
Next
Return strDesc
End Function
I believe that when the XML from the atom feed is parsed, that the description is not handled. Take a look at this: http://code.google.com/p/google-gdata/wiki/UnderstandingTheUnknown
But what happens with things that are not understood? They end up as
an element of the ExtensionElements collection, that is a member of
all classes inherited from AtomBase, like AtomFeed, AtomEntry,
EventEntry etc...
So, what we can do is pull out the description from the extensionelement like this:
Dim query As New FeedQuery()
Dim service As New Service()
query.Uri = New Uri("https://gdata.youtube.com/feeds/api/standardfeeds/top_rated")
Dim myFeed As AtomFeed = service.Query(query)
For Each entry In myFeed.Entries
For Each obj As Object In entry.ExtensionElements
If TypeOf obj Is XmlExtension Then
Dim xel As XElement = XElement.Parse(TryCast(obj, XmlExtension).Node.OuterXml)
If xel.Name = "{http://search.yahoo.com/mrss/}group" Then
Dim descNode = xel.Descendants("{http://search.yahoo.com/mrss/}description").FirstOrDefault()
If descNode IsNot Nothing Then
Console.WriteLine(descNode.Value)
End If
Exit For
End If
End If
Next
Next
Also, the reason why you are getting "Google.GData.Client.AtomTextConstruct" is because Summary is an object of type Google.GData.Client.AtomTextConstruct, so doing entry.Summary.ToString() is just giving you the default ToString() behavior. You would normally do Summary.Text, but this of course is blank because as I say above, it's not handled properly by the library.
For youtube, I fetch the information for each video using the Google.GData.YouTube.
Something like this returns a lot of information from the video.
Dim yv As Google.YouTube.Video
url = New Uri("http://gdata.youtube.com/feeds/api/videos/" & video.Custom)
r = New YouTubeRequest(New YouTubeRequestSettings("??", "??"))
yv = r.Retrieve(Of Video)(url)
Then it's possible to get the description with: yv.Description

Save changes to Entity model to the database

I'm new to Entity Framework and am expanding an existing codebase. I'm using jQuery to pass the needed info back to the server ajaxy style, so I can't use TryUpdateModel(). Here's the code:
<HttpPost()>
Function UpdateRoster() As JsonResult
Dim model As New Models.ViewModels.PlayerAdmin
Dim jsonString As String = Request.Form("json")
model = Deserialise(Of Models.ViewModels.PlayerAdmin)(jsonString)
For Each playerAdminPlayer As Models.ViewModels.PlayerAdminPlayer In model.Roster
Dim playerToTeam As New DAL.PlayersToTeam
Dim player As DAL.Player = PlayerAdminManager.GetPlayerById(playerAdminPlayer.PlayerId)
player.FirstName = playerAdminPlayer.FirstName
PlayerAdminManager.SaveChanges()
Next playerAdminPlayer
Dim playerAfter As DAL.Player = PlayerAdminManager.GetPlayerById(model.Roster.First.PlayerId)
Return Json(New With {.success = False, .message = playerAfter.FirstName})
End Function
Deserialise is a helper function that converts the incoming JSON string to a vb object.
Things seem to work fine in that player successfully loads from the DB and playerAdminPlayer is the correct object from the JSON string. However, when I call PlayerAdminManager.SaveChanges() (which just passes the call the db.SaveChanges() the result is always 0, even if there is a change (not sure if that is expected).
playerAfter was my attempt to see if changes were actually being saved. It seems to work correctly, in that playerAfter.FirstName is the newly updated first name.
PlayerAdminManager.GetPlayerById(integer) pulls from the DB, so I would think that, since changes are observed in playerAfter, that those changes were saved to the DB. However, when I reload the web page (which pulls from the DB), the old values are there.
Any ideas?
Here are some of the functions I mention:
Function GetPlayerById(ByVal Id As Integer) As DAL.Player
Return Container.Players.Where(Function(o) o.PlayerId = Id And o.IsVisible = True).SingleOrDefault
End Function
Sub SaveChanges()
Dim numberOfChanges As Integer = Container.SaveChanges()
Debug.WriteLine("No conflicts. " & numberOfChanges.ToString() & " updates saved.")
End Sub
EDIT
Container code:
Private _Container As DAL.LateralSportsContainer
Protected ReadOnly Property Container As DAL.LateralSportsContainer
Get
If _Container Is Nothing Then
Dim connStr As New System.Data.EntityClient.EntityConnectionStringBuilder
connStr.ProviderConnectionString = Web.Configuration.WebConfigurationManager.ConnectionStrings("ApplicationServices").ConnectionString
connStr.Metadata = "res://*/Lateral.csdl|res://*/Lateral.ssdl|res://*/Lateral.msl"
connStr.Provider = "System.Data.SqlClient"
_Container = New DAL.LateralSportsContainer(connStr.ConnectionString)
End If
Return _Container
End Get
End Property
Turns out I was using a non static (shared) Container. I had 2 Manager classes that both inherited from a BaseManager class were the Container was defined. I was executing the query command in one Manager and saving in another.
Doh!

Lucene.net: Separate building Index from Searching the Index

I created a website but i have a problem.
i want to build once an index und use it.
at the moment i have two functions "create a document an store it into the directory" and "searching"
when the user submit:
sub submit ()
create_doc()
search(text)
end sub
this works, but when i try this:
create_doc()
sub submit()
search(text)
end sub
it's like the directory has been deleted.
global:
Dim analyzer As StandardAnalyzer = New StandardAnalyzer()Dim directory As Directory = FSDirectory.GetDirectory("C:\[...]luceneindex", True)
Dim indexwriter As IndexWriter = New IndexWriter(directory, analyzer, True)
Sub create_doc()
Dim meindoc As New Document()
im feldbodytext As Field = New Field("bodytext", textstring[...]
meindoc.Add(feldbodytext)
indexwriter.AddDocument(meindoc)
indexwriter.Close()
end sub
Sub lucene_search(ByVal strSuchbegriff As String)
Dim parser As QueryParser = New QueryParser("bodytext", analyzer)
Dim query As Query = parser.Parse(strSuchbegriff)
Dim hits As Hits = searcher.Search(query)
[...]
end sub
Is there a possibility to store the index permanently?
could there be a problem init. the index writer gloabel, but close it local?
I think your problem is that each time you declare your IndexWriter, the index is being re-created and the contents of the index erased - this is because of the 3rd parameter being passed into the constructor (True):
Dim indexwriter As IndexWriter = New IndexWriter(directory, analyzer, True)
You should instead use False, to indicate that the existing contents of the index should remain unchanged:
Dim indexwriter As IndexWriter = New IndexWriter(directory, analyzer, False)
ahh, i think i've got it ;-)
the first time i create a index i have to use
Dim directory As Directory = FSDirectory.GetDirectory("C:\[...]\luceneindex", True)
Dim indexwriter As IndexWriter = New IndexWriter("C:\[...]luceneindex", analyzer, True)
and after indexing i have to use both with "False".
True everytimes creates an index?
thanks =)

Resources