Invoke Webservice with yield return on windows phone - windows-phone-7

i'm developing a Windows Phone 7 app and I use Windows Live authentication to access the user contacts. I have a webservice, with the following method:
public IEnumerable<LiveIDContact> GetContactsInformationYield(string LocationID, string DelegationToken)
{
string uriTemplate = "https://livecontacts.services.live.com/#L#{0}/rest/LiveContacts/Contacts";
var xdoc = WindowsLiveContactAPIRequest(LocationID, DelegationToken, uriTemplate);
var contacts = (from contact in xdoc.Descendants("Contact")
select contact).ToArray();
foreach (var con in contacts)
{
RetrieveCID(LocationID, DelegationToken, con);
LiveIDContact c = new LiveIDContact()
{
ID = con.Element("ID").Value,
DisplayName = con.Element("Profiles").Element("Personal").Element("DisplayName").Value,
CID = (con.Element("CID") != null ? con.Element("CID").Value : "")
};
yield return c;
}
}
How i invoke the methode in the app:
public void GetContactInformationAsync()
{
LiveIDClient.GetContactsInformationYieldAsync(LocationID, ConsentToken);
}
Here is the problem, when I invoke this methode and i wait on the complete event. It takes 4 to 5 minutes to update the list of contacts in my app.(Performance issue). Is there any way that an event occurs on every yield return ? So i can update my list from that event?
I couldn't find the answer anywhere so lets hope somebody knows the answer.

Is this making a separate HTTP call for every single contact? If so, then I think you simply need to redesign the webservice so that it makes a call for, say, every hundred contacts.

Related

Problem listing assignments of a student in Google Classroom

I am starting to use Classroom API to enhance local apps in our school. In order to make a report for a class, I want to list all student assignments and gradings. I use loops to go through all courses for a student, then all coursework for every course, and then all submissions for every coursework. Here is the piece of code that I use:
function fListWorkStudent(idStudent)
{
// Variables
var pageToken = null;
var optionalArgs =
{
pageToken: pageToken,
courseStates: 'ACTIVE',
studentId: idStudent,
pageSize: 0
};
var optionalArgs2 =
{
pageToken: pageToken,
userId: idStudent,
pageSize: 0
};
// Courses for a student
var response = Classroom.Courses.list(optionalArgs);
var sCourses = response.courses;
if (sCourses.length === 0)
Logger.log("No courses");
else
{
for (course in sCourses)
{
var idCourse=sCourses[course].id;
var nomprof=getUserName(sCourses[course].ownerId);
// Coursework for every course
var responseW = Classroom.Courses.CourseWork.list(idCourse);
var works = responseW.courseWork;
if (works && (works.length > 0))
{
for work in works)
{
var idWork=works[work].id;
// Submissions for every coursework
var responseS = Classroom.Courses.CourseWork.StudentSubmissions.list(idCourse, idWork, optionalArgs2);
var submissions = responseS.studentSubmissions;
if (submissions && submissions.length >0)
{
for (submission in submissions)
{
// Prepare report here
}
}
}
}
}
}
}
The problem with this code is that when I call Classroom.Courses.CourseWork.StudentSubmissions.list(idCourse, idWork, optionalArgs2) to get the submissions filtered of selected student, and the loop reaches a coursework not assigned to that student, the call fails with error 'classroom.courses.courseWork.studentSubmissions.list; error: Requested entity was not found.'
I could solve it by checking in the loop if the coursework is not assigned to that student before calling the API function, or maybe using a try..catch clause to catch the possible error, but I would like to know if there is a smarter solution to this issue.
Regards
Rafael
Unfortunately the API does not give you an endpoint to list directly all assignment / submissions of a given student
However, you are not alone with this problem, there is already a feature request for this functionality on Google's Public Issue Tracker.
I recommend you to give it a "star" in order to increase visibility.
In the mean time, indeed you either need to implement a try...catch statement, or a conditonal statement, something like:
if(works[work].assigneeMode == "ALL_STUDENTS" || (works[work].assigneeMode == "INDIVIDUAL_STUDENTS" && works[work].individualStudentsOptions.studentIds.indexOf(idStudent)!=-1))
{
var responseS = Classroom.Courses.CourseWork.StudentSubmissions.list(idCourse, idWork, optionalArgs2);
...
}

eror when retrieve createdby field in crm using plugin

I try to retrieve the createdby field when I create a cases with a plugin, but the first retrieval fails, and the second and subsequent retrieval are successful. And then when I logged out and login with other user the first retrieval fails (retrieve result is the user before i change the user), and the second and subsequent retrieval are successful.
here is the code i write :
public void Execute(IServiceProvider serviceProv)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProv.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory servicefac = (IOrganizationServiceFactory)serviceProv.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = servicefac.CreateOrganizationService(context.UserId);
ITracingService trace = (ITracingService)serviceProv.GetService(typeof(ITracingService));
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity ent = (Entity)context.InputParameters["Target"];
if (ent.LogicalName != "incident")
return;
QueryExpression qe = new QueryExpression("incident");
string[] cols1 = { "createdby" };
qe.ColumnSet = new ColumnSet(true);
EntityCollection ec = service.RetrieveMultiple(qe);
foreach (Entity act in ec.Entities)
{
created = act. GetAttributeValue<EntityReference>("createdby").Name;
}
if (created == "CRM SNA")
{
created = string.Empty;
}
else
{
//here is the autonumber code
created = string.Empty;
}
}
}
What I want to make is an autonumber plugin, when cases are created by "CRM SNA" then the autonumber must not run, when cases are created by other users the autonumber will run.
How to make the first retrieve successful? and did not retrieve the user before?
thanks.
I assume your plugin runs in the Pre-Create step. CreatedBy and CreatedOn are not available in this step (probably because the record is not saved yet).
If you are just trying to get the user that executed the action that fired the plugin, use context.InitiatingUserId. You could also look into the documentation for the WhoAmI request.
Hope that helps!

(Windows Phone 10) Is possible to edit, add new contact programmatically in windows phone 10?

I want to implement function edit and add contact programatically in windows phone 10.
Is it possible? Has any sample about it ?
Here is a code snippet for creating the contact:
public async Task AddContact(String FirstName, String LastName)
{
var contact = new Windows.ApplicationModel.Contacts.Contact();
contact.FirstName = FirstName;
contact.LastName = LastName;
//Here you can set other properties...
//Get he contact store for the app (so no lists from outlook and other stuff will be in the returned lists..)
var contactstore = await Windows.ApplicationModel.Contacts.ContactManager.RequestStoreAsync(Windows.ApplicationModel.Contacts.ContactStoreAccessType.AppContactsReadWrite);
try
{
var contactLists = await contactstore.FindContactListsAsync();
Windows.ApplicationModel.Contacts.ContactList contactList;
//if there is no contact list we create one
if (contactLists.Count == 0)
{
contactList = await contactstore.CreateContactListAsync("MyList");
}
//otherwise if there is one then we reuse it
else
{
contactList = contactLists.FirstOrDefault();
}
await contactList.SaveContactAsync(contact);
}
catch
{
//Handle it properly...
}
}
And here is a short sample for changing an existing contact:
//you can obviusly couple the changes better then this... this is just to show the basics
public async Task ChangeContact(Windows.ApplicationModel.Contacts.Contact ContactToChange, String NewFirstName, String NewLastName)
{
var contactStore = await Windows.ApplicationModel.Contacts.ContactManager.RequestStoreAsync(Windows.ApplicationModel.Contacts.ContactStoreAccessType.AppContactsReadWrite);
var contactList = await contactStore.GetContactListAsync(ContactToChange.ContactListId);
var contact = await contactList.GetContactAsync(ContactToChange.Id);
contact.FirstName = NewFirstName;
contact.LastName = NewLastName;
await contactList.SaveContactAsync(contact);
}
And very important:
In the appxmanifest you have to add the contacts capability. Right click to it in the solution explorer and "View Code" and then under Capabilities put
<uap:Capability Name="contacts" />
There is no UI for this. See this.
Both samples are meant to be for starting point... obviously it's not production ready and you have to adapt it to your scenario.
Update
Since this came up in the comments I extend my answer a little bit.
Based on this (plus my own experimentation) the ContactListId for aggregated contacts is null (which makes sense if you think about it). Here is how to get the raw contact with ContactlLstId (code is based on the comment from the link)
public async Task IterateThroughContactsForContactListId()
{
ContactStore allAccessStore = await ContactManager.RequestStoreAsync(ContactStoreAccessType.AllContactsReadOnly);
var contacts = await allAccessStore.FindContactsAsync();
foreach (var contact in contacts)
{
//process aggregated contacts
if (contact.IsAggregate)
{
//here contact.ContactListId is "" (null....)
//in this case if you need the the ContactListId then you need to iterate through the raw contacts
var rawContacts = await allAccessStore.AggregateContactManager.FindRawContactsAsync(contact);
foreach (var rawContact in rawContacts)
{
//Here you should have ContactListId
Debug.WriteLine($"aggregated, name: {rawContact.DisplayName }, ContactListId: {rawContact.ContactListId}");
}
}
else //not aggregated contacts should work
{
Debug.WriteLine($"not aggregated, name: {contact.DisplayName }, ContactListId: {contact.ContactListId}");
}
}
}
And another important thing:
According to the documentation you won’t be able to change all the contacts which are created by other apps.
AllContactsReadWrite:
Read and write access to all app and system contacts. This value is
not available to all apps. Your developer account must be specially
provisioned by Microsoft in order to request this level of access.
In some cases, I get a System.UnauthorizedAccessException when SaveContactAsync(contact) is called. One example for this was when the contact was in the Skype Contact List.

Refresh MVC View

I have a little app that initially requests a user id. This user id is then sent as a parameter to a stored procedure that returns values from a database. What I would like for this app to do is to refresh those same values every 30 seconds. My issue is that when I refresh, I lose the user id. Is there something simple that I'm missing here?
public ActionResult Report()
{
string operatorCode = Request.Form.GetValues("txtOperator")[0].ToString();
ViewBag.operatorName = (from e in db.employees
where e.operator_code == operatorCode
select e.name).Max().ToString();
ViewData["operatorCode"] = operatorCode;
var results = db.lex_sp_Select_Paintline_FinRew_Operator(operatorCode);
Response.AddHeader("Refresh", "10");
return View(results.ToList());
}
I think the main reason for the null value is due to the fact that you are trying to refresh an HttpPost, rather than a request (the refresh header is not intended for POSTS). I'd suggest as an alternative, that you change your process to be a request, which would result in only needing to change the invoking code (to a get) and changing the Report action to:
string operatorCode = Request.QueryString["txtOperator"];
this should give you the desired result, tho at the expense of the action now being a get rather than a post. You could also store the operatorCode in Session (tho this may not scale very well). The final option that I can see, would be to run an ajax request on a setInterval() and use that process to send a POST to the controller action.
How about storing in temp session and then using it from there when you lost it?
string operatorCode = Request.Form.GetValues("txtOperator")[0].ToString();
TempData["operatorCode"] = operatorCode;
if (!String.IsNullOrEmpty(operatorCode))
{
TempData["operatorCode"] = operatorCode;
ViewBag.operatorName = (from e in db.employees
where e.operator_code == operatorCode
select e.name).Max().ToString();
ViewData["operatorCode"] = operatorCode;
var results = db.lex_sp_Select_Paintline_FinRew_Operator(operatorCode);
Response.AddHeader("Refresh", "10");
return View(results.ToList());
}
else
{
var tempCode = TempData["operatorCode"]
ViewData["operatorCode"] = tempCode;
var results = db.lex_sp_Select_Paintline_FinRew_Operator(tempCode);
Response.AddHeader("Refresh", "10");
return View(results.ToList());
}

PrepareResponse().AsActionResult() throws unsupported exception DotNetOpenAuth CTP

Currently I'm developing an OAuth2 authorization server using DotNetOpenAuth CTP version. My authorization server is in asp.net MVC3, and it's based on the sample provided by the library. Everything works fine until the app reaches the point where the user authorizes the consumer client.
There's an action inside my OAuth controller which takes care of the authorization process, and is very similar to the equivalent action in the sample:
[Authorize, HttpPost, ValidateAntiForgeryToken]
public ActionResult AuthorizeResponse(bool isApproved)
{
var pendingRequest = this.authorizationServer.ReadAuthorizationRequest();
if (pendingRequest == null)
{
throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
}
IDirectedProtocolMessage response;
if (isApproved)
{
var client = MvcApplication.DataContext.Clients.First(c => c.ClientIdentifier == pendingRequest.ClientIdentifier);
client.ClientAuthorizations.Add(
new ClientAuthorization
{
Scope = OAuthUtilities.JoinScopes(pendingRequest.Scope),
User = MvcApplication.LoggedInUser,
CreatedOn = DateTime.UtcNow,
});
MvcApplication.DataContext.SaveChanges();
response = this.authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, User.Identity.Name);
}
else
{
response = this.authorizationServer.PrepareRejectAuthorizationRequest(pendingRequest);
}
return this.authorizationServer.Channel.PrepareResponse(response).AsActionResult();
}
Everytime the program reaches this line:
this.authorizationServer.Channel.PrepareResponse(response).AsActionResult();
The system throws an exception which I have researched with no success. The exception is the following:
Only parameterless constructors and initializers are supported in LINQ to Entities.
The stack trace: http://pastebin.com/TibCax2t
The only thing I've done differently from the sample is that I used entity framework's code first approach, an I think the sample was done using a designer which autogenerated the entities.
Thank you in advance.
If you started from the example, the problem Andrew is talking about stays in DatabaseKeyNonceStore.cs. The exception is raised by one on these two methods:
public CryptoKey GetKey(string bucket, string handle) {
// It is critical that this lookup be case-sensitive, which can only be configured at the database.
var matches = from key in MvcApplication.DataContext.SymmetricCryptoKeys
where key.Bucket == bucket && key.Handle == handle
select new CryptoKey(key.Secret, key.ExpiresUtc.AsUtc());
return matches.FirstOrDefault();
}
public IEnumerable<KeyValuePair<string, CryptoKey>> GetKeys(string bucket) {
return from key in MvcApplication.DataContext.SymmetricCryptoKeys
where key.Bucket == bucket
orderby key.ExpiresUtc descending
select new KeyValuePair<string, CryptoKey>(key.Handle, new CryptoKey(key.Secret, key.ExpiresUtc.AsUtc()));
}
I've resolved moving initializations outside of the query:
public CryptoKey GetKey(string bucket, string handle) {
// It is critical that this lookup be case-sensitive, which can only be configured at the database.
var matches = from key in db.SymmetricCryptoKeys
where key.Bucket == bucket && key.Handle == handle
select key;
var match = matches.FirstOrDefault();
CryptoKey ck = new CryptoKey(match.Secret, match.ExpiresUtc.AsUtc());
return ck;
}
public IEnumerable<KeyValuePair<string, CryptoKey>> GetKeys(string bucket) {
var matches = from key in db.SymmetricCryptoKeys
where key.Bucket == bucket
orderby key.ExpiresUtc descending
select key;
List<KeyValuePair<string, CryptoKey>> en = new List<KeyValuePair<string, CryptoKey>>();
foreach (var key in matches)
en.Add(new KeyValuePair<string, CryptoKey>(key.Handle, new CryptoKey(key.Secret, key.ExpiresUtc.AsUtc())));
return en.AsEnumerable<KeyValuePair<string,CryptoKey>>();
}
I'm not sure that this is the best way, but it works!
It looks like your ICryptoKeyStore implementation may be attempting to store CryptoKey directly, but it's not a class that is compatible with the Entity framework (due to not have a public default constructor). Instead, define your own entity class for storing the data in CryptoKey and your ICryptoKeyStore is responsible to transition between the two data types for persistence and retrieval.

Resources