Pages

Wednesday, October 25, 2017

Solved: "No such interface supported" error when a Visual studio solution is opened


  • "No such interface supported"
  • "This project is under source control. This version of Visual Studio .NET does not support source controlled projects. Any changes that you make to this project will not be propagated to source control."

Visual studio 2012 throws an error "No such interface supported" when any of the following actions are performed:

  • Open Source control explorer from within Visual studio.
  • Open a solution bound to Source control
  • Add a solution to Source control.

In addition to this error message, when a solution bound to source control is opened, an error message "This project is under source control. This version of Visual Studio .NET does not support source controlled projects. Any changes that you make to this project will not be propagated to source control." pops up and the projects fail to load.

One of the reasons for this issue is that the config file "VersionControl.config" present in "C:\Users\YourName\AppData\Local\Microsoft\Team Foundation\4.0\Cache\" folder got corrupted.

In order to resolve this issue, close Visual studio, navigate to the folder and delete the config file. Start Visual studio and source control should work as expected.



Monday, April 24, 2017

Check public key token for a dll using powershell

Public key token for a dll can be checked using a simple command in PowerShell.

Open Windows PowerShell window.
Run the command "[system.reflection.assembly]::loadFile("DllPath").FullName

powershell command



Sunday, April 16, 2017

How to determine if a dll is built for 32-bit, 64bit or Any CPU

CorFlags.exe is part of the .NET Framework SDK. I have the development tools on my machine, and the simplest way for me determine whether a DLL is 32-bit only is to:

  • Open the Visual Studio Command Prompt (In Windows: menu Start/Programs/Microsoft Visual Studio/Visual Studio Tools/Visual Studio 2008 Command Prompt)
  • CD to the directory containing the DLL in question
  • Run corflags like this: corflags MyAssembly.dll
You will get output something like this:


   Microsoft (R) .NET Framework CorFlags Conversion Tool.  Version  3.5.21022.8
Copyright (c) Microsoft Corporation.  All rights reserved.
Version   : v2.0.50727
CLR Header: 2.5
PE        : PE32CorFlags  : 3
ILONLY    : 1
32BIT     : 1
Signed    : 0
The key is the "32BIT" flag as documented above: 1 = x86; 0 = Any CPU.
For x64 only the output would be (plus after 32): PE: PE32+

How to read connection string

 string connectionString = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;  

Make sure to add reference to System.configuration in your project.

Wednesday, April 12, 2017

How to open a file locked by other process

Trying to open a file which is being used by another process will result in an exception.

For example, when we try to open a word document opened and locked by other process, we will get an exception.

Here is the sample code that results in exception:
 using (FileStream fs = new FileStream(fileToUpload, FileMode.Open, FileAccess.Read))  
 {  
  fileContents = new Byte[fs.Length];  
  fs.Read(fileContents, 0, Convert.ToInt32(fs.Length));  
 }  

Inorder to resolve this,

we need to use another overload of the FileStream constructor.

Just add FileShare.ReadWrite to the parameters.
 using (FileStream fs = new FileStream(fileToUpload, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))  
 {  
 fileContents = new Byte[fs.Length];  
 fs.Read(fileContents, 0, Convert.ToInt32(fs.Length));  
 }  
This overload of the FileStream constructor allows to open a file in a non-exclusive mode.

Thursday, April 6, 2017

Error: A table, Extended Data Type, Base Enum or class called {TableName} already exists. Import of table aborted.

Sometimes during import of an xpo file, we might encounter the following error:

A table, Extended Data Type, Base Enum or class called {TableName} already exists. Import of table aborted.

This errors is a critical error and it stops the import of xpo.

REASON: In majority of cases this error is due to caching.

FIX: In order to resolve this, clear all cache files - .AUC files from the users AppData folder.

  • Close AX 2012 client
  • Browse to the folder "C:\Users\{userName}\AppData\Local (Windows 2012 Server)
  • Delete all AUC files
  • Start AX 2012 client and start import.

#Happy coding :)









Sunday, March 19, 2017

How to enable Google translation API

Google translation API can be enabled on a trial basis for a period of 30 days.
Here is how this can be achieved.

Navigate to https://cloud.google.com/translate/

Google translate home page




Select "Try it free" option.
Login with your google account.
Provide necessary details and fill the registration form.

It will take a few moments to create the project.

Let the page take its time to create project




Let it take its time. Once the project is created you should see something similar to the screen shot below

You are now signed up for 12 month free trial

Click on "GOT IT" to see the project dashboard.

Project dashboard


Click on API Manager from the menu. On the next page click on Enable API.

Enable API

This opens the API manager console. Click on "Translation API" from the list of APIs presented on the screen.
API manager console


The Google Cloud Translation API page opens up. Click "Enable" to enable the API.

Enable Google cloud translation API

Once the API is enabled, API configuration page opens up.

Translate API configuration page


Click on Quotas tab to check or edit the limits on the number of characters allowed per day and other similar parameters.
Quotas




Create credentials




From the left menu on the API manager console, select "Credentials" option. On the pop up window select"Create credentials" dropdown and select API Key.
API key option


You should now see a page with the API Key created.

Here is your free pass - API key

This key needs to be added as a query string value to every call that you make to this API.

Keep this key secured.

Tuesday, March 14, 2017

Use Google translation service in your application - C# Walk through

This walk through gives step by step instructions on how to create a class library to access Google Translation service.

In this walk through you will complete the following tasks:
  • Creation of Class Library project
  • Add code to access Google Translation service
  • Build the project and create a dll
  • Test the dll created
Lets start with creation of Class Library project:
  • Open Visual Studio
  • Create a new project
  • In the "New Project" window select "Class Library" template
  • For this project name the library as "GoogleTranslationLibrary"
  • Under location field, key in a location where you would like to save the project.
  • Checking the box "Create directory for solution" creates a folder for the solution within the selected location.
  • By default Visual Studio assumes the same name as Project name for solution. Lets leave as it is for this project.
New project window
New project window
  • Once the settings are done, you should see something like this in Solution Explorer window of Visual Studio:
Solution explorer
Solution explorer
  • Visual Studio creates a solution with one project "GoogleTranslationLibrary" within it.
  • Within the project a new class "Class1" is created. Rename the class "Class1.cs" to "Translator.cs". You should now see something similar in the "Translator.cs" code file.
code editor
Editor should look similar to this image
We are now done with the basics.

Lets now start with the real translation work.

Currently, Google is publishing its translation API using a translation web service.
Here is the URL for the web service.
https://www.googleapis.com/language/translate/v2

More information can be found at this URL:
https://cloud.google.com/translate/docs/translating-text

In order for this URL to work, a few query string parameters need to be supplied:

key : In order to access the REST service the user needs to register with Google API cloud service. Once the registration is done, the user needs to enable the translation API. After enabling the translation API Google provides the user with an API key. The API key obtained needs to be sent as a query string parameter.

source: The source language of the text (Example: en, fr, de and so on)

target: The target language - language in which the source text needs to be translated

q: The text that needs to be translated. The query string value with parameter name 'q' will be translated and the translated value will be sent as part of the response.

Example URL with query string:
https://translation.googleapis.com/language/translate/v2?key=YOUR_API_KEY&source=en&target=de&q=Hello%20world

YOUR_API_KEY in the above URL refers to API key obtained by the user after registering to the cloud service and enabling the translation API.

Lets start using this service Url in our code:
  • Add a new method that does the translation.
 public void Translate()  
 {  
 }  
  • Add necessary values as parameters to the method so that the values can be passed to the library from calling application.
 public void Translate(string key, string sourceText, string sourceLanguage, string targetLanguage)  
 {  
 }  
  • Since the calling application needs translated value as a response add string as a return type.
 public string Translate(string key, string sourceText, string sourceLanguage, string targetLanguage)  
 {  
 }  
This completes the method signature.

Now lets start the real coding part.
  • Create a string variable and add the Url as a base url.
 string baseUrl = "https://www.googleapis.com/language/translate/v2?";  
  • Create a HttpWebRequest to the Url.
 HttpWebRequest request = WebRequest.Create(baseUrl+ string.Format("key={0}& q={1}&source={2}&target={3}",   
     new object[] { key, sourceText, sourceLanguage, targetLanguage })) as HttpWebRequest;   
  • HttpWebRequest is present inside System.Net namespace. So add System.Net to the list of namespaces.
The code editor should look similar to this:

code editor
Editor should look similar to this image
  • Set the request method to "GET"
 request.Method = "GET";  
Now its time to get the response.
  • Call GetResponse method on the request object and assign it to a new HttpResponse object.
 HttpWebResponse response = request.GetResponse() as HttpWebResponse;  
  • The response object will have a status code associated with it. The status code specifies the status of response. It denotes if the request to the translation service succeeded or resulted in a failure.
Now lets check if the request succeeded.

 if (response.StatusCode == HttpStatusCode.OK)  
 {  
 }  
If the status code is OK, we proceed and read the response.

The response is sent in the following JSON format:

 {  
  "data": {  
   "translations": [  
    {  
     "translatedText": "Hallo Welt"  
    }  
   ]  
  }  
 }  
Since the response contains JSON string we need a way to read JSON. For this example, I used Newtonsoft Json library. Newtonsoft Json library is a free and a very popular library for processing Json.

Lets add a reference to NewtonSoft Json library

Newtonsoft Json library can be added to the solution using Nuget package manager.
In Visual Studio, under Tools -> Library package manager select "Manage NuGet packages for solution".
NuGet package manager
Open NuGet package manager
In the package manager window, search for newtonsoft json.
Install the Json.NET library from search results.
Package manager window
Search for newtonsoft json library in package manager window
Once a reference to NewtonSoft library is added, use "JsonTextReader" object from the library and read the property with key "translatedText".
"JsonTextReader" takes StreamReader as a parameter. So lets create a StreamReader out of the response object.


 JsonTextReader reader = new JsonTextReader(new StreamReader(response.GetResponseStream()));  
Just to make sure that the reader object is disposed off correctly lets wrap the above statement in a using construct.
 using (JsonTextReader reader = new JsonTextReader(new StreamReader(response.GetResponseStream())))  
 {  
 }  
Now lets loop through the reader object recursively and find the property with key "translatedText".
Return the string value once the property is found.

 while (reader.Read())  
 {  
    if ((reader.TokenType == JsonToken.PropertyName) && (reader.Value.ToString() == "translatedText"))  
    {  
      return reader.ReadAsString();  
    }  
 }  
Here is the final code:
 using Newtonsoft.Json;  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Net;  
 using System.Text;  
 namespace GoogleTranslationLibrary  
 {  
   public class Translator  
   {  
     public string Translate(string key, string sourceText, string sourceLanguage, string targetLanguage)  
     {  
       string baseUrl = "https://www.googleapis.com/language/translate/v2?";  
       string responseText = string.Empty;  
       try  
       {  
         //Call format for the translation API  
         //https://www.googleapis.com/language/translate/v2?key={INSERT-YOUR-KEY}&q=hello%20world&source=en&target=de  
         HttpWebRequest request = WebRequest.Create(baseUrl + string.Format("key={0}&q={1}&source={2}&target={3}", new object[] { key, sourceText, sourceLanguage, targetLanguage })) as HttpWebRequest;  
         request.Method = "GET";  
         HttpWebResponse response = request.GetResponse() as HttpWebResponse;  
         if (response.StatusCode == HttpStatusCode.OK)  
         {  
           using (JsonTextReader reader = new JsonTextReader(new StreamReader(response.GetResponseStream())))  
           {  
             while (reader.Read())  
             {  
               if ((reader.TokenType == JsonToken.PropertyName) && (reader.Value.ToString() == "translatedText"))  
               {  
                 return reader.ReadAsString();  
               }  
             }  
           }  
           return sourceText;  
         }  
         return ("Failed with " + response.StatusCode);  
       }  
       catch (Exception ex)  
       {  
       }  
       return responseText;  
     }  
   }  
 }  
Build the project:

In Solution explorer window, right click on the "GoogleTranslationLibrary" projetc and select "Build" option. The build option compiles the application and generates a dll file.


Build project from Solution explorer window
Build project from Solution explorer window
Testing the library:

Lets now create a console application in order to test the GoogleTranslationLibrary.
Right click on the Solution Explorer window and select Add->New Project.
In the "Add new project" window select Console Application.

Add new project window
Add new project window
Now lets add a reference to the dll created in "GoogleTranslationLibrary" project.
Right click on the References node of the project explorer window and select the option "Add Reference".
Add reference to dll
Add reference to dll

In the Add reference window under Solution tab, select Projects. You should see the library GoogleTranslationLibrary listed.
Add solution reference
Add solution reference

Select "GoogleTranslationLibrary" and press "OK".
A reference to the "GoogleTranslationLibrary" dll is added to the project "GoogleTranslationLibraryTestProject".
A reference to GoogleTranslationLibrary dll is added
A reference to GoogleTranslationLibrary dll is added

Lets add the following few lines of code inside the "Main" method:
 Translator translator = new Translator();  
 string translatedString = string.Empty;  
 translatedString = translator.Translate("YOUR-API-KEY", "Hello world", "en", "fr");  
 Console.WriteLine(translatedString);  
 Console.Read();  
Running the project should give the following output:
Translation output
Translation output

For the above code to work, you need to register for Google Translation API and obtain a key. The procedure to obtain the API key is explained in another post.