Unable to retrieve new customer from MYOB SDK - c#

I am trying something like
customer.Uid = Guid.NewGuid()
// set other properties
myCustomerService.Insert(myCompanyFile, myobCustomerContact, myCredentials );
myobCustomerContact = myCustomerService.Get(myCompanyFile, myobCustomerContact.UID,myCredentials);
The Get returns a 404 error.
What am I doing wrong?

You cannot currently control the UID used to insert a new entity; the API will create a new UID on insert for you.
When you use InsertAsync the task will return a string which is the full URI to the newly inserted entity. You can then retrieve the entity using
var location = await service.InsertAsync(cf, customer, credentials, ct);
var insertedEntity = await service.GetAsync(cf, new Uri(location), credentials, ct);
however if you want to insert and retrieve an inserted entity then you can use InsertExAsync e.g.
var insertEntity = await service.InsertExAsync(cf, customer, credentials, ct);

Related

FirebaseAuthentication.net package in Xamarin Forms - get current user UID

In my Xamarin.Forms project, I saw that the FirebaseAuthentication.Net package can be used for the cross-platform project. How would I get the current user's UID with this? I have figured out how to get the current user's email by saving the firebase refresh token and using NewtonSoft.JSON, but am not sure how to do this with the id. I want to be able to do this so that I can store the user's data in the database under their uid and retrieve it that way.
Here's what I have so far for getting the email address of the current user:
var authProvider = new FirebaseAuthProvider(new FirebaseConfig(WebAPIKey));
var savedfirebaseauth = JsonConvert.DeserializeObject<Firebase.Auth.FirebaseAuth>(Preferences.Get("FirebaseRefreshToken", ""));
var RefreshedContent = await authProvider.RefreshAuthAsync(savedfirebaseauth);
Preferences.Set("FirebaseRefreshToken", JsonConvert.SerializeObject(RefreshedContent));
string UsersEmailToDisplay = savedfirebaseauth.User.Email;
What I am storing as "FirebaseRefreshToken" is the following.
var auth = await authProvider.CreateUserWithEmailAndPasswordAsync(Email.Text, Password.Text);
var content = await auth.GetFreshAuthAsync();
var serializedcontent = JsonConvert.SerializeObject(content);
Please let me know if any more clarification of my question is needed.
I think you want to get the UserId which unique to the Firebase project.
You could try to call its LocalId after you sign in.
var authProvider = new FirebaseAuthProvider(new FirebaseConfig(""));
var auth = await authProvider.SignInWithOAuthAsync(authType, accessToken);
var uid = auth.User.LocalId;

Extracting ListItems from a List in a SharePoint Site

I am trying to extract a list of items in a SharePoint Site below the root site at host.sharepoint.com/sites/mysite. I've tried a bunch of different methods, but only one seems to work:
var host = "host.sharepoint.com:/";
var siteName = "mysite";
var listName = "MyList";
// Generate the Client Connection
var graphHelper = new ApplicationAuthenticatedClient(ClientId, Tenant, ClientSecret);
await graphHelper.ConnectAsync().ConfigureAwait(false);
// Code: itemNotFound
//Message: The provided path does not exist, or does not represent a site
//var list = await graphHelper.GraphClient.Sites[$"{host}{siteName}"].Request().GetAsync();
// Returns a Site, no Lists.
//var list = await graphHelper.GraphClient.Sites[host].Sites[siteName].Request().GetAsync();
//Code: itemNotFound
//Message: The provided path does not exist, or does not represent a site
//var list = await graphHelper.GraphClient.Sites[host].Sites[siteName].Lists[listName].Request().GetAsync();
// List retrieved, but no Items
//var site = await graphHelper.GraphClient.Sites[host].Sites[siteName].Request().Expand("lists").GetAsync();
//var list = await graphHelper.GraphClient.Sites[site.Id].Lists[listName].Request().Expand("Items").GetAsync();
//Code: invalidRequest
//Message: Can only provide expand and select for expand options
//var queryOptions = new List<QueryOption>() { new QueryOption("expand", "fields") };
// This works
var site = await graphHelper.GraphClient.Sites[host].Sites[siteName].Request().GetAsync();
var list = await graphHelper.GraphClient.Sites[site.Id].Lists[listName].Items.Request().Expand("Fields").GetAsync();
I've finally managed to get it to connect, but I'm wondering if there's a better way to navigate to the list, rather than the two API calls? (Assuming that I don't know the Site ID beforehand)
Edit: Using the Graph Explorer, I can access the items using https://graph.microsoft.com/v1.0/sites/{host}.sharepoint.com:/sites/{siteName}:/lists/{listName}/items?expand=fields, but I don't know how to (or if) access that API call in a single call in the .NET API.
It appears that I was on the right track with var list = await graphHelper.GraphClient.Sites[$"{host}{siteName}"].Request().GetAsync(); but the URI was not formatted correctly.
The correct Site ID for https://host.sharepoint.com/sites/mysite/MyList is:
Sites[host.sharepoint.com:/sites/mysite:"]
Retrieving the list from the code in my original question would look like this:
var host = "host.sharepoint.com";
var siteName = "mysite";
var listName = "MyList";
// Generate the Client Connection
var graphHelper = new ApplicationAuthenticatedClient(ClientId, Tenant, ClientSecret);
await graphHelper.ConnectAsync().ConfigureAwait(false);
var list = await graphHelper.GraphClient.Sites[$"{host}:/sites/{siteName}:"].Lists[listName].Request().GetAsync();
it's possible in one API call.
GET https://graph.microsoft.com/v1.0/sites/{host}.sharepoint.com:/sites/{siteName}:/lists/{listTitle}/items?$expand=Fields

Is it possible to get user email from MS Teams with a Bot using SDK4?

I'm using C# and Bot Framework SDK4 and need to get the user email from a 1:1 chat with my bot. Is it possible? All I can seem to get is ID and full name.
I have tried the things listed here https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/bots/bots-context
but the teamsContext is just returning null.
ITeamsContext teamsContext = turnContext.TurnState.Get<ITeamsContext>();
string incomingTeamId = teamsContext.Team.Id;
string incomingChannelid = teamsContext.Channel.Id;
string incomingTenantId = teamsContext.Tenant.Id;
So is it even possible to get the user email from the current user chatting with the bot?
You can! Per the docs, you just do the same as if you were getting the team roster, but use the conversation id, instead. For example:
var credentials = new MicrosoftAppCredentials("<yourAppId>", "<yourAppPassword>");
var connector = new ConnectorClient(new Uri(turnContext.Activity.ServiceUrl), credentials);
var conversationId = turnContext.Activity.Conversation.Id;
var userInfo = await connector.Conversations.GetConversationMembersAsync(conversationId );
Note: I tried using the Microsoft.Bot.Connector.Teams package to do this, but couldn't get it to work. Had to use the connector method above.
Private async Task GetUserProfile(TurnContext context,CancellationToken cancellationToken)
{
BotFrameworkAdapter botAdapter = (BotFrameworkAdapter)context.Adapter;
var conversation = await botAdapter.GetConversationMembersAsync(context, cancellationToken);
}
You can visit - How get user email from MS Teams with a Bot using SDK4?

C# .NET core Best way to get current user ID

I have a lot of tables in my database that use a user's identity User.Id as a foreign key. Now, in a lot of the requests I need to do the below lines it seems just in case the User is null (even if I add [Authorise] filter to the function).
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
ViewBag.ErrorCode = "1201";
ViewBag.ErrorMsg = "User not found";
return View("HandledError");
}
var userId = user.Id;
Does anyone know the best way I can access this without copying this same code for each function?
I guess I could have a function that retrieves the Id... and throws an exception on Null.. but then I would still need to write it in a try catch everytime anyway....
Any ideas?
User id is a claim. You can get it via:
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
Note: You'll need to add a using for System.Security.Claims.
In WebApi 2 you can use RequestContext.Principal from within a method on ApiController
string id;
id = User.Identity.GetUserId();
id = RequestContext.Principal.Identity.GetUserId();

Search for user in Azure Active directory group using graph api

I would like to have some kind of people picker functionality with auto complete features in my asp.net mvc 5 app to search for a user in a specific Azure AD group. It's a demo "todo app" that allows to assign a todo to a user that is member of a the group.
I tried with both the Graph API directly and the Azure Graph Client library but I don't seem to find a way to achieve what I want. The graph api allows to get the members of a group but adding filter "startswith" fails as when adding the filter the api returns only directory object which don't include for example DisplayName property... the client library doesn't help much either except for the batch functionality which offers a way but with a lot of overhead... I then would have to get a filtered resultset of user regardless of group membership (using User List stuff in the api), all members of the group and then fish out using Linq the correct result set.... would work fine for dev/testing but in production with a couple of hundred users this would be insane...
Any ideas or suggestions would be much appreciated. Thanks!
EDIT
Below my code that is called from client side Javascript to search for user;
AccessGroupId is the Azure AD group used to authorize users. Only
members of this group can access the web app which I handle in custom
OWin Middleware
The method is intented to be used to find a user in that group
Code works fine as below only there is no filtering applied which is the intentaion with the input parameter pre (which comes from a textbox in the ui). I get all the members of the access group.
public async Task<JsonResult> FindUser(string pre)
{
string AccessGroupId = ConfigurationManager.AppSettings["AccessGroupId"];
AuthenticationContext authCtx = new AuthenticationContext(String.Format(CultureInfo.InvariantCulture, "{0}/{1}", SecurityConfiguration.LoginUrl, SecurityConfiguration.Tenant));
ClientCredential credential = new ClientCredential(SecurityConfiguration.ClientId, SecurityConfiguration.AppKey);
AuthenticationResult assertionCredential = await authCtx.AcquireTokenAsync(SecurityConfiguration.GraphUrl, credential);
var accessToken = assertionCredential.AccessToken;
var graphUrl = string.Format("https://graph.windows.net/mytenant.onmicrosoft.com/groups/{0}/members?api-version=2013-11-08, AccessGroupId );
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, graphUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
HttpResponseMessage response = await client.SendAsync(request);
String responseString = await response.Content.ReadAsStringAsync();
JObject jsonReponse = JObject.Parse(responseString);
var l = from r in jsonReponse["value"].Children()
select new
{
UserObjectId = r["objectId"].ToString(),
UserPrincipalName = r["userPrincipalName"].ToString(),
DisplayName = r["displayName"].ToString()
};
//users = Newtonsoft.Json.JsonConvert.DeserializeObject<List<User>>(responseString);
return Json(l, JsonRequestBehavior.AllowGet);
}
When I add a filter to the same api call instead of returning the members (users, groups and/or contacts), it returns directory objects (that doesn't have displayName) which are not really usefull in the above code, unless I would query the api again (in batch) to retrieve the users displayname but that looks like a lot of overhead to me.
var graphUrl = string.Format("https://graph.windows.net/mytenant.onmicrosoft.com/groups/{0}/members?api-version=2013-11-08&$filter=startswith(displayName,'{1}')", AccessGroupId, pre);
I'd highlight two possible approaches:
Execute requests to Graph API using a custom JS library.
You'd need still need to care for accesstokens and have a look at ADAL.js
A sample app (not finalized as of this writing) available at:
AzureADSamples WebApp-GroupClaims-DotNet
Have a look at AadPickerLibrary.js
Try using ActiveDirectoryClient
It would look something like:
public async Task<JsonResult> FindUser(string pre) {
ActiveDirectoryClient client = AADHelper.GetActiveDirectoryClient();
IPagedCollection<IUser> pagedCollection = await client.Users.Where(u => u.UserPrincipalName.StartsWith(pre, StringComparison.CurrentCultureIgnoreCase)).ExecuteAsync();
if (pagedCollection != null)
{
do
{
List<IUser> usersList = pagedCollection.CurrentPage.ToList();
foreach (IUser user in usersList)
{
userList.Add((User)user);
}
pagedCollection = await pagedCollection.GetNextPageAsync();
} while (pagedCollection != null);
}
return Json(userList, JsonRequestBehavior.AllowGet);
}
More detailed sample is available at:
AzureADSamples WebApp-GraphAPI-DotNet

Categories

Resources