How to get via Organisation service for Microsoft Dynamics the OptionSet value and Formatted value in different languages? - asp.net-mvc

I have a custom .NET application to query and managing data on a Microsoft Dynamics CRM instance.
This application is multilingual and the user can change via a language switch the language of the application.
For the connection and actions I'm using the OrganizationService and CRMServiceClient from Microsoft.Xrm.Sdk. This is combined with dependency injection to pass the connection to our different classes.
With Ninject this bindings look like
Bind().To().WithConstructArgument("crmConnectionString","the connection string");
Querying and updating the data in Dynamics is working but we are not able to retrieve the OptionSet values and Formatted values in the language the visitor have selected in the custom app. This is always in the same language even when we change the culture for the Thread before we call Dynamics.
How can we pass the current language / culture to the OrganizationService so that it knows in what language it have to retrieve the fields?
Someone told me that this is based on the account used to connect to the CRM. So if that's indeed the case then it means that if we have 5 languages that we need to have 5 connection strings and 5 OrgnaizationService instances that need to be called. How should I handle this in a good way in that case?
Thanks for your answers

The solution I implemented was to use CallerId.
Before returning the client I fill the CallerId with a Guid.
The Guid is from a user configured with a specific language in Dynamics.
Based on the language I take a different user.

I don't know if you can pass a culture to the OrganizationService, and I think having different connection strings would work if you want to go this route.
However, you can query the CRM to retrieve the localized labels for the option set you want, as described here.
To sum it up, it's using a RetrieveAttributeRequest, passing the entity logical name and field name and looping trough the result to get the labels.
var request = new RetrieveAttributeRequest
{
EntityLogicalName = "incident",
LogicalName = "casetypecode"
};
var response = organizationService.Execute(request) as RetrieveAttributeResponse;
var optionSetAttributeMetadata = response.AttributeMetadata as EnumAttributeMetadata;
foreach (var option in optionSetAttributeMetadata.OptionSet.Options)
{
Console.WriteLine($"Localized labels for option {option.Value}:");
foreach (var locLabel in option.Label.LocalizedLabels)
{
Console.WriteLine($"Language {locLabel.LanguageCode}: {locLabel.Label}");
}
Console.WriteLine($"Localized description for option {option.Value}:");
foreach (var locLabel in option.Description.LocalizedLabels)
{
Console.WriteLine($"Language {locLabel.LanguageCode}: {locLabel.Label}");
}
}
The code in the link also add caching of already retrieved values, so that you only query the CRM once per option set.

Related

How to integrate Power BI in a Delphi desktop application

Has anyone integrated Microsoft Power BI into a Delphi application. I beleive that I will need to embed a webpage into a form,I am ok with that, however I cant see how you force a refresh or feed Power BI the run-time selection criteria.
It will be linked to a standard SQL Server database (not cloud based at the moment). I have the graph I want working on Power BI desktop.
I'm integrating it in WPF C# application. It's pretty much the same as in Delphi, but easier due to availability of ADAL library for C#.
If you want to display a report (or tile, or dashboard) based on the current selection from your application, you must provide this information to the report. You can save the selection to a table in the database (or information about the selection, like primary key values) and build the report on this table. Put a session column in it, and on every save generate an unique session ID value. Then filter the report to show only data for your session.
To filter the embedded report, define a filter and assign it to filters property of the embed configuration object, that you are passing to the JavaScript Power BI Client, or call report.setFilters method. In your case, IBasicFilter is enough. Construct it like this:
const basicFilter: pbi.models.IBasicFilter = {
$schema: "http://powerbi.com/product/schema#basic",
target: {
table: "ReportTempTableName",
column: "SessionId"
},
operator: "In",
values: [12345],
filterType: 1 // pbi.models.FilterType.BasicFilter
}
replacing 12345 with the unique session ID value, that you want to visualize.
To avoid the possibility the user to remove the applied filter and see the data for all sessions, you may hide the filter pane:
var embedConfig = {
...
settings: {
filterPaneEnabled: false
}
};

What is the difference between new sap.ui.model.odata.ODataModel and read?

I am playing around with a OData service and I am very confused when to use this
var oModel = new sap.ui.model.odata.ODataModel("proxy/http/services.odata.org/V3/(S(k42qhed3hw4zgjxfnhivnmes))/OData/OData.svc");
this.getView().setModel(oModel);
vs
var oModel = new sap.ui.model.odata.ODataModel("odatserviceurl", true);
var productsModel = new JSONModel();
oModel.read("/Products",
null,
null,
false,
function _OnSuccess(oData, response) {
var data = { "ProductCollection" : oData.results };
productsModel.setData(data);
},
function _OnError(error) {
console.log(error);
}
);
this.getView().setModel(productsModel);
I have two working example using both approach but I am not able to figure out why using read method if I can achieve same with first version. Please explain or guide me to the documentation which can clear my confusion.
Ok, lets start with the models:
JSON Model : The JSON model is a client-side model and, therefore, intended for small datasets, which are completely available on the client. The JSON model supports two-way binding. NOTE: no server side call is made on filtering, searching, refresh.
OData Model : The OData model is a server-side model: the dataset is only available on the server and the client only knows the currently visible rows and fields. This also means that sorting and filtering on the client is not possible. For this, the client has to send a request to the server. Meaning searching/filtering calls odata service again.
Now, lets look at scenarios where we will use these models:
Scenario 1: Showing data to user in a list/table/display form. Data manipulation is limited to searching and filtering. Here, I would use oData model directly to controls as only fetching of data is required.( your method 1) (NOTE: One way binding). Remember here all changes require a call to server.
Scenario 2: I have an application which has multiple inputs, user can edit changes, also some fields are calculated and mandatory. All in all, many user changes are done which may be temporary and user might not want to save them. Here, you dont want to send these temporary changes to backend as yet. You way want to manipulate, validate data before sending. Here, we will use JSON Model after reading data from odata model ( your method 2). Store the changes in local JSON model, validate and manipulate them and finally send the data using Odata create/update. Remember here all changes DO NOT require a call to server as data is present in local JSON MODEL.
Let me know if this helps you. :)
EDIT : Additional Information :
As per your comment :
Documentation says oModel.read' trigger get request but new sap.ui.model.odata.ODataModel("proxy/http/services.odata.org‌​/V3/(S(k42qhed3hw4zg‌​jxfnhivnmes))/OData/‌​OData.svc")` does the same thing so why and when to use oModel.read
Here, is where you misunderstood. The code
new sap.ui.model.odata.ODataModel("proxy/http/services.odata.org‌​/V3/(S(k42qhed3hw4zg‌​jxfnhivnmes))/OData/‌​OData.svc") will NOT send a read/get Request. It calls the odata services and fetches the metadata of the service. A service can have multiple entities.
For example: the service :http://services.odata.org/Northwind/Northwind.svc/ has mutiple entity sets such as Categories, Customers, Employees etc. So, when I declare : new sap.ui.model.odata.ODataModel("http://services.odata.org/Northwind/Northwind.svc/") it will fetch the metadata for service (not actual data). Only when you call the desired entity set, it will fetch the data. The Entity set is specified :
When you call the read method ( like you have specified '/Products')
Bind the entity set name directly to control like to List,Table etc ( items='{/Products}' )

How to move from untyped DataSets to POCO\LINQ2SQL in legacy application

Good day!
I've a legacy application where data access layer consists of classes where queries are done using SqlConnection/SqlCommand and results are passed to upper layers wrapped in untyped DataSets/DataTable.
Now I'm working on integrating this application into newer one where written in ASP.NET MVC 2 where LINQ2SQL is used for data access. I don't want to rewrite fancy logic of generating complex queries that are passed to SqlConnection/SqlCommand in LINQ2SQL (and don't have permission to do this), but I'd like to have result of these queries as strong-typed objects collection instead of untyped DataSets/DataTable.
The basic idea is to wrap old data access code in a nice-looking from ASP.NET MVC "Model".
What is the fast\easy way of doing this?
Additionally to the answer below here is a nice solution based on AutoMapper: http://elegantcode.com/2009/10/16/mapping-from-idatareaderidatarecord-with-automapper/
An approach that you could take is using the DataReader and transfer. So for every object you want to work with define the class in a data transfer object folder (or however your project is structured) then in you data access layer have something along the lines of the below.
We used something very similar to this in a project with a highly normalized database but in the code we did not need that normalization so we used procedures to put the data into more usable objects. If you need to be able to save these objects as well you will need handle translating the objects into database commands.
What is the fast\easy way of doing
this?
Depending on the number of classes etc this is could not be the fastest approach but it will allow you to use the objects very similarly to the Linq objects and depending on the type of collections used (IList, IEnumerable etc) you will be able to use the extension methods on those types of collections.
public IList<NewClass> LoadNewClasses(string abc)
{
List<NewClass> newClasses = new List<NewClass>();
using (DbCommand command = /* Get the command */)
{
// Add parameters
command.Parameters["#Abc"].Value = abc;
// Could also put the DataReader in a using block
IDataReader reader = /* Get Data Reader*/;
while (reader.Read())
{
NewClass newClass = new NewClass();
newClass.Id = (byte)reader["Id"];
newClass.Name = (string)reader["Name"];
newClasses.Add(newClass);
}
reader.Close();
}
return newClasses;
}

How to add / create Foul or bad language keyword filter in SharePoint Lists, Documents?

I am building an Internal social networking website on SharePoint. Since its a networking intranet, I want it to be Open and non moderated. However, I also dont want people to use abusive / Foul or bad language words in the portal.
I tried Googling and wasnt really sucessfull in finding a solution.
Microsoft Forefront will do that for me, but it only does for Documents. But I also want to do that on Lists since Discussion forum on the SharePoint is in a list format.
You may create site solution/list definition for your site using Visual studio Sharepoint Site Solution Genarator. Create a custom list and name it as you wish. I would name it "AbusiveWordList" in the following code example.
After creating site solution/list definition, Add below code in Item Adding function, which will iterate through all column in the list and will check from the custom list that is created named "AbusiveWordList". This list contains abusive words.
The chkbody function which will reference list item from custom list named "AbusiveWordList" and check if the bodytext contains item from AbusiveWordList.If yes, then it will throw an error.
*base.ItemAdding(properties);
foreach (DictionaryEntry
dictionaryEntry in
properties.AfterProperties) { string
bodytext = "";
bodytext = bodytext +
dictionaryEntry.Value;
finalwordcount = finalwordcount +
chkbody(bodytext, properties); }
if (finalwordcount > 0) {
properties.ErrorMessage = "Abusive /
Foul / Illicit information
found.Kindly refer to the terms and
conditions.";
properties.Cancel = true;
}
You will probably need to override any controls that display text to avoid this issue. As this would be a lot of work, perhaps an HTTP Module would be a better solution.
I've worked on a module that used regular expressions to make SharePoint's output XHTML compliant. Similarly, you could use regular expressions to strip out offensive words when a page is rendered. It wouldn't stop people typing them but as no-one would be able to see them this wouldn't matter. You could use a basic SharePoint custom list to store the offensive words you don't want displayed.

Code re-use with Linq-to-Sql - Creating 'generic' look-up tables

I'm working on an application at the moment in ASP.NET MVC which has a number of look-up tables, all of the form
LookUp {
Id
Text
}
As you can see, this just maps the Id to a textual value. These are used for things such as Colours. I now have a number of these, currently 6 and probably soon to be more.
I'm trying to put together an API that can be used via AJAX to allow the user to add/list/remove values from these lookup tables, so for example I could have something like:
http://example.com/Attributes/Colours/[List/Add/Delete]
My current problem is that clearly, regardless of which lookup table I'm using, everything else happens exactly the same. So really there should be no repetition of code whatsoever.
I currently have a custom route which points to an 'AttributeController', which figures out the attribute/look-up table in question based upon the URL (ie http://example.com/Attributes/Colours/List would want the 'Colours' table). I pass the attribute (Colours - a string) and the operation (List/Add/Delete), as well as any other parameters required (say "Red" if I want to add red to the list) back to my repository where the actual work is performed.
Things start getting messy here, as at the moment I've resorted to doing a switch/case on the attribute string, which can then grab the Linq-to-Sql entity corresponding to the particular lookup table. I find this pretty dirty though as I find myself having to write the same operations on each of the look-up entities, ugh!
What I'd really like to do is have some sort of mapping, which I could simply pass in the attribute name and get out some form of generic lookup object, which I could perform the desired operations on without having to care about type.
Is there some way to do this to my Linq-To-Sql entities? I've tried making them implement a basic interface (IAttribute), which simply specifies the Id/Text properties, however doing things like this fails:
System.Data.Linq.Table<IAttribute> table = GetAttribute("Colours");
As I cannot convert System.Data.Linq.Table<Colour> to System.Data.Linq.Table<IAttribute>.
Is there a way to make these look-up tables 'generic'?
Apologies that this is a bit of a brain-dump. There's surely imformation missing here, so just let me know if you'd like any further details. Cheers!
You have 2 options.
Use Expression Trees to dynamically create your lambda expression
Use Dynamic LINQ as detailed on Scott Gu's blog
I've looked at both options and have successfully implemented Expression Trees as my preferred approach.
Here's an example function that i created: (NOT TESTED)
private static bool ValueExists<T>(String Value) where T : class
{
ParameterExpression pe = Expression.Parameter(typeof(T), "p");
Expression value = Expression.Equal(Expression.Property(pe, "ColumnName"), Expression.Constant(Value));
Expression<Func<T, bool>> predicate = Expression.Lambda<Func<T, bool>>(value, pe);
return MyDataContext.GetTable<T>().Where(predicate).Count() > 0;
}
Instead of using a switch statement, you can use a lookup dictionary. This is psuedocode-ish, but this is one way to get your table in question. You'll have to manually maintain the dictionary, but it should be much easier than a switch.
It looks like the DataContext.GetTable() method could be the answer to your problem. You can get a table if you know the type of the linq entity that you want to operate upon.
Dictionary<string, Type> lookupDict = new Dictionary<string, Type>
{
"Colour", typeof(MatchingLinqEntity)
...
}
Type entityType = lookupDict[AttributeFromRouteValue];
YourDataContext db = new YourDataContext();
var entityTable = db.GetTable(entityType);
var entity = entityTable.Single(x => x.Id == IdFromRouteValue);
// or whatever operations you need
db.SubmitChanges()
The Suteki Shop project has some very slick work in it. You could look into their implementation of IRepository<T> and IRepositoryResolver for a generic repository pattern. This really works well with an IoC container, but you could create them manually with reflection if the performance is acceptable. I'd use this route if you have or can add an IoC container to the project. You need to make sure your IoC container supports open generics if you go this route, but I'm pretty sure all the major players do.

Resources