Sharepoint 2010 EventReceiver for SPFolder adding - sharepoint-2010

I have a document library in which we have added a custom folder content type in order to keep the Folder Owner in a custom field.
Now I am asked to set the default value of the "Add new" form to the Parent Folder Owner. I have tried this code below but the event fires after saving the new Folder. Could anyone pls help me? How can I set this default value before opening the form?
public override void ItemAdding(SPItemEventProperties properties)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
try
{
this.EventFiringEnabled = false;
base.ItemAdding(properties);
if (properties.List.RootFolder.Name == "Documents")
{
SPWeb web = properties.List.ParentWeb;
SPList List = properties.List;
SPField fld = List.Fields["Folder Owner"];
SPUser usr = web.CurrentUser;
SPFieldUserValue curUser = new SPFieldUserValue();
curUser.LookupId = usr.ID;
SPFolder parentFolder = web.GetFolder(properties.AfterUrl.Substring(0,properties.AfterUrl.LastIndexOf("/")));
if (parentFolder.Item["Folder Owner"] == null)
{
fld.DefaultValue = curUser.ToString();
}
else
{
fld.DefaultValue = parentFolder.Item["Folder Owner"].ToString();
}
fld.Update();
List.Update();
}
}
catch (Exception)
{
}
finally
{
this.EventFiringEnabled = true;
}
});
}

Related

How to register the cache button in ASP.NET

I have created the cache button to clear all the .json files. Its perfectly working fine in local machine. But when i uploaded in server the cache button is not working.
After uploading in server, when i click on clear cache button the message is displaying as cache(.json files) has been cleared but actually all .json files is remain as it is.
Please help me in this isuue.
below is the code
#region Delete Cache Functions
public bool FnDeleteCache(string directoryName)
{
try
{
var di = new DirectoryInfo(rootDirectory + directoryName);
di.Attributes &= ~FileAttributes.ReadOnly;
if (CacheAttribute() == true)
{
System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(rootDirectory + directoryName);
foreach (System.IO.FileInfo file in directory.GetFiles())
{
if (file.Name != null)
file.Delete();
}
return true;
}
}
catch
{
return false;
}
return false;
}
public bool FnDeleteCache(string directoryName, string FileName)
{
var di = new DirectoryInfo(rootDirectory + directoryName);
di.Attributes &= ~FileAttributes.ReadOnly;
if (CacheAttribute() == true)
{
System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(rootDirectory + directoryName);
foreach (System.IO.FileInfo file in directory.GetFiles())
{
if (file.Name.Contains(FileName))
{
file.Delete();
return true;
}
}
}
return false;
}
#endregion
Thank you.

The security validation for this page is invalid error trying to add sharepoint approval workflow to List in ListAdded eventreceiver

What I am trying to do is to attach the OOTB sharepoint workflow [Approval Sharepoint - 2010] to each and every document library that ever gets created. To accomplish this I created a List Added event reciever and put this code in it -
public override void ListAdded(SPListEventProperties properties)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPUtility.ValidateFormDigest();
using (SPSite site = new SPSite(properties.SiteId))
{
using (SPWeb web = site.OpenWeb())
{
try
{
base.ListAdded(properties);
if (currentList is SPDocumentLibrary)
{
SPDocumentLibrary docLib = (SPDocumentLibrary)properties.List;
//workflows need a tasks and history list. Here we assume they exist
SPList taskList = web.Lists["Tasks"];
SPList historyList = web.Lists["Workflow History"];
//loop through the workfows in the web and grab the one we want by name
SPWorkflowTemplate wfTemp = null;
foreach (SPWorkflowTemplate wt in web.WorkflowTemplates)
{
if (wt.Name == "Approval - SharePoint 2010")
{
wfTemp = wt;
Common.AddToLog(web, "Found " + wt.Name + " in current web " +
web.Url, false);
break;
}
}
//Now add the workflow to the doc library
SPWorkflowAssociation workFlow = SPWorkflowAssociation.CreateListAssociation(wfTemp, wfTemp.Name, taskList, historyList);
workFlow.AllowManual = true;
workFlow.AutoStartChange = false;
workFlow.AutoStartCreate = true;
workFlow.AssociationData = null;
web.AllowUnsafeUpdates = true;
web.ValidateFormDigest();
docLib.WorkflowAssociations.Add(workFlow);
docLib.EnableModeration = true;
docLib.Update();
web.Update();
web.AllowUnsafeUpdates = false;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
web.AllowUnsafeUpdates = false;
}
}
}
});
}
I am getting this error-
The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.
at this line
docLib.WorkflowAssociations.Add(workFlow);
Any any have any suggestions please ? Thanks for your feedback.
Why do you need "SPUtility.ValidateFormDigest()" at all?
Your code was running in an event receiver, not on a form or aspx page, there is nothing to validate.
Could you remove this line and try again?
I believe updating this code block:
web.AllowUnsafeUpdates = true;
web.ValidateFormDigest();
docLib.WorkflowAssociations.Add(workFlow);
docLib.EnableModeration = true;
docLib.Update();
web.Update();
web.AllowUnsafeUpdates = false;
and replacing it with:
web.Site.WebApplication.FormDigestSettings.Enabled = false;
docLib.WorkflowAssociations.Add(workFlow);
docLib.EnableModeration = true;
docLib.Update();
web.Update();
web.Site.WebApplication.FormDigestSettings.Enabled = true;
Let me know if this works for you or if you still encounter the same error.

How to search file from a document library using client object model sharepoint 2010

At the moment i am struggling to programatically enable the search functionality to search file from a document library using client object model sharepoint 2010,
Can you please help me with the code
Thanks
Kajal
List list = clientcontext.Web.Lists.GetByTitle(ListName);
clientcontext.Load(list);
clientcontext.ExecuteQuery();
FileCollection files = list.RootFolder.Files;
clientcontext.Load(files);
clientcontext.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.File file in files)
{
if(file.Name == txtSearch)
{
// your logic
}
}
private string searchDoc(string name)
{
try
{
ClientContext clientContext = new ClientContext("YOUR SERVER");
SP.List oList = clientContext.Web.Lists.GetByTitle("YOUR DOC");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = #"<View Scope='Recursive'/>";
Microsoft.SharePoint.Client.ListItemCollection collListItem1 = oList.GetItems(camlQuery);
clientContext.Load(collListItem1, items => items.Include(item => item.DisplayName, item => item["Comments"]));
clientContext.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem oListItem1 in collListItem1)
{
if (oListItem1.DisplayName == name)
{
XXXXXXXXXXXXXX
}
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message, "Exception");
}
}
Recursive's search!

Create multiple sharepoint list items based multiple uploaded files SP2010

I would like to create sharepoint list items based on selected multiple files from local drive. After uploading selected multiple files list should contains new list items (title is file name) with attachments (one attachment/uploaded file).
Ok I extended my custom webpart (with dynatree) on that list using http://www.plupload.com/ and creating page for saving attachments.
public partial class ImportMultipleFilesAsListItems : LayoutsPageBase
{
protected void Page_Load(object sender, EventArgs e)
{
//request form parameters comes from plupload
int parentFolderKey = int.Parse(Request.Form["key"]);
var file = Request.Files[0];
SPList list = SPContext.Current.Web.GetList(Request.Form["listUrl"]);
SPListItem folderItem = list.GetItemById(parentFolderKey);
if (folderItem != null)
{
string parentFolder = null;
if (folderItem.Folder != null)
{
parentFolder = folderItem.Folder.Url;
}
else
{
int slashIndx = folderItem.Url.LastIndexOf('/');
parentFolder = folderItem.Url.Substring(0, slashIndx);
}
SPListItem childFile = list.AddItem(parentFolder, SPFileSystemObjectType.File);
childFile["Title"] = file.FileName;
childFile["IsFolder"] = 0;
childFile["DocParentId"] = parentFolderKey;
childFile.UpdateOverwriteVersion();
byte[] data = new byte[file.ContentLength];
file.InputStream.Read(data, 0, file.ContentLength);
childFile.Attachments.AddNow(file.FileName, data);
}
}
}
$(function () {
var listInfo = new Object();
listInfo.key = null;
listInfo.listUrl = ctx.listUrlDir;
listInfo.__REQUESTDIGEST = $('#__REQUESTDIGEST').val();
$("#uploader").pluploadQueue({
// General settings
runtimes: 'browserplus,html5,html4',
url: $('#uploadMultipleFilesUrl').val(),
max_file_size: '50mb',
chunk_size: '1mb',
multipart_params: listInfo,
rename: true
});
// Client side form validation
$('form').submit(function (e) {
var uploader = $('#uploader').pluploadQueue();
// Files in queue upload them first
if (uploader.files.length > 0) {
// When all files are uploaded submit form
uploader.bind('StateChanged', function () {
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
$('form')[0].submit();
}
});
uploader.start();
} else {
alert('You must queue at least one file.');
}
return false;
});
$("#uploader").hide();
});

Set the value of custom webpart property in c#

How to set the value of custom webpart property Programatically in C#.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite SiteCollection = new SPSite(mySiteGuid))
{
SPWeb myWeb = SiteCollection.OpenWeb(myWebGuid);
myWeb .AllowUnsafeUpdates = true;
Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager mgr = null;
mgr = myWeb.GetLimitedWebPartManager ("default.aspx",System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
foreach (System.Web.UI.WebControls.WebParts.WebPart myWebPart in mgr.WebParts)
{
if (myWebPart.Title == "Other Webpart Name")
{
myWebPart.Visible = ! myWebPart.Visible;
myWeb.Update();
break;
}
}
}
});
I have a custom property in the webpart of type string to get the input from the user.
I wanted to updated the value of the property from c#.
Is there any way to set the value?
TIA
Try myWebPart.Update() instead of myWeb.Update().
Maybe it's a bit late for the answer, but here i let a piece of code i used for this.
var webCollection = new SPSite("http://mySharePointSite").AllWebs;
foreach (SPWeb web in webCollection)
{
var landingPageReference = #"/Pages/default.aspx";
var page = web.GetFile(landingPageReference);
if (!page.Exists)
continue;
page.CheckOut();
var spLimitedWebPartManager = web.GetLimitedWebPartManager(page.ServerRelativeUrl, PersonalizationScope.Shared);
foreach (WebPart webPartItem in spLimitedWebPartManager.WebParts)
{
if (webPartItem.Title.Equals("myWebPartTitle"))
{
// Specify Properties to change here
webPartItem.ChromeType = PartChromeType.Default;
webPartItem.Description = "AGAIN CHANGED";
// Save made changes
spLimitedWebPartManager.SaveChanges(webPartItem);
break;
}
}
page.CheckIn("Add Comment if desired");
page.Publish("Add Comment if desired");
web.Update();
web.Dispose();
}