Thursday 25 January 2018
Tuesday 23 January 2018
How to set any SP.Field Value with REST API (Javascript) in Sharepoint 2013 to New SP.Listitem
Here is an example on how to create a new SP.ListItem using java script in SharePoint 2013 and setting most of the available fields in code using REST API.
$(document).ready(function() {
var digestValue = $("#__REQUESTDIGEST").val();
var url = "/_api/Web/Lists/GetByTitle('TestList')/Items";
$("#clickBtn").on('click', function(e) {
e.preventDefault();
addNewItem(url);
});
function addNewItem(url, data) {
var data = {
__metadata: {
type: 'SP.Data.TestListListItem'
},
Title: 'Some title',
PetkaMultiText: 'Some multiline text. <bold>Can Be HTML</bold>',
PetkaChoiceDrop: 'Choice #2',
PetkaChoiceMulti: {
__metadata: {
type: "Collection(Edm.String)"
},
results: [
"Choice #1",
"Choice #2"
]
},
PetkaPersonSingleId: 19,
PetkaPersonMultiId: {
__metadata: {
type: "Collection(Edm.Int32)"
},
results: [
1,
18
]
},
PetkaManagedSingle: {
"__metadata": {
"type": "SP.Taxonomy.TaxonomyFieldValue"
},
"Label": "3",
"TermGuid": "08a8397f-2165-47cf-b185-37f0c40777e5",
"WssId": 3
},
// Not supported at this time. If you know how to make it work, let me know.
//PetkaManagedMulti: {
// __metadata: {
// type: "Collection(SP.Taxonomy.TaxonomyFieldValue)"
// },
// results: [{
// "Label": "In the Press",
// "TermGuid": "02832069-36a5-4d2b-af89-0e5378fc7cef",
// "WssId": 1
// }, {
// "Label": "News & Announcements",
// "TermGuid": "6a12f6bc-1174-4cea-a48a-cc6f4f7040d3",
// "WssId": 2
// }]
//},
PetkaLookupId: 2,
PetkaLookupMultiId: {
__metadata: {
type: "Collection(Edm.Int32)"
},
results: [
1,
2
]
},
PetkaNumber: 1,
PetkaCurrency: 34,
PetkaDateTime: new Date().toISOString(),
PetkaYesNo: true,
PetkaHyperLink: {
__metadata: {
type: "SP.FieldUrlValue"
},
Url: "http://google.com",
Description: "Google Url Description"
}
};
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + url,
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": digestValue,
"content-Type": "application/json;odata=verbose"
},
data: JSON.stringify(data),
success: function(data) {
console.log(data);
},
error: function(error) {
alert(JSON.stringify(error));
}
});
}
});
Configuring SharePoint 2013 Site Navigation Programmatically using Feature – UI Walkthrough
I found this great post about setting SharePoint 2013 Site Navigation Programmatically. Just want to keep it for my future reference.
Just in case if link goes dead, here is the screenshot.
How to set any SP.Field Value with JSOM (Javascript) in Sharepoint 2013 to New SP.Listitem
Here is an example on how to create a new SP.ListItem using java script in SharePoint 2013 and setting most of the available fields in code.
function createListItem() {
var clientContext = new SP.ClientContext(_spPageContextInfo.siteAbsoluteUrl);
var oList = clientContext.get_web().get_lists().getByTitle('TestList');
var itemCreateInfo = new SP.ListItemCreationInformation();
this.oListItem = oList.addItem(itemCreateInfo);
//Single line of text
oListItem.set_item('Title', 'My New Item!');
//Single Choice
oListItem.set_item('PetkaChoiceDrop', 'Enter Choice #1');
//Multi Choice
var petkaChoiceMultiArray = new Array("Enter Choice #1","Enter Choice #2");
oListItem.set_item('PetkaChoiceMulti', petkaChoiceMultiArray);
//Single Lookup
var PetkaLookupSingle = new SP.FieldLookupValue();
PetkaLookupSingle.set_lookupId(2);
oListItem.set_item('PetkaLookup', PetkaLookupSingle);
//Multi Lookup
var lookupsIds = [1,2];
var lookups = [];
for (var ii in lookupsIds) {
var lookupValue = new SP.FieldLookupValue();
lookupValue.set_lookupId(lookupsIds[ii]);
lookups.push(lookupValue);
}
oListItem.set_item('PetkaLookupMulti', lookups);
//Yes=1 / No=0
oListItem.set_item('PetkaYesNo', 1);
// Single Person
var singleUser = SP.FieldUserValue.fromUser('Peter Dotsenko');
oListItem.set_item('PetkaPersonSingle', singleUser);
//Multi Person
var petkaUserMultiArray = new Array("peterd@domain.com","Peter Dotsenko","domain\\peterd");
var lookups = [];
for (var ii in petkaUserMultiArray) {
var lookupValue = SP.FieldUserValue.fromUser(petkaUserMultiArray[ii]);
lookups.push(lookupValue);
}
oListItem.set_item('PetkaPersonMulti', lookups);
//Managed Multi
var field = oList.get_fields().getByInternalNameOrTitle("PetkaManagedMulti");
var taxField = clientContext.castTo(field, SP.Taxonomy.TaxonomyField);
var terms = new SP.Taxonomy.TaxonomyFieldValueCollection(clientContext,getMultiTax(),taxField);
taxField.setFieldValueByValueCollection(oListItem, terms);
//Managed Single
var field = oList.get_fields().getByInternalNameOrTitle("PetkaManagedSingle");
var taxField = clientContext.castTo(field, SP.Taxonomy.TaxonomyField);
var taxonomySingle = new SP.Taxonomy.TaxonomyFieldValue();
taxonomySingle.set_label("Mamo");
taxonomySingle.set_termGuid("10d05b55-6ae5-413b-9fe6-ff11b9b5767c");
taxonomySingle.set_wssId(-1);
taxField.setFieldValueByValue(oListItem, taxonomySingle);
//Hyperlink or Picture
var hyperLink = new SP.FieldUrlValue();
hyperLink.set_url("http://cnn.com");
hyperLink.set_description("CNN");
oListItem.set_item('PetkaHyperLink', hyperLink);
//Currency
oListItem.set_item('PetkaCurrency', '100');
//DateTime
oListItem.set_item('PetkaDateTime', '3/14/2014');
//MultiLine text
oListItem.set_item('PetkaMultiText', '<p><strong>Hello!</strong></p>');
oListItem.update();
clientContext.load(oListItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}
function getMultiTax(){
var terms = new Array();
terms.push("-1;#Mamo|10d05b55-6ae5-413b-9fe6-ff11b9b5767c");
terms.push("-1;#Popo|178888b0-7942-45bb-b3f1-2f38d476e3db");
return terms.join(";#");
}
function onQuerySucceeded() {
SP.UI.Notify.addNotification('Item created: ' + oListItem.get_id());
}
function onQueryFailed(sender, args) {
console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
Thursday 18 January 2018
MS files to pdf conversion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Collections;
using msExcel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Core;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Collections;
using msExcel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Core;
namespace ConsoleApplication1
{
{
public class Program
{
public static object missing = System.Reflection.Missing.Value;
private static string sourcefolder;
private static string destinationfile;
private static IList fileList = new ArrayList();
public string SourceFolder
{
get { return sourcefolder; }
set { sourcefolder = value; }
}
public string DestinationFile
{
get { return destinationfile; }
set { destinationfile = value; }
}
{
public static object missing = System.Reflection.Missing.Value;
private static string sourcefolder;
private static string destinationfile;
private static IList fileList = new ArrayList();
public string SourceFolder
{
get { return sourcefolder; }
set { sourcefolder = value; }
}
public string DestinationFile
{
get { return destinationfile; }
set { destinationfile = value; }
}
public static void Main(string[] args)
{
{
string [] array1=Directory.GetFiles(“D:\\Test”);
for(int i=0;i<array1.Length;i++)
{
if(array1[i].Contains(“.docx”))
{
ConvertWordToPdf(array1[i],array1[i].Substring(array1[i].LastIndexOf(“\\”)+1));
for(int i=0;i<array1.Length;i++)
{
if(array1[i].Contains(“.docx”))
{
ConvertWordToPdf(array1[i],array1[i].Substring(array1[i].LastIndexOf(“\\”)+1));
}
else if (array1[i].Contains(“.xlsx”))
{
ConvertExcelToPdf(array1[i], array1[i].Substring(0, array1[i].LastIndexOf(“\\”)));
else if (array1[i].Contains(“.xlsx”))
{
ConvertExcelToPdf(array1[i], array1[i].Substring(0, array1[i].LastIndexOf(“\\”)));
}
else if (array1[i].Contains(“.pptx”))
{
ConvertPPTXToPDF(array1[i]);
}
}
Execute();
else if (array1[i].Contains(“.pptx”))
{
ConvertPPTXToPDF(array1[i]);
}
}
Execute();
}
public static void AddFile(string pathnname)
{
fileList.Add(pathnname);
public static void AddFile(string pathnname)
{
fileList.Add(pathnname);
}
public static void Execute()
{
MergeDocs();
}
public static void Execute()
{
MergeDocs();
}
public static void MergeDocs()
{
//Step 1: Create a Docuement-Object
iTextSharp.text.Document document = new iTextSharp.text.Document();
try
{
//Step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(“D:\\Test1\\Final.pdf”, FileMode.Create));
//Step 3: Open the document
document.Open();
PdfContentByte cb = writer.DirectContent; PdfImportedPage page;
int n = 0;
int rotation = 0;
string[] array2= Directory.GetFiles(“D:\\Test”);
for(int i=0;i<array2.Length;i++)
{
if(array2[i].Contains(“.pdf”))
{
AddFile(array2[i]);
}
}
{
//Step 1: Create a Docuement-Object
iTextSharp.text.Document document = new iTextSharp.text.Document();
try
{
//Step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(“D:\\Test1\\Final.pdf”, FileMode.Create));
//Step 3: Open the document
document.Open();
PdfContentByte cb = writer.DirectContent; PdfImportedPage page;
int n = 0;
int rotation = 0;
string[] array2= Directory.GetFiles(“D:\\Test”);
for(int i=0;i<array2.Length;i++)
{
if(array2[i].Contains(“.pdf”))
{
AddFile(array2[i]);
}
}
//Loops for each file that has been listed
foreach (string filename in fileList)
{
foreach (string filename in fileList)
{
//The current file path
string filePath = sourcefolder + filename;
// we create a reader for the document
PdfReader reader = new PdfReader(filePath);
//Gets the number of pages to process
n = reader.NumberOfPages; int i = 0;
while (i < n)
{
i++; document.SetPageSize(reader.GetPageSizeWithRotation(1));
document.NewPage();
//Insert to Destination on the first page
if (i == 1)
{
Chunk fileRef = new Chunk(” “);
fileRef.SetLocalDestination(filename); document.Add(fileRef);
}
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{ cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height); }
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
string filePath = sourcefolder + filename;
// we create a reader for the document
PdfReader reader = new PdfReader(filePath);
//Gets the number of pages to process
n = reader.NumberOfPages; int i = 0;
while (i < n)
{
i++; document.SetPageSize(reader.GetPageSizeWithRotation(1));
document.NewPage();
//Insert to Destination on the first page
if (i == 1)
{
Chunk fileRef = new Chunk(” “);
fileRef.SetLocalDestination(filename); document.Add(fileRef);
}
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{ cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height); }
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
}
}
catch (Exception e) { throw e; }
finally { document.Close(); }
}
}
catch (Exception e) { throw e; }
finally { document.Close(); }
}
public static void ConvertExcelToPdf(string excelFileIn, string pdfFileOut)
{
msExcel.Application excel = new msExcel.Application();
try
{
excel.Visible = false;
excel.ScreenUpdating = false;
excel.DisplayAlerts = false;
{
msExcel.Application excel = new msExcel.Application();
try
{
excel.Visible = false;
excel.ScreenUpdating = false;
excel.DisplayAlerts = false;
FileInfo excelFile = new FileInfo(excelFileIn);
string filename = excelFile.FullName;
msExcel.Workbook wbk = excel.Workbooks.Open(filename, missing,
missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing,
missing, missing, missing);
wbk.Activate();
missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing,
missing, missing, missing);
wbk.Activate();
object outputFileName = wbk.FullName.Replace(“.xslx”, “.pdf”); ;
msExcel.XlFixedFormatType fileFormat = msExcel.XlFixedFormatType.xlTypePDF;
msExcel.XlFixedFormatType fileFormat = msExcel.XlFixedFormatType.xlTypePDF;
// Save document into PDF Format
wbk.ExportAsFixedFormat(fileFormat, outputFileName,
missing, missing, missing,
missing, missing, missing,
missing);
wbk.ExportAsFixedFormat(fileFormat, outputFileName,
missing, missing, missing,
missing, missing, missing,
missing);
object saveChanges = msExcel.XlSaveAction.xlDoNotSaveChanges;
((msExcel._Workbook)wbk).Close(saveChanges, missing, missing);
wbk = null;
}
catch (Exception e)
{
}
finally
{
((msExcel._Application)excel).Quit();
excel = null;
}
}
((msExcel._Workbook)wbk).Close(saveChanges, missing, missing);
wbk = null;
}
catch (Exception e)
{
}
finally
{
((msExcel._Application)excel).Quit();
excel = null;
}
}
#region Converting word to PDF
// C# doesn’t have optional arguments so we’ll need a dummy value
// object oMissing = System.Reflection.Missing.Value;
public static void ConvertWordToPdf(String FilePath,String FileName)
{
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
try
{
// object oMissing = System.Reflection.Missing.Value;
public static void ConvertWordToPdf(String FilePath,String FileName)
{
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
try
{
// Get a Word file
FileInfo wordFile = new FileInfo((FileName));
FileInfo wordFile = new FileInfo((FileName));
word.Visible = false;
word.ScreenUpdating = false;
word.ScreenUpdating = false;
// Cast as Object for word Open method
Object filename = (Object)FilePath;
//object filename = (Object)wordFile.FullName;
Object filename = (Object)FilePath;
//object filename = (Object)wordFile.FullName;
// Use the dummy value as a placeholder for optional arguments
Microsoft.Office.Interop.Word.Document doc = word.Documents.Open(ref filename, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);
doc.Activate();
Microsoft.Office.Interop.Word.Document doc = word.Documents.Open(ref filename, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);
doc.Activate();
object outputFileName = FilePath.Replace(“.docx”, “.pdf”);
object fileFormat = WdSaveFormat.wdFormatPDF;
object fileFormat = WdSaveFormat.wdFormatPDF;
// Save document into PDF Format
doc.SaveAs(ref outputFileName,
ref fileFormat, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);
doc.SaveAs(ref outputFileName,
ref fileFormat, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);
// Close the Word document, but leave the Word application open.
// doc has to be cast to type _Document so that it will find the
// correct Close method.
object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
((_Document)doc).Close(ref saveChanges, ref missing, ref missing);
doc = null;
// doc has to be cast to type _Document so that it will find the
// correct Close method.
object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
((_Document)doc).Close(ref saveChanges, ref missing, ref missing);
doc = null;
// word has to be cast to type _Application so that it will find
// the correct Quit method.
((Microsoft.Office.Interop.Word._Application)word).Quit(ref missing, ref missing, ref missing);
word = null;
}
catch (Exception e)
{
}
// the correct Quit method.
((Microsoft.Office.Interop.Word._Application)word).Quit(ref missing, ref missing, ref missing);
word = null;
}
catch (Exception e)
{
}
#endregion
}
}
public static void ConvertPPTXToPDF(string FileName)
{
Microsoft.Office.Interop.PowerPoint.Application app = new Microsoft.Office.Interop.PowerPoint.Application();
string sourcePptx = FileName;
string targetPpt = sourcePptx.Replace(“.pptx”, “.pdf”);
object missing = Type.Missing;
Microsoft.Office.Interop.PowerPoint.Presentation pptx = app.Presentations.Open(sourcePptx, MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoFalse);
pptx.SaveAs(targetPpt, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF, MsoTriState.msoTrue);
app.Quit();
}
{
Microsoft.Office.Interop.PowerPoint.Application app = new Microsoft.Office.Interop.PowerPoint.Application();
string sourcePptx = FileName;
string targetPpt = sourcePptx.Replace(“.pptx”, “.pdf”);
object missing = Type.Missing;
Microsoft.Office.Interop.PowerPoint.Presentation pptx = app.Presentations.Open(sourcePptx, MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoFalse);
pptx.SaveAs(targetPpt, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF, MsoTriState.msoTrue);
app.Quit();
}
}
}
}
Tuesday 16 January 2018
LIST OF INTERNAL NAMES FOR SHAREPOINT FIELDS
TITLE | INTERNAL NAME |
---|---|
Approval Status | _ModerationStatus |
Approver Comments | _ModerationComments |
Check In Comment | _CheckinComment |
Checked Out To | CheckoutUser |
Checked Out To | CheckedOutTitle |
Checked Out To | LinkCheckedOutTitle |
Content Type | ContentType |
Content Type ID | ContentTypeId |
Copy Source | _CopySource |
Created | Created |
Created | Created_x0020_Date |
Created By | Author |
Document Created By | Created_x0020_By |
Document Modified By | Modified_x0020_By |
Edit | Edit |
Edit Menu Table End | _EditMenuTableEnd |
Edit Menu Table Start | _EditMenuTableStart |
Effective Permissions Mask | PermMask |
Encoded Absolute URL | EncodedAbsUrl |
File Size | File_x0020_Size |
File Size | FileSizeDisplay |
File Type | File_x0020_Type |
GUID | GUID |
Has Copy Destinations | _HasCopyDestinations |
Html File Link | xd_ProgID |
HTML File Type | HTML_x0020_File_x0020_Type |
ID | ID |
ID of the User who has the item Checked Out | CheckedOutUserId |
Instance ID | InstanceID |
Is Checked out to local | IsCheckedoutToLocal |
Is Current Version | _IsCurrentVersion |
Is Signed | xd_Signature |
Item Type | FSObjType |
Level | _Level |
Merge | Combine |
Modified | Modified |
Modified | Last_x0020_Modified |
Modified By | Editor |
Name | FileLeafRef |
Name | LinkFilenameNoMenu |
Name | LinkFilename |
Name | BaseName |
Order | Order |
owshiddenversion | owshiddenversion |
Path | FileDirRef |
ProgId | ProgId |
Property Bag | MetaInfo |
Relink | RepairDocument |
ScopeId | ScopeId |
Select | SelectTitle |
Select | SelectFilename |
Server Relative URL | ServerUrl |
Shared File Index | _SharedFileIndex |
Source Name (Converted Document) | ParentLeafName |
Source Url | _SourceUrl |
Source Version (Converted Document) | ParentVersionString |
Template Link | TemplateUrl |
Title | Title |
Type | DocIcon |
UI Version | _UIVersion |
Unique Id | UniqueId |
URL Path | FileRef |
Version | _UIVersionString |
Virus Status | VirusStatus |
Workflow Instance ID | WorkflowInstanceID |
Workflow Version | WorkflowVersion |
Subscribe to:
Posts (Atom)
Featured post
Data connections in Infopath forms
https://www.qdoscc.com/blog/how-automatically-retrieve-current-username-infopath-sharepoint-list-form
Popular Posts
-
function setLoginName() { debugger; var loginName = _spPageContextInfo.userLoginName; var peoplePickerDiv = $("[id$='Cl...
-
Named Items Named Items is a feature of Excel which allows Naming few cell area. This makes us easier to integrate the Excel workbook with...
-
Document sets – the hidden gem of SharePoint Posted on March 1, 2017 | Document Management The classical joke in SharePoint is tha...