How can i Pull Profile image from sharepoint - asp.net-mvc

I'am new in API's & trying to pull user profile from sharepoint i use following code but don't know about servername? domainname? and username?
const string serverUrl = "http://sharepoint.com/";
const string targetUser = "ttgdev-my.sharepoint.com\\testuser1#ttgdev.guru";
// Connect to the client context.
ClientContext clientContext = new ClientContext(serverUrl);
// Get the PeopleManager object and then get the target user's properties.
PeopleManager peopleManager = new PeopleManager(clientContext);
PersonProperties personProperties = peopleManager.GetPropertiesFor(targetUser);
// Load the request and run it on the server.
// This example requests only the AccountName and UserProfileProperties
// properties of the personProperties object.
clientContext.Load(personProperties, p => p.AccountName, p => p.UserProfileProperties);
clientContext.ExecuteQuery();
foreach (var property in personProperties.UserProfileProperties)
{
Console.WriteLine(string.Format("{0}: {1}",
property.Key.ToString(), property.Value.ToString()));
}
Console.ReadKey(false);
Please guide me it will give me the error in
{"The property or field 'UserProfileProperties' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested."}
in the following line
clientContext.ExecuteQuery();

Most likely it is related with the format of targetUser variable. PeopleManager.GetPropertiesFor method expects accountName parameter to be specified in the proper format, in case of SharePoint Online it should be specified in claims format, for example:
i:0#.f|membership|jdow#contoso.onmicrosoft.com
For more details about Claims format follow this article.
So, in your case targetUser value should be replaced from ttgdev-my.sharepoint.com\\testuser1#ttgdev.guru to i:0#.f|membership|testuser1#ttgdev.guru
The following example demonstrates how to retrieve user profile picture via CSOM API:
using (var ctx = TokenHelper.GetClientContextWithAccessToken(webUri.ToString(), accessToken))
{
// Get the PeopleManager object and then get the target user's properties.
var peopleManager = new PeopleManager(ctx);
PersonProperties personProperties = peopleManager.GetPropertiesFor(targetUser);
//Retrieve picture property
var result = peopleManager.GetUserProfilePropertyFor(accountName, "PictureURL");
ctx.ExecuteQuery();
Console.WriteLine("Picture Url: {0}",result.Value);
}

Related

How to do a POST batch request in Miscrosoft Graph .NET SDK

I'm trying to do a batch request using MS Graph .NET SDK as shown here: https://learn.microsoft.com/en-us/graph/sdks/batch-requests?tabs=csharp
The only problem is that when I run the code, nothing happens.
I'm trying to move a set of emails (stored in a list) to another mail folder.
Am I missing anything?
The move request is here https://learn.microsoft.com/en-us/graph/api/message-move?view=graph-rest-1.0&tabs=http
When used in a single query it works, but not when batching.
Below you will find the code, in this case I'm looping to 20 just to test as 20 is the maximum queries per batch.
Thanks in advance.
for (int i = 0; i < 20; i++)
{
var mail = invalidMessages[i];
var userRequest = client.Me.Messages[mail.Id]
.Move(failureFolderID)
.Request();
requestID = batchRequestContent.AddBatchRequestStep(userRequest);
}
var returnedResponse = await client.Batch.Request().PostAsync(batchRequestContent);
EDIT: I tried to change the method to POST
userRequest.Method = System.Net.Http.HttpMethod.Post;
but I get a ServiceException: 'Code: BadRequest
Message: Write request id : fe23b1c1-663d-4499-829a-291d04a12b48 does not contain Content-Type header or body.'
The Microsoft Graph message-move API call you are attempting to use is a POST request
The Microsoft Batch API handles POST requests differently than the other API methods.
As per https://learn.microsoft.com/en-us/graph/sdks/batch-requests?tabs=csharp
POST requests are handled a bit differently.
The SDK request builders generate GET requests, so
you must get the HttpRequestMessage and convert to a POST
To have a successful post with the batch API you need to
Create an HttpRequestMessage
provide a value for the HttpRequestMessage's Content property which houses the POST requests payload
So if I applied this to your code I would first create a class to represent the POST payload for the message-move API. As per https://learn.microsoft.com/en-us/graph/api/message-move?view=graph-rest-1.0&tabs=http
the POST API has one property called destinationId
destinationId - The destination folder ID, or a well-known folder name. For a list of supported well-known folder names, see mailFolder resource type.
public class MailMovePayload
{
public string destinationId { get; set; }
}
then I would use an instance of this class in this modified version of you code
string str = events.Content.ReadAsStringAsync().Result;
events.Method = HttpMethod.Post;
for (int i = 0; i < 20; i++)
{
var mail = invalidMessages[i];
//get the request message object from your request
var userRequestMessage = client.Me.Messages[mail.Id]
.Move(failureFolderID)
.GetHttpRequestMessage();
//set the message API method
userRequestMessage.Method = HttpMethod.Post;
//create the payload, I am assuming failureFolderID is
//the name of the folder where the mail will be moved to
var payloadData = new MailMovePayload { destinationId = failureFolderID };
//make the JSON payload for the request message
userRequestMessage.Content = new StringContent(JsonConvert.SerializeObject(payloadData), Encoding.UTF8, "application/json")
requestID = batchRequestContent.AddBatchRequestStep(userRequestMessage);
}
var returnedResponse = await client.Batch.Request().PostAsync(batchRequestContent);
return httpRequestMessage;
}

How to use SODA.net and App Token in asp.net-core MVC

As per Socradata.com suggest, I have created both and an Application Token and an Application Key.
When I query using a Soda.net Click using the App Token and username and password like this:
var client = new SodaClient(sodaHost, sodaAppToken, user, pwd);
var soql = new SoqlQuery().Select("draw_date", "winning_numbers", "mega_ball", "multiplier").Where("draw_date > '2018-01-01'").Order(SoqlOrderDirection.DESC, "draw_date");
var dataset = client.GetResource<MyClass>(soda4x4);
var results = dataset.Query<MyClass>(soql);
Or when query using the App Token and App Key like this:
var client = new SodaClient(sodaHost, sodaAppToken, keyId, keySecret);
var soql = new SoqlQuery().Select("draw_date", "winning_numbers", "mega_ball", "multiplier").Where("draw_date > '2018-01-01'").Order(SoqlOrderDirection.DESC, "draw_date");
var dataset = client.GetResource<MyClass>(soda4x4);
var results = dataset.Query<MyClass>(soql);
I get the following error:
System.ArgumentOutOfRangeException
HResult=0x80131502
Message=The provided resourceId is not a valid Socrata (4x4) resource identifier.
Parameter name: resourceId
Source=SODA
StackTrace:
at SODA.SodaClient.Query[TRow](SoqlQuery soqlQuery, String resourceId)
at SODA.Resource1.Query[T](SoqlQuery soqlQuery)
at NumPicker.Controllers.HomeController.MegaMillions() in C:\Users\ka8kgj\Desktop\NumPicker\NumPicker\Controllers\HomeController.cs:line 45
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()
However, when I query anonymously with this client. No error. All is well.
var client = new SodaClient(sodaHost);
var soql = new SoqlQuery().Select("draw_date", "winning_numbers", "mega_ball", "multiplier").Where("draw_date > '2018-01-01'").Order(SoqlOrderDirection.DESC, "draw_date");
var dataset = client.GetResource<MyClass>(soda4x4);
var results = dataset.Query<MyClass>(soql);
Obviously I can not see an issue with the code. Can someone point out what I am missing?
Ok, Here is the answer. It is most embarrassing but I will take the humiliation so that others may not have too..
When you create the app-token on the SOCRATA web site. You get a Key / Secrete pair.
When passing the app-token, It is the KEY that should be passed. NOT THE SECRETE !

Rally Authentication issue in Getting results

I am using asp.net MVC application and consuming Rally web API for integration. I want fetch the data from rally site.
in Login Controller
RallyRestApi restApi = new RallyRestApi(webServiceVersion: "v2.0");
dynamic authenticateUser=restApi.Authenticate(usr.UserName, usr.Password, "https://rally1.rallydev.com/", allowSSO: false);
dynamic objUserName;
if (authenticateUser.ToString().ToLower() == "authenticated")
{
Session["Username"] = usr.UserName;
Session["Password"] = usr.Password;
FormsAuthentication.SetAuthCookie(usr.UserName, true);
FormsAuthentication.SetAuthCookie(usr.Password, true);
objUserName = restApi.GetCurrentUser();
Session["DisplayName"] = objUserName["DisplayName"];
return RedirectToAction("Home", "PortfolioItem");
}
Here Authentication is successful. But as per my research, if we want to fetch data every time, I think we need to pass user authentication details like below:
CreateResult createResult = restApi.Create("defect", toCreate); // need to get with same restApi object or authentication details
OperationResult updateResult = restApi.Update(createResult.Reference, toUpdate);
//Get the item
DynamicJsonObject item = restApi.GetByReference(createResult.Reference);// need to get with same restApi object or authentication details
//Query for items
Request request = new Request("defect");
request.Fetch = new List<string>() { "Name", "Description", "FormattedID" };
request.Query = new Query("Name", Query.Operator.Equals, "My Defect");
QueryResult queryResult = restApi.Query(request); // need to get with same restApi object or authentication details
Like above, is it if we need to fetch anything, we need to authenticate first and every time? please clarify on this.
You'll need to authenticate once for each instance of RallyRestApi you create. In general it is better to create one, use it, and then dispose of it rather than creating it once and then keeping it around in session forever.

Unable to figure out how to use post method, for a suitescript written in Netsuite

I am trying to do use the post method for a simple suitescript program, i am very new to this.
In Netsuite i have written a suitescript as follows.
function restPost()
{
var i = nlapiLoadRecord('department', 115);
var memo = nlapisetfieldvalue('custrecord225', ' ');// this is a customfield, which i want to populate the memo field, using rest client in firefox
var recordId = nlapiSubmitRecord(i);
}
i have created a script record and uploaded this suitescript and even copied the external URL to paste it in restclient.
In Restclient(firefox plugin), pasted the external URL, i have given the method as post, header authorization given, content-type: application/json, and in body i put in {"memo":"mynamehere"};
In this the error i get is
message": "missing ) after argument list
I even tried it by writting other suitescript programs the errors i get is as follows:
Unexpected token in object literal (null$lib#3) Empty JSON string
Invalid data format. You should return TEXT.
I am kinda new to the programming world, so any help would be really good.
I think you are trying to create a RESTlet for POST method. Following is the sample code for POST method -
function createRecord(datain)
{
var err = new Object();
// Validate if mandatory record type is set in the request
if (!datain.recordtype)
{
err.status = "failed";
err.message= "missing recordtype";
return err;
}
var record = nlapiCreateRecord(datain.recordtype);
for (var fieldname in datain)
{
if (datain.hasOwnProperty(fieldname))
{
if (fieldname != 'recordtype' && fieldname != 'id')
{
var value = datain[fieldname];
if (value && typeof value != 'object') // ignore other type of parameters
{
record.setFieldValue(fieldname, value);
}
}
}
}
var recordId = nlapiSubmitRecord(record);
nlapiLogExecution('DEBUG','id='+recordId);
var nlobj = nlapiLoadRecord(datain.recordtype,recordId);
return nlobj;
}
So after deploying this RESTlet you can call this POST method by passing following sample JSON payload -
{"recordtype":"customer","entityid":"John Doe","companyname":"ABCTools Inc","subsidiary":"1","email":"jdoe#email.com"}
For Authorization you have to pass request headers as follows -
var headers = {
"Authorization": "NLAuth nlauth_account=" + cred.account + ", nlauth_email=" + cred.email +
", nlauth_signature= " + cred.password + ", nlauth_role=" + cred.role,
"Content-Type": "application/json"};
I can understand your requirement and the answer posted by Parsun & NetSuite-Expert is good. You can follow that code. That is a generic code that can accept any master record without child records. For Example Customer Without Contact or Addressbook.
I would like to suggest a small change in the code and i have given it in my solution.
Changes Below
var isExistRec = isExistingRecord(objDataIn);
var record = (isExistRec) ? nlapiLoadRecord(objDataIn.recordtype, objDataIn.internalid, {
recordmode: 'dynamic'
}) : nlapiCreateRecord(objDataIn.recordtype);
//Check for Record is Existing in Netsuite or Not using a custom function
function isExistingRecord(objDataIn) {
if (objDataIn.internalid != null && objDataIn.internalid != '' && objDataIn.internalid.trim().length > 0)
return true;
else
return false;
}
So whenever you pass JSON data to the REStlet, keep in mind you have
to pass the internalid, recordtype as mandatory values.
Thanks
Frederick
I believe you will want to return something from your function. An empty object should do fine, or something like {success : true}.
Welcome to Netsuite Suitescripting #Vin :)
I strongly recommend to go through SuiteScript API Overview & SuiteScript API - Alphabetized Index in NS help Center, which is the only and most obvious place to learn the basics of Suitescripting.
nlapiLoadRecord(type, id, initializeValues)
Loads an existing record from the system and returns an nlobjRecord object containing all the field data for that record. You can then extract the desired information from the loaded record using the methods available on the returned record object. This API is a core API. It is available in both client and server contexts.
function restPost(dataIn) {
var record = nlapiLoadRecord('department', 115); // returns nlobjRecord
record.setFieldValue('custrecord225', dataIn.memo); // set the value in custom field
var recordId = nlapiSubmitRecord(record);
return recordId;
}

How to change the default values of start and count parameters when picking the companies followed by a user in linkedin?

I am making a web-application in ASP.NET. I have used oauth to get profile fields of a user. I need the names of the companies followed by the user, but the problem is that the default value is set to 20. so, if the user is following more than 20 companies i am not able to get it. Please tell me how can i modify the start and count values. Iv used this url to make the call http://api.linkedin.com/v1/people/~:(following:(people,companies,industries,news-sources),educations).. Please help asap..
var requestHeader = GetUserProfileAuthorizationHeader();
var queryString = CreateQueryString();
var request = WebRequest.Create(RequestProfileUrl + queryString);
request.Headers.Add("Authorization", requestHeader.ToString());
request.Method = HttpMethod.Get;
try
{
var response = request.GetResponse();
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
var responseText = reader.ReadToEnd();
reader.Close();
return responseText;
}
}
Here public static string RequestProfileUrl = "http://api.linkedin.com/v1/people/~:(following:(companies:(id,name,size,industry),industries))"; And the method CreateQueryString() does this queryString = "?format=xml"; whenever i try to add something like queryString = "?format=xml&start=0&count=40"; it gives error dispite the number of companies followed being more than 60.. maybe i need to pass the query parameters in between the RequestProfileUrl i.e near the company somehow..
Did you tried adding ?start=x&count=y to the url?
Probably if you're getting an error when you add query parameters to the URL, you're not adding those parameters in the way that your OAuth library expects them to be added. You need to figure out how to add the parameters so they're added to the signature generation process or your signature will be invalid and you'll get a 401 error back from the server.

Resources