I'm really not experienced in this subject, and I can't seem to find out where to quite start.
I'm trying to read data from a list on SharePoint 13 (365 Preview) into a WinRT App. I added a Service Reference to mysite.sharepoint.com/_vti_bin/listdata.svc and it added correctly. From there I built this wrapper for getting the a list asynchronously:
private Task<IEnumerable<MyListItems>> GetMyListAsync()
{
var tcs = new TaskCompletionSource<IEnumerable<MyListItems>>();
var sharepointContext =
new WelcomescreentestTeamSiteDataContext(
new Uri("https://mysite.sharepoint.com/_vti_bin/listdata.svc"))
{
Credentials = new NetworkCredential("user.name", "pass.word", "mysite.onmicrosoft.com")
}; ;
try
{
sharepointContext.MyList.BeginExecute(asyncResult =>
{
try
{
var result = sharepointContext.MyList.EndExecute(asyncResult);
tcs.TrySetResult(result);
}
catch (OperationCanceledException ex)
{
tcs.TrySetCanceled();
}
catch (Exception ex)
{
if (!tcs.TrySetException(ex))
{
throw;
}
}
}, new object());
}
catch (Exception ex)
{
tcs.TrySetException(ex);
tcs.SetCanceled();
}
return tcs.Task;
}
I've changed the username / domain around quite a bit, but nothing seems to work.
What's the right approach here?
I've built in a SAML-based security approach which works, but I'm still wondering why this isn't working.
Related
I am trying to Get EventMessage from Message in MS Graph API with C# but every time it is showing type as a message instead of EventMessage. Below are the code:-
public static Graph.MailFolderMessagesCollectionPage ReadInbox()
{
GetAuthenticatedClient();
var result = new Graph.MailFolderMessagesCollectionPage();
List<Graph.QueryOption> options = new List<Graph.QueryOption>
{
new Graph.QueryOption("$expand","microsoft.graph.eventMessage/event"),
new Graph.QueryOption("$filter","isread eq false")
};
try
{
var response = graphClient.Me.MailFolders.Inbox.Messages.Request(options).OrderBy("receivedDateTime DESC").GetAsync();
result = response.Result as Graph.MailFolderMessagesCollectionPage;
}
catch (Exception ex)
{ }
Call the above method ReadInbox to get type and perform some action.
var appointments = ReadInbox();
if (appointments != null)
{
foreach (dynamic request in appointments)
{
try
{
if (request.GetType().Name.Contains("EventMessage"))
{
}
else if (request.GetType().Name == "Message")
{
}
}
catch (Exception ex)
{
}
}
}
Use the IsInstanceOfType method to identify if its an eventMessage. You can also remove the expand option from the query option since eventMessages are fetched anyway as part of the get Messages call.
if (appointments != null)
{
foreach (dynamic request in appointments)
{
try
{
if (typeof(EventMessage).IsInstanceOfType(request))
{
Console.WriteLine("Is an event");
Console.WriteLine(request);
}
}
catch (Exception ex)
{
}
}
}
I have not implemented versioning to my api yet, as wanted to get some more info first.
I am using asp.net web api, and integrating into a WPF application, using AutoRest.
Its been running for some months now, but I'm looking to use versioning with the api.
With a typical call from WPF to the api, is there a way to target particular versions of the api?
public async Task<ObservableCollection<EventsDTO>> GetEvents(bool ShowInActive)
{
try
{
CheckCredentials.CheckValidCredentials();
using (var db = new BuxtedAPI(CheckCredentials.RestCredentials))
{
var res = await db.GetEventsAsync(ShowInActive).ConfigureAwait(false);
var obs = new ObservableCollection<EventsDTO>(res);
return obs;
}
}
catch (Exception ex)
{
logger.Error(ex);
return null;
}
}
Thanks in advance.
If anyone else has this problem.
public async Task<ObservableCollection<EventsDTO>> GetEvents(bool ShowInActive)
{
try
{
CheckCredentials.CheckValidCredentials();
using (var db = new BuxtedAPI(CheckCredentials.RestCredentials))
{
db.HttpClient.DefaultRequestHeaders.Add("X-Version", "2.0");
var res = await db.GetEventsAsync(ShowInActive).ConfigureAwait(false);
var obs = new ObservableCollection<EventsDTO>(res);
return obs;
}
}
catch (Exception ex)
{
logger.Error(ex);
MessageBox.Show(
$"{ex.Message}{Environment.NewLine}{ex.InnerException?.ToString() ?? ""}");
return null;
}
}
and on the controller
public class EventV2Controller : ApiController
{
[ApiVersion("2.0")]
[RoutePrefix("api/events")]
and the config.
config.AddApiVersioning(cfg =>
{
cfg.DefaultApiVersion = new ApiVersion(1, 0);
cfg.AssumeDefaultVersionWhenUnspecified = true;
cfg.ReportApiVersions = true;
cfg.ApiVersionReader = new HeaderApiVersionReader("X-Version");
});
We have an ASP.NET website running which throws a NullReference-exception along with a stacktrace and a line number that is simply impossible. And I can't make heads nor tails from it myself.
It says:
Exception at ReportService.GetReport(String reportType) in ReportService.cs:line 1458
which is funny, because that is this line:
var exports = new List<ReportExport>();
Thanks to the (very short) stacktrace, I can see that the error is triggered in the GetReport-function and not in the "GetAllUsers" or "GetAllUsersWithFilter" functions, because I would receive a different error message in my e-mailbox or I would see it pop up in the stacktrace.
So I suspect the line number is wrong, in which case there is only one other possibility and that is this line:
foreach (var userProfile in users) {
exports.Add(CreateUserProfile(userProfile));
}
But how could users ever be null?
Full (albeit simplified) code right here:
public function IList<ReportExport> GetReport(string reportType) {
try {
IQueryable<UserProfile> users = null;
switch (reportType) {
case "abc" :
users = GetAllUsersWithFilter();
break;
case default:
users = GetAllUsers();
break;
}
var exports = new List<ReportExport>();
foreach (var userProfile in users) {
exports.Add(CreateUserProfile(userProfile));
}
} catch (Exception ex) {
SendErrorMail("GetReport has failed", ex); /* I receive this error mail */
}
function IQueryable<UserProfile> GetAllUsers() {
try {
return dbContext.Users.Where(x => x.IsRegistered == true);
} catch (Exception ex) {
SendErrorMail("GetAllUsers", ex); /* I don't receive this e-mail */
return null;
}
}
function IQueryable<UserProfile> GetAllUsersWithFilter() {
try {
return GetAllUsers().Where(x => x.ExtraFilter == true);
} catch (Exception ex) {
SendErrorMail("GetAllUsersWithFilter", ex); /* I don't receive this e-mail */
}
}
function int GetNumberOfSessions(int userId) {
try {
return dbContext.Sessions.Count(x => x.UserId == userId);
} catch (Exception ex) {
SendErrorMail("GetNumberOfSessions", ex); /* I don't receive this e-mail */
}
}
function ReportExport CreateUserExport(UserProfile user) {
try {
var cnt = GetNumberOfSessions(user.Id);
return new ReportExport() {
UserId = user.Id,
NumberOfSessions = cnt
}
} catch (Exception ex) {
SendErrorMail(("CreateUserExport", ex);
}
}
If you are in production then you might be running with optimizations switched on - therefore the line number will be wrong.
But how could users ever be null?
But you are catching the Exception then returning null. You are relying on returning data - which may not be the case in GetAllUsers.
function IQueryable<UserProfile> GetAllUsers() {
try {
return dbContext.Users.Where(x => x.IsRegistered == true);
} catch (Exception ex) {
SendErrorMail("GetAllUsers", ex); /* I don't receive this e-mail */
return null;
}
}
I am very new to sharepoint. What is the fastest and most efficient way to check Sharepoint site connectivity before ClientContext.ExecuteQuery.
ClientContext ctx = new ClientContext(ConfigurationManager.AppSettings["sharepoint siteUrl"]);
float pageLoadTime = getPageLoadTime(ctx);
if(pageLoadTime > 0.5)
{
MessageBox.Show("Sharepoint site is not available!");
return;
}
//do very heavy query
....
ctx.ExecuteQuery();
There is no such standard method to do that. But you can achieve this like following code
using (ClientContext sourceContext = new ClientContext("Sharepoint Url"))
{
try
{
sourceContext.ExecuteQuery();
List list = sourceContext.Web.Lists.GetByTitle("Test");
ListItemCollection itemColl = list.GetItems(CamlQuery.CreateAllItemsQuery());
sourceContext.Load(itemColl);
sourceContext.ExecuteQuery();
}
catch (System.Net.WebException ex)
{
if (ex.Message == "The remote server returned an error: (404) Not Found.")
{
Console.WriteLine("SharePoint not available");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
because "ExecuteQuery" is the method which connect to SharePoint through Client.svc wcf service.
Hope this helps...
I am implementing some performance counters and I would like to know your opinion.
The question is should I declare response and return it outside try block or Is it OK to return it directly in the try block. Is there a difference and If so, what sample code is valid (if any).
With best regards, no9.
public string TestMethod(string document)
{
try
{
WebService ws = new WebService();
string response = null;
var startTime = PerformanceCounter.GetPerformanceCounterStartTimeHandle();
try
{
response = ws.InsertDocument(document);
}
catch (Exception ex)
{
PerformanceCounterHelper.Increment(PerformanceCounterEnum.NumberOfExternalWsCallsExceptionOnSec);
throw;
}
finally
{
PerformanceCounterHelper.IncrementPerformanceCounterByElapsedTime(PerformanceCounterEnum.DurationOfExternalCallsInSec, startTime);
PerformanceCounterHelper.Increment(PerformanceCounterEnum.NumberOfExternalCallsOnSec);
}
return response;
}
catch (Exception ex)
{
log.EventError(ex);
throw new DocumentGeneralException();
}
}
versus:
public string TestMethod(string document)
{
try
{
WebService ws = new WebService();
var startTime = PerformanceCounter.GetPerformanceCounterStartTimeHandle();
try
{
return ws.InsertDocument(document);
}
catch (Exception ex)
{
PerformanceCounterHelper.Increment(PerformanceCounterEnum.NumberOfExternalWsCallsExceptionOnSec);
throw;
}
finally
{
PerformanceCounterHelper.IncrementPerformanceCounterByElapsedTime(PerformanceCounterEnum.DurationOfExternalCallsInSec, startTime);
PerformanceCounterHelper.Increment(PerformanceCounterEnum.NumberOfExternalCallsOnSec);
}
}
catch (Exception ex)
{
log.EventError(ex);
throw new DocumentGeneralException();
}
}
As long as there isn't a difference because of not exiting (i.e. it runs additional/different code), then the code is identical. Actually, at the IL level it is illegal to ret from inside a try/catch, so one of the things the compiler does is to do exactly what you have done: introduce a local, assign the local inside the try/catch, then return that value when outside the try/catch.
Basically, go with whatever is simplest and most convenient to read. In your case, I would say "the first one".