upload a file to SharePoint 2013 programmatically externally

Hi there,

Simple console app, took a while but found article

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace SPSample2
{
class Program
{
static void Main(string[] args)
{

string filePath = @”C:\Running Notes.txt”; //File to be uploade
string siteurl = “http://siteurl”; //site on which file needs to be uploaded (don’t put / at end)
string documentlibrary = “account”; //Document library where file needs to be uploaded
bool filestatus = UploadUsingRest(siteurl, documentlibrary, filePath);
if (filestatus)
{
Console.WriteLine(“File uploaded successfully”);
}
else
{
Console.WriteLine(“Error uploading file”);
}
}

//Method to upload File
public static bool UploadUsingRest(string siteurl, string libraryName, string filePath)
{
bool status = false;
byte[] binary = System.IO.File.ReadAllBytes(filePath);
string fname = System.IO.Path.GetFileName(filePath);
string result = string.Empty;
//Url to upload file
string resourceUrl = siteurl + “/_api/web/GetFolderByServerRelativeUrl(‘” + libraryName + “‘)/Files/add(url='” + fname + “‘,overwrite=true)”;
HttpWebRequest wreq = HttpWebRequest.Create(resourceUrl) as HttpWebRequest;
wreq.UseDefaultCredentials = false;
//credential who has edit access on document library
NetworkCredential credentials = new System.Net.NetworkCredential(“username”, “password”, “domain”);
wreq.Credentials = credentials;

//Get formdigest value from site
string formDigest = GetFormDigestValue(siteurl, credentials);
wreq.Headers.Add(“X-RequestDigest”, formDigest);
wreq.Method = “POST”;
wreq.Timeout = 1000000; //timeout should be large in order to upload file which are of large size
wreq.Accept = “application/json; odata=verbose”;
wreq.ContentLength = binary.Length;
try
{
using (System.IO.Stream requestStream = wreq.GetRequestStream())
{
requestStream.Write(binary, 0, binary.Length);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

try
{
WebResponse wresp = wreq.GetResponse();
using (System.IO.StreamReader sr = new System.IO.StreamReader(wresp.GetResponseStream()))
{
result = sr.ReadToEnd();
status = true;
return status;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return status;
throw;
}
}

//Method which return form digest value
private static string GetFormDigestValue(string siteurl, NetworkCredential credentials)
{
string newFormDigest = “”;
HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(siteurl + “/_api/contextinfo”);
endpointRequest.Method = “POST”;
endpointRequest.ContentLength = 0;
endpointRequest.Credentials = credentials;
endpointRequest.Accept = “application/json;odata=verbose”;

try
{
HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

try
{

WebResponse webResp = endpointRequest.GetResponse();
Stream webStream = webResp.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
var j = JObject.Parse(response);
var jObj = (JObject)JsonConvert.DeserializeObject(response);
foreach (var item in jObj[“d”].Children())
{
newFormDigest = item.First()[“FormDigestValue”].ToString();
}
responseReader.Close();

}
catch (Exception ex)
{

Console.WriteLine(ex.Message);
}

return newFormDigest;
}

}
}

Add the Newtonsoft.Json dll from nugget.

Cheers.

CRM 2013 update the Party list type field using OData and JavaScript/ Associate ActivityParty record with Activity

Hello there,

After a day struggle can conclude that in JavaScript using Odata with Ajax and Jquery, we can’t update party list fields on Activities. Only Soap using Odata and JavaScript, we can update party fields.

On creation of any Activity, we can’t get Partylist fields updated on that Activity. Rather we need to create Activity record first then pass the new ActivityId to ActivityParty object and create the ActivityParty record. Which upon creation associates the Partylist field in the above Activity record created.

To Create Activity use any standary odata method in javascript But for Later ActivtyParty we need SDK.Rest.Create function from the SDK.REST library. Rest methods are not fruitful. Below is working example of creating a Service Activity record and later updating the Customer field on the Service activity.

// JavaScript source code
// =====================================================================
// This file is part of the Microsoft Dynamics CRM SDK code samples.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// This source code is intended only as a supplement to Microsoft
// Development Tools and/or on-line documentation. See these other
// materials for detailed information regarding Microsoft code samples.
//
// THIS CODE AND INFORMATION ARE PROVIDED “AS IS” WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// =====================================================================
//
///
///
///
///
///

var primaryContact = null;
var startButton;
var resetButton;
var output;

function CreateSA()
{

alert(“Entered the Script”);

var ContactId = “8DA6E5B9-88DF-E311-B8E5-6C3BE5A8B200”;

var serviceAppointment = {};
serviceAppointment.Subject = “Subject Demo1”;
serviceAppointment.ScheduledStart = new Date(“January 11, 2013”);
serviceAppointment.ScheduledEnd = new Date(“January 15, 2013”);
// serviceAppointment.Customers = { Id: ContactId, Name: “Alex Simmons”, entityType: “contact”, };

//Below code doesn’t work because odata with Ajax and Jquery doesn’t work for Activity party records
//Create the Account
//SDK.JQuery.createRecord(
// serviceAppointment,
// “ServiceAppointment”,
// function (account) {
// // writeMessage(“The account named \”” + account.Name + “\” was created with the AccountId : \”” + account.AccountId + “\”.”);
// // writeMessage(“Retrieving account with the AccountId: \”” + account.AccountId + “\”.”);
// retrieveAccount(account.AccountId)
// },
// errorHandler
// );

SDK.REST.createRecord(
serviceAppointment,
“ServiceAppointment”,
function (SA) {

alert(“Service Activity created…check now”);
//Now updating the Customers field on the Service appointment
var activityParty = new Object();
// Set the “party” of the ActivityParty // EntityReference of an entity this activityparty relatated to.
activityParty.PartyId = {
Id: ContactId,//replace this with the contactid from your system.
LogicalName: “contact”
};
// Set the “activity” of the ActivityParty
// EntityReference.
activityParty.ActivityId = {
Id: SA.ActivityId,
LogicalName: “serviceappointment”
};
// Set the participation type (what role the party has on the activity).
activityParty.ParticipationTypeMask = { Value: 11 }; // 11 mean Customers
SDK.REST.createRecord(activityParty, “ActivityParty”,
function (SA2) {
alert(“activityparity created”);
},
function (error) {
alert(error.message);
}

);

},
errorHandler
);
// this.setAttribute(“disabled”, “disabled”);
}

function errorHandler(error) {
alert(error.message);
}

Always update participation mask by checking with field you are updating and relevant Party List field

https://msdn.microsoft.com/en-us/library/gg328549.aspx

so never try to update any partylist with activity record, rather do it separately by creating the ActivityParty record with association to Activity.

Thanks,
Sama.

Charts not rendering due to date filters CRM 2011/An error occurred while the chart is rendering

Hi there,

Charts not rendering due to the date fields or aggregate methods on the chart filters.

System.Data.SqlClient.SqlException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #9E276F66: System.Data.SqlClient.SqlException (0x80131904): An error occurred in the Microsoft .NET Framework while trying to load assembly id 65536. The server may be running out of resources, or the assembly may not be trusted with PERMISSION_SET = EXTERNAL_ACCESS or UNSAFE. Run the query again, or check documentation to see how to solve the assembly trust issues. For more information about this error:
>System.IO.FileLoadException: Could not load file or assembly ‘microsoft.crm.sqlclr.helper, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ or one of its dependencies. An error relating to security occurred. (Exception from HRESULT: 0x8013150A)
>System.IO.FileLoadException:

Cause: In CRM database migration from one sqlserver to another, the SID(security identification number) for the database should match source and destination, or at least the destination database owner should be service account with admin access in CRM, with Trustworthy enabled.

Fix: Make sure the Trustworthy is enabled for the database
Make sure the database owner is service account or account as admin with in the CRM users

usefull tips:
check the owner name of the database
select SUSER_SNAME(owner_sid) from sys.databases

set the Trustworthy of database
ALTER DATABASE orgname_MSCRM SET trustworthy ON

Change the owner of the database

USE DatabaseName
GO

EXEC sp_changedbowner ‘sa’

lastly if nothing working just do sql service restart or change the db owner as sql service account and roll back to the crm service account.

helpfull blogs on this:
https://support.microsoft.com/en-us/kb/918040
http://crmpt.blogspot.co.uk/2011/12/charts-aggregated-by-date-problem.html

Thanks,
Sama.

External Images in CRM reports not displayed on premises CRM

Hello Guys,

If you see any external images like hyperlink referred in Reports.

Issue: Image throwing error or empty

Fix: Just go to the reporting manager and setup the right account details on execution context

Excecution account Reporting Manager

Further information on images click here

Thanks,
Sama.

Passing callback as parameter to another function JavaScript

Hi there,

below library gives you in detail of how we can optimise the code in javascript

upload this library either formload or in html webresource

//start
function testhtml()
{
mactest.htmlOnload();
}

mactest= {
//Ends
findlinkurl: function (findurlparm) {

alert(“just entered findlinkurl” + findurlparm);

},

htmlOnload: function () {
alert(“welcome to hello world”);
mactest.getserviceurl(“test1param”, mactest.findlinkurl)
},

getserviceurl: function (test1, callbackname) {
alert(“Inside the test1 and test2 values” + test1);
test1 = “findurlparam1”;
callbackname(test1);
}
};

call testhtml() function from any event trigger
output:

welcome to hello world
Inside the test1 and test2 valuestest1param
just entered findlinkurlfindurlparam1

Thanks,

Check the form isdirty and suppress

Hi there, if you find OnLoad of a record, causes some script either system/custom script to set value on visible/hidden fields on a record
Bug: once the form is dirty, when you are closing the record it prompts to save the record which you don’t wish to
solution: Run the below code in debugging options or onload event
for (var i in Xrm.Page.data.entity.attributes.get())
{
if (Xrm.Page.data.entity.attributes.get()[i].getIsDirty())
alert(“Dirty Field: ” + Xrm.Page.data.entity.attributes.get()[i].getName());
}

find the fields which are dirty from the alerts you get in above script, then run below code before you exit the onload event to supress the isdirty fields submission
Xrm.Page.getAttribute(“dirty field you found”).setSubmitMode(“never”);

Thanks

CRM 2011 security access privileges check

Hi there,

if you want to know the user’s privilege access check with in CRM interface and behind the screens can be seen by running below query in SQL

SELECT Privilege.*, RolePrivileges.*, SystemUserRoles.*
FROM Privilege
INNER JOIN RolePrivileges ON Privilege.PrivilegeId = RolePrivileges.PrivilegeId
INNER JOIN SystemUserRoles ON SystemUserRoles.RoleId = RolePrivileges.RoleId AND SystemUserRoles.SystemUserId = ‘6CC471DA-FEEB-E311-880C-00237DEC9650’

Thanks,
Sama.