Wednesday, November 19, 2014

Reading JSON data from a webservice


Create a class for the JSON data

public class JSONData
{
public string id{ get; set; }
public string name{ get; set; }
}

Use this to consume the webservice

string requestURL = "Webservice URL";
CredentialCache credCache = new CredentialCache();
credCache.Add(new Uri(requestURL), "NTLM", CredentialCache.DefaultNetworkCredentials);
HttpWebRequest spRequest = (HttpWebRequest)HttpWebRequest.Create(requestURL);
spRequest.Credentials = credCache;
spRequest.UserAgent = "Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0";
spRequest.Method = "GET";
spRequest.Accept = "application/json;odata=verbose";
HttpWebResponse endpointResponse = (HttpWebResponse)spRequest.GetResponse();
if (endpointResponse.StatusCode == HttpStatusCode.OK)
{
                using (endpointResponse)
{
using (var reader = new StreamReader(endpointResponse.GetResponseStream()))
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
try
{
string jSON = reader.ReadToEnd();
JSONData data = new JavaScriptSerializer().Deserialize<JSONData>(jSON);
string strId = data.id;
string strName=data.name;
}
catch (Exception ex)
{
throw ex;
}
}
}
}

Monday, November 3, 2014

Check item exists based on a column value using REST API

<script type="text/javascript">
function PreSaveAction() {
var result = false;
var value=$("select[title=MyColumn] option:selected").text();
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getbytitle('MyList')/Items?$select=LinkTitle,MyColumn/Title&$expand=MyColumn&$filter=MyColumn/Title eq '" + value;
$.ajax
({
url: requestUri,
type: "GET",
cache: true,
async: false,
headers:{
"ACCEPT": "application/json;odata=verbose"
        },
success: function (data) {
if($(data.d.results).length == 0)
result = true;
else
alert("Retry!!!");
},
error: function () {
}
});
return result;
}
</script>

Tuesday, October 21, 2014

Logging error in event viewer

        void LogError(TraceSeverity Level, Exception exception)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                string errorMessage = exception.Message + "--" + exception.StackTrace;
                SPDiagnosticsService.Local.WriteTrace(0,
                    new SPDiagnosticsCategory("Error Log", Level, EventSeverity.Error), TraceSeverity.Unexpected, errorMessage, null);
            });
        }

Friday, October 10, 2014

Change text in a word file using OpenXML

using (SPSite oSite = new SPSite("SP SITE URL"))
{
    using (SPWeb oWeb = oSite.OpenWeb())
    {
        SPFile oFile = oWeb.GetFile("FILE TEMPLATE URL");
        byte[] byteArray = oFile.OpenBinary();
        using (MemoryStream memStr = new MemoryStream())
        {
            memStr.Write(byteArray, 0, byteArray.Length);
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(memStr, true))
            {
                Table table = wordDoc.MainDocumentPart.Document.Body.Elements<Table>().First();//find first table
                TableRow row = table.Elements<TableRow>().ElementAt(7);//get the 7th row
                TableCell cell = row.Elements<TableCell>().ElementAt(2);//get the 2nd cell
                Paragraph p = cell.Elements<Paragraph>().First();//1st paragraph
                Run r = p.Elements<Run>().First();//1st run
                Text t = r.Elements<Text>().First();//get the text
                t.Text = "TEXT TO BE UPDATED";//set the text
            }
        }
    }
}

Wednesday, September 10, 2014

Clearing designer cache

Close SPD and then remove all files from the following folders

%APPDATA%\Microsoft\Web Server Extensions\Cache

%USERPROFILE%\AppData\Local\Microsoft\WebsiteCache



Thursday, August 7, 2014

Get related item id from a workflow task list

​​​​<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
function retrieveListItems() {
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('Workflow Tasks');
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query><Where></Where></Query><RowLimit>10</RowLimit></View>');
    this.collListItem = oList.getItems(camlQuery);
    clientContext.load(collListItem);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));            
}

function onQuerySucceeded(sender, args) {
    var listItemEnumerator = collListItem.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        oListItem = listItemEnumerator.get_current();
        obj=JSON.parse(oListItem.get_item('RelatedItems'));
        alert(obj[0].ItemId);
    }
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>​​​​​​​​​​​​​​​​​​​​​​​​​​

Friday, July 25, 2014

Popup dialog in SharePoint using javascript

function popupDialog(){
var options = SP.UI.$create_DialogOptions();
options.width = 800;
options.height = 800;

options.url = "http://serverURL";

options.dialogReturnValueCallback = Function.createDelegate(null, DialogCallback);
SP.UI.ModalDialog.showModalDialog(options);
}
function DialogCallback(result,value){
window.location.href = "http://callbackURL";
}

How to launch a document by clicking a link to the file?

Word: <a href='ms-word:ofe|u|path/to/web/word/document.docx'>Link to document</a> Excel: <a href='ms-excel:o...