Get current user language using javascript - dynamics-crm-2011

In CRM 2011 it's easy to get current user language using javascript, using the following code:
Xrm.Page.context.getUserLcid();
Is there anyway to do the same in server side using plugins ?
Thanks and best regards

Here is a sample in a Plugin:
class GetUserLanguage : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
//PluginSetup abstracts setup code: http://nicknow.net/dynamics-crm-2011-abstracting-plugin-setup/
var p = new PluginSetup(serviceProvider);
var user = p.Context.InitiatingUserId;
var lcid = RetrieveUserUiLanguageCode(p.Service, user);
}
//From the SDK: http://msdn.microsoft.com/en-us/library/hh670609.aspx
private static int RetrieveUserUiLanguageCode(IOrganizationService service, Guid userId)
{
var userSettingsQuery = new QueryExpression("usersettings");
userSettingsQuery.ColumnSet.AddColumns("uilanguageid", "systemuserid");
userSettingsQuery.Criteria.AddCondition("systemuserid", ConditionOperator.Equal, userId);
var userSettings = service.RetrieveMultiple(userSettingsQuery);
if (userSettings.Entities.Count > 0)
{
return (int)userSettings.Entities[0]["uilanguageid"];
}
return 0;
}
}

There are a couple options for it that I've used before.
Use a Retrieve on the systemuser entity using the userid from the plugin execution context. Don't forget to set the column set to just get the user! Otherwise systemuser can be a hefty retrieve for online envs.
Issue a WhoAmI request to the server.
I personally use the former because Retrieves are very common for devs who use plugins, but not all are familiar with the WhoAmI message (it derives from retrieve: http://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.whoamirequest.aspx)
Unfortunately I have not found a way to get it without issuing a request to the server. Let me know if this helps!
Nick

I think that once the user selects a preferred locale you can pick it up using:
Thread.CurrentUICulture.LCID

Related

Get Receipt number on Stripe C#

Please how can I get the receipt number on Stripe with c#
My image :
https://www.casimages.com/i/191231053006538388.png.html
Maybe with a Session ID ?
You'd access the Charge object and it's a field on that resource.
You say you're using Checkout. So the Charge is under session.payment_intent.charges.data[0]. It requires a little digging to get it but it's all there. I'd suggest that when you receive the event as part of fulfilling the order etc, retrieve the Session(stripe.com/docs/api/checkout/sessions/retrieve) and expand "payment_intent". Then session.PaymentIntent.Charges.Data[0].ReceiptNumber is the value you're looking for.
static void CheckoutSessionReceiptEmail()
{
var service = new Stripe.Checkout.SessionService();
var session = service.Get(
"cs_test_nHUZtpUvaI80YAKGgCMGyeHfjQ6nMtUhVLeVpowWsgpfyGujccGxnAuJ",
new Stripe.Checkout.SessionGetOptions
{
Expand = new List<string> { "payment_intent" }
}
);
Console.WriteLine(session.PaymentIntent.Charges.Data[0].ReceiptNumber);
}

How to get the names and ids of test cases that are under the Tested By section of a user story in tfs

Tested BY(19)
Under tested by there are 19 test cases.
If the id of the user story is given how to get these test cases.
If (Link link is Related) returns all the links.
How to get just the test cases.
Any help would be appreciated. I just started working with tfs using c#
You could use TFS REST API to get the information you need, the Microsoft.VSTS.Common.TestedBy-Forward relation is the TestedBy link type. The API is as below:
GET https://{account}.visualstudio.com/{project}/_apis/wit/workitems/{id}?$expand=Relations&api-version=5.0-preview.3
The following screenshot is the response of the REST API:
Here is a sample with client library to get test case ids from the User Story for your reference:
using System;
using Microsoft.VisualStudio.Services.Client;
using Microsoft.VisualStudio.Services.WebApi;
using Microsoft.TeamFoundation.WorkItemTracking.WebApi;
using Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models;
namespace GetWorkItemFullyExpanded
{
class Program
{
static void Main(string[] args)
{
GetWorkItemFullyExpanded();
}
public static WorkItem GetWorkItemFullyExpanded()
{
int id = xx;
var myCredentials = new VssClientCredentials();
var connection = new VssConnection(new Uri(#"https://xxxx.visualstudio.com"), myCredentials);
WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>();
WorkItem workitem = workItemTrackingClient.GetWorkItemAsync(id, expand: WorkItemExpand.Relations).Result;
Console.WriteLine(workitem.Id);
Console.WriteLine("Relations: ");
foreach (var relation in workitem.Relations)
{
if (relation.Rel == "Microsoft.VSTS.Common.TestedBy-Forward")
Console.WriteLine(relation.Url);
}
return workitem;
}
}
}

How to stop 'Send order notification' & 'Send payment notification' in checkout process from code side in kentico

I know there is option in kentico admin setting to stop the sending notification email. but I want to check this in the code for my customization. so could you please suggest me where should I get the code in kentico.
Setting in kentico
Please refer to the official documentation.
You need to use SettingsKeyInfoProvider:
SettingsKeyInfoProvider.SetValue("CMSSettingName", "SiteName", value);
Leave out the site name parameter if you want to set it globally.
The settings names you are looking for are CMSStoreSendOrderNotification and CMSStoreSendPaymentNotification.
You can find more settings by querying the DB:
SELECT * FROM [CMS_SettingsKey] where keyname like '%cmsstoresend%'
If you are looking to intercept an action when a notification is being sent, you can use Global events for the EmailInfo object like this:
[assembly: RegisterModule(typeof(GlobalEventsModule))]
public class GlobalEventsModule : Module
{
public GlobalEventsModule() : base (typeof(GlobalEventsModule).Name)
{
}
protected override void OnInit()
{
base.OnInit();
EmailInfo.TYPEINFO.Events.Insert.Before += Insert_Before;
}
private void Insert_Before(object sender, ObjectEventArgs e)
{
// executed before an e-mail is inserted into DB
var email = (EmailInfo)e.Object;
}
}
To cancel the execution in code you can call Cancel() method (although you might get exceptions in this case - you have to test for yourself in your scenario):
private void Insert_Before(object sender, ObjectEventArgs e)
{
var email = (EmailInfo)e.Object;
e.Cancel();
}
This will also work only if you are using Email queue (which is highly recommended anyway) and will be executed for all outgoing e-mails, not just notifications.
Using the CMS.Ecommerce library you can check these settings through the API
SiteInfoIdentifier sii = new SiteInfoIdentifier(SiteContext.CurrentSiteID);
bool sendOrderNotificationEmail = CMS.Ecommerce.ECommerceSettings.SendOrderNotification(sii);
If you wanted to set them programmatically you would have to use the SettingsKeyInfoProvider
SettingsKeyInfoProvider.SetValue("CMSStoreSendOrderNotification ", false);

Create a Custom Login page for logged in Users with Mvc5 Identity?

I am trying to find a guide or something that can teach me to make a view that users navigate to when they login. The view should show profile properties like firstname,lastname, and additional custom data. The problem is I dont know how to send the id from login to a another view. In other words when this succeeds in AccountController...
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
// return RedirectToAction("Customer", "Account");
... I want to send id to another view. I tried make a view like so:
public ActionResult Customer(string userId)
{
ApplicationDbContext _context = new ApplicationDbContext();
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));
var ThisUser = UserManager.FindById(User.Identity.GetUserId());
//string a = Convert.ToString(User.Identity.GetUserId());
//RegisterViewModel RVM = db.RegisterViewModels.Find(a);
return View(ThisUser);
}
It did not work. Any suggestions?
There is a lot of information to found about ASP.NET Identity on the web, in particular Microsoft's own documentation is really good. Check this out for a starter for some great examples.

ServiceStack adding roles and permissions with custom AuthUserSession

I'm trying to add roles and permissions when a new user is registered. I'm running into the problem that adding to the session roles and permissions does not get persisted to the database.
I've written a Custom AuthUserSession and overridden OnAuthenticated.
The code below uses the AssignRolesService, and that seems like it would be exactly what I need except for one problem. When the authentication is handled by Facebook auth provider session.UserAuthName is null so I can't call the service.
To clarify, all code snippets below are contained within:
public override void OnAuthenticated(IServiceBase authService, IAuthSession session,
IOAuthTokens tokens, Dictionary<string, string> authInfo)
The suggested way of doing this (from what I found on SO/Google):
using (var assignRoles = authService.ResolveService<AssignRolesService>())
{
assignRoles.Post(new AssignRoles {
UserName = session.UserAuthName,
Roles = { RoleNames.Admin }
});
}
Also tried this but it did not work:
session.Roles.Add("user");
session.Permissions.Add("setup");
authService.SaveSession(session);
The only thing that I found that seems to work, but seems like a hack is:
UserAuth ua = db.GetById<UserAuth>(session.UserAuthId);
ua.UserName = user.Email;
ua.Roles.Add("user");
ua.Permissions.Add("setup");
db.Save(ua);
Hi I just figured it out!
if just by a a coincidence you're using LoadUserInfo that have a try / catch when you are trying to assign the values, hiding a null reference exception and doing the redirect without doing a re-throw
that got fixed just by creating a new List like this:
userSession.Roles = new List<string> {"your-role-here"};

Resources