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...
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 want to read an Item from a Document Library and then Delete it. The problem I get a Security Exception: "The security validation for this page is invalid"
What am I doing wrong? I'm executing the commands with Elevated Privilages!
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite oSiteCollection = new SPSite(SharePointInfo.SubSiteUrl))
{
using (SPWeb oWebsite = oSiteCollection.OpenWeb())
{
SPList uploadFilesLibrary = oWebsite.Lists[SharePointInfo.UploadFilesLibraryName];
if (files.Count > 0)
{
foreach (var fileToSend in files)
{
try{
/*SPFile file = uploadFilesLibrary.Items.Cast<SPListItem>()
.Where(x => x.Name.Equals(fileToSend))
.Select(x => x.File).First();*/
SPListItem p = uploadFilesLibrary.Items.Cast<SPListItem>()
.Where(x => x.Name.Equals(fileToSend)).First();
byte[] binaryFile = p.File.OpenBinary();
p.Delete();
aux = new FileAttachesForm(fileToSend, System.Convert.ToBase64String(binaryFile));
rtn.Add(aux);
}catch (Exception ex){
string errMessage = string.Format("Error al descargar el fichero desde SP: {0} - Pila: {1}", ex.Message, ex.StackTrace);
Logger.LogError(errMessage, ex);
throw ex;
}
}
}
}
}
});
return rtn;
}
Try adding this inside of your if:
oSiteCollection.AllowUnsafeUpdates = true;
And take a look at this related question:
SharePoint Security Validation Issue while updating metadata (The security validation for this page is invalid)
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.