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");
});
Related
I was using the Microsoft Graph API 1.0 but have updated to the Beta in order to use CustomSecurityAttributeValue support.
I've managed to port most of the code but I can't see any way to process multiple results pages.
Previously you would just do something like
if (membersPage.NextPageRequest != null)
membersPage = await membersPage.NextPageRequest.GetAsync();
But NextPageRequest no longer exists, the only available information is OdataNextLink which is a string with no obvious way to request the next page or create a raw request using the url.
Code I have so far:
public async Task<IEnumerable<Microsoft.Graph.Beta.Models.User>> GetGraphUsersInGroups(IEnumerable<string> groupIds, string? searchText = null)
{
Dictionary<String, Microsoft.Graph.Beta.Models.User> users = new Dictionary<String, Microsoft.Graph.Beta.Models.User>();
foreach (var groupId in groupIds)
{
try
{
var membersPage = await GraphClient.Groups[groupId].Members
.GetAsync((memberRequest) => {
memberRequest.Headers.Add(new KeyValuePair<string, string>("$count", "true"));
memberRequest.Headers.Add(new KeyValuePair<string, string>("ConsistencyLevel", "eventual"));
memberRequest.QueryParameters.Count = true;
memberRequest.QueryParameters.Orderby = new[] { "displayName" };
if (searchText != null)
memberRequest.QueryParameters.Search = $"\"displayName:{searchText}\"";
});
while (membersPage != null)
{
foreach (var member in membersPage.Value.OfType<Microsoft.Graph.Beta.Models.User>())
{
users[member.Id] = member;
}
if (membersPage.OdataNextLink != null)
{
// How to use membersPage.OdataNextLink???
}
else
break;
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
return users.Values;
}
You should use the PageIterator, see an example below:
var users = new List<User>();
var userResponse = await serviceClient.Users.GetAsync((builder) => {
// builder.SomeStuff
});
// Added the namespace here, just for some clarity :-)
var pageIterator = Microsoft.Graph.PageIterator<User,UserCollectionResponse>
.CreatePageIterator(serviceClient, userResponse, (user) =>
{
users.Add(user.Id);
return true; });
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 use following script to get data from external service and store in dB. In certain rare cases less than 1% records gets updated with null values. In below code, the "re.status=fail" we see null. let us know if any thots.
public void ProcessEnquiries()
{
List<req> request = new List<req>();
var options = new ParallelOptions { MaxDegreeOfParallelism = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["MaxDegreeOfParallelism"]) };
try
{
Parallel.ForEach(request, options, currentRequest =>
{
ProcessedRequest processedRequest = null;
processedRequest = CommunicateToWS(currentRequest); // Here we call to webservice
});
}
catch (AggregateException exception)
{
foreach (Exception ex in exception.InnerExceptions)
{
// Handle Exception
}
}
}
public ProcessedRequest CommunicateToWS(req objReq)
{
ProcessedRequest re = new ProcessedRequest();
using (WebCall obj = new WebCall())
{
re.no = refnu;
try
{
retval = obj.getValue(inval);
objProxy.Close();
//get data
// parse and store to DB
}
catch (Exception e)
{
re.status = "fail";
//update DB that request has failed
//Handle Exception
obj.Close();
}
}
}
I have SQLite database in isolated storage in Windows Store App.
I use SQLite for Windows Runtime
When i want to delete all table entry I use follow method:
public static async void DeleteAllProjects()
{
var storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("myDb.sqlite");
using (var db = new SQLiteConnection(storageFile.Path))
{
try
{
db.DeleteAll<Projects>();
}
catch
(Exception ex)
{
Debug.WriteLine("Delete error " + ex.Message);
}
}
}
All work like a charm.
But when i need to delete part of entries:
public static async void Delete(List<Projects> projects)
{
var storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("myDb.sqlite");
using (var db = new SQLiteConnection(storageFile.Path))
{
try
{
foreach (var project in projects)
{
var existingProject = (db.Table<Projects>().Where(
p => p.id == project.Id)).FirstOrDefault();
if (existingProject != null)
{
db.Delete<Projects>(existingProject);
}
}
}
catch
(Exception ex)
{
Debug.WriteLine("Delete error " + ex.Message);
}
}
}
I handled exeption with
ex.Message = "Cannot delete Projects: it has no PK" string
Can somebody help me?
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.