How to search file from a document library using client object model sharepoint 2010 - 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!

Related

Generating a new PDF using an existing PDF Document

I'm trying to generate a new PDF document using an existing document as a base on a UWP application. I want to import the pages from the existing document, create annotations with information received from the application level and create a new PDF document combining both.
But it just creates a PDF document with the same number of pages but they are empty. When I analyze the created document the content is not available even though I imported it. But the created annotations are available in the document.
This is the file creation logic.
public async Task EmbedCurrentAnnotationsInStore(PdfDocument document)
{
if (document is null || document.IsDisposed)
return;
try
{
var file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("embedded_doc.pdf", CreationCollisionOption.ReplaceExisting);
PdfDocument newDocument = new PdfDocument();
PDFium.FPDF_ImportPages(newDocument.Handle, document.Handle, 0);
foreach (var page in newDocument.Pages)
await annotationConvertor.ConvertToFPDFAnnotations(page, annotationAdapter.GetAnnotations()
.Where(x =>
x.Status != AnnotationStatus.Removed &&
x.PageIndex == page.Index)
.OrderBy(x => x.AnnotationIndex));
using (var stream = await file.OpenStreamForWriteAsync())
{
newDocument.Save(stream, SaveFlags.None, document.FileVersion);
await stream.FlushAsync();
newDocument.Close();
}
}
catch (Exception ex)
{
var err = PDFium.FPDF_GetLastError();
throw ex;
}
}
ConvertToFPDFAnnotations()
public async Task ConvertToFPDFAnnotations(PdfPage page, IEnumerable<BaseAnnotation> annotations)
{
foreach (var annotation in annotations)
{
switch (annotation.AnnotationType)
{
case FPDF_ANNOTATION_SUBTYPE.FPDF_ANNOT_HIGHLIGHT:
await EmbedFPDFAnnotationFromHighlightAnnotation(page, annotation.AsHighlightAnnotation());
break;
default:
break;
}
}
}
EmbedFPDFAnnotationFromHighlightAnnotation()
private async Task EmbedFPDFAnnotationFromHighlightAnnotation(PdfPage page, HighlightAnnotation annotation)
{
if (page is null || page.IsDisposed)
return;
var fdfAnnotation = page.CreateAnnot(page, FPDF_ANNOTATION_SUBTYPE.FPDF_ANNOT_HIGHLIGHT);
fdfAnnotation.SetColor(fdfAnnotation.Handle, FPDFANNOT_COLORTYPE.FPDFANNOT_COLORTYPE_Color,
(uint)annotation.Color.R,
(uint)annotation.Color.G,
(uint)annotation.Color.B,
(uint)annotation.Color.A);
fdfAnnotation.SetStringValue(fdfAnnotation.Handle, "CA", annotation.Color.A.ToString());
foreach (var quadpoint in annotation.Quadpoints)
{
var refQuadpoint = quadpoint;
fdfAnnotation.AppendAttachmentPoints(fdfAnnotation.Handle, ref refQuadpoint);
}
fdfAnnotation.SetStringValue(fdfAnnotation.Handle, "Index", annotation.StartIndex.ToString());
fdfAnnotation.SetStringValue(fdfAnnotation.Handle, "Count", annotation.CharCount.ToString());
var rect = new FS_RECTF();
rect = annotation.Rect;
fdfAnnotation.SetRect(fdfAnnotation.Handle, ref rect);
fdfAnnotation.SetStringValue(fdfAnnotation.Handle, "CreationDate", annotation.CreationDate);
fdfAnnotation.SetStringValue(fdfAnnotation.Handle, "M", annotation.ModifiedDate);
if (string.IsNullOrEmpty(annotation.Contents))
fdfAnnotation.SetStringValue(fdfAnnotation.Handle, "Contents", annotation.Contents);
fdfAnnotation.CloseAnnot(fdfAnnotation.Handle);
}
I used this (FPDF_ImportPages) method to import the pages from the existing document.
Could someone help me with the issue I'm facing? Maybe I'm missing something here.
Thanks.

Sharepoint 2010 EventReceiver for SPFolder adding

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

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

Get custom templates programmatically sharepoint 2010

To get standard templates I do:
private void getTemplates()
{
string server = serverURL();
using (SPSite siteCollection = new SPSite(server))
{
SPWebTemplateCollection Templates = siteCollection.GetWebTemplates(1033);
foreach (SPWebTemplate template in Templates)
{
ddlSiteTemplate.Items.Add(new ListItem(template.Title, template.Name));
}
}
}
I thought I could do:
private void getTemplates()
{
string server = serverURL();
using (SPSite siteCollection = new SPSite(server))
{
SPWebTemplateCollection Templates = siteCollection.GetCustomWebTemplates(1033);
foreach (SPCustomWebTemplate template in Templates)
{
ddlSiteTemplate.Items.Add(new ListItem(template.Title, template.Name));
}
}
}
To get the custom templates but the dropdown is empty, what am I doing wrong here?
Thanks in advance.
Edit: the templates are activated in the solutions gallery.
I got it to work with
private void getTemplates()
{
string server = serverURL();
using (SPSite siteCollection = new SPSite(server))
{
SPWebTemplateCollection Templates = siteCollection.GetAvailableWebTemplates(1033);
foreach (SPCustomWebTemplate template in Templates)
{
//this gives me all templates, both standard and custom so I filter by name
if(template.name.ToUpper().StartsWith("CUSTOM"))
{
ddlSiteTemplate.Items.Add(new ListItem(template.Title, template.Name));
}
}
}
}
SPSite does not contain a GetAvailableWebTemplates method. For those who would like to use the code use the one below. So I have added this line of code:
using(SPWeb web = siteCollection.OpenWeb())
{
SPWebTemplateCollection Templates = web.GetAvailableWebTemplates(1033);
Full code:
private void getTemplates()
{
string server = serverURL();
using (SPSite siteCollection = new SPSite(server))
{
using(SPWeb web = siteCollection.OpenWeb())
{
SPWebTemplateCollection Templates = web.GetAvailableWebTemplates(1033);
foreach (SPCustomWebTemplate template in Templates)
{
//this gives me all templates, both standard and custom so I filter by name
if(template.name.ToUpper().StartsWith("CUSTOM"))
{
ddlSiteTemplate.Items.Add(new ListItem(template.Title, template.Name));
}
}
}
}
}