Failed to create directory C:\Program Files(x86)\Android\Android-sdk\temp – How to fix it ?

Objective :

When Trying to install new packages/updates using Android SDK Manager, We can see some errors that “Unable to Install”. So Here are some errors I got when I got when I was trying to Install android API(s) and other package by Right Click and Run the app(Normal way).

Failed to create directory C:\Program Files(x86)\Android\Android-sdk\temp

4 error faild to create directory - Copy

Error 1

URL not found: C:\Program Files (x86)\Android\android-sdk\temp\platform-tools_r25.0.5-windows.zip (Access is denied)

1 error

Error 2

How to Fix it ?

To Fix the error and Install the packages, what we have to do is Run the Android SDK Manager as Administrator..

First, go to C:\Program Files (x86)\Android\android-sdk and select SDK Manager.exe. 

Then Right Click and Run As Administrator.

5 run as administrator

Image 1 : Run as Administrator

6 loading packages

Image 2 : Loading packages

1 install ready

Image 3 : Select Packages to Install/Update

2 click install

Image 4 : Selected Packages

3 select and click install

Image 5 : Accept one by one to Install (Accept radio Button)

3 install sdk s

Image 6 : Accept all selected packages to install using “Accept Licence” radio Button

7 downloading

Image 7 : Downloading

8 finished downloading

Image 8 : Downloaded Successfully

Important

Instead of Running as Administrator by going to Program Files, You can Open Android SDK manager using Visual Studio.

It will run the Android SDK Manager as Administrator itself.

Click the …  Tools -> Android -> Android SDK Manager

9. open in vs

Image 9 : Run SDK Manager using VS as Administrator

Thanks !

Xamarin Lesson 1 – Install Xamarin with VS 2017

Video

This Video show you how to download and install Visual Studio for the development of Cross-platform mobile apps.

Please Follow the video.. To Download and Install Visual Studio 2017…

How to Check the App is running for the First time – in Xamarin Forms (Android/iOS/Windows)

Objective

In one of my Xamarin Forms apps, I wanted to check is the app running for the first time after the installation or the app is already installed and according to that Load different pages in the app

 How to Install Xamarin in Visual Studio 2017…

Furthermore,

  1. If the App is running for the first time, I wanted to a Quick Start Guide to the user.
  2. If all has already installed, app will show the Login Form.

pags

Then I looked for a solution and James Montemagno‘s  SettingsPlugin gave me the solution…

If you want to learn more, Click above links to go to GitHub and  MotzCod.es.

How I did it ?

First I went through the Instruction of the above references and I installed the plugin using NuGet..

Here I’ll explain how I did it.. and Here is my project at the beginning.

1-project

1. First Install the Settings Plugin using NuGet packages.. Search  “Xam.Plugins.Settings”

2-download-settings

2. Apply The package to all projects or selected projects.. (But I’m managing the settings from the PCL project) and Install the package..

3-select-all-projects

3. Then Conform the installation..

4-conform-installa-tion

4. When the packages has installed, It will generate a folder which is “Helpers” and a class onside it “Settings.cs” to manage settings.

It will added to all selected projects.

5-helpers-settings

The default Settings class includes below C# code to manage settings..


using Plugin.Settings;
using Plugin.Settings.Abstractions;

namespace FirstTimeUse.Droid.Helpers
{
///
<summary>
/// This is the Settings static class that can be used in your Core solution or in any
/// of your client applications. All settings are laid out the same exact way with getters
/// and setters.
/// </summary>

public static class Settings
{
private static ISettings AppSettings
{
get
{
return CrossSettings.Current;
}
}

#region Setting Constants

private const string SettingsKey = "settings_key";
private static readonly string SettingsDefault = string.Empty;

#endregion
public static string GeneralSettings
{
get
{
return AppSettings.GetValueOrDefault<string>(SettingsKey, SettingsDefault);
}
set
{
AppSettings.AddOrUpdateValue<string>(SettingsKey, value);
}
}

}
}

To read the more about the Settings class go to:  https://github.com/jamesmontemagno/SettingsPlugin

I’m going to store my value in the SettingsKey property. So I’ll change the default value of the SettingsKey property to “yes”. Which means the app is running for the first time.

6-change-settings-key


private static readonly string SettingsDefault = "yes";

5. Now I’m going to use the Settings in the application..

I’m checking the app status in the App.xaml.cs class. Because the app navigating to the Main page happens in the constructor in App.xaml.cs class.

The default code of the App class is… And there are not properties in this class…


public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new MainPage();
}

protected override void OnStart()
{
// Handle when your app starts
}

protected override void OnSleep()
{
// Handle when your app sleeps
}

protected override void OnResume()
{
// Handle when your app resumes
}
}

Now I’ll add a Property to App class to Manage App Settings. The property name is “IsFirstTime” and type is String.

7-add-isfirsttime


///
<summary>
/// Get and Set value to General settings
/// </summary>

public string IsFirstTime
{
get { return Settings.GeneralSettings; }
set
{
if (Settings.GeneralSettings == value)
return;
Settings.GeneralSettings = value;
OnPropertyChanged();
}
}

6. Now I’ll add another page to use for log in to system if the app has already installed.

Page name is “LoginPage.xaml”.

8-added-2-pages

7. Now Lets Write code in App.xaml.cs to check the app status…

The page is initialize in the constructor of the App class. So I’m going to check the status of the app inside of the constructor.

And Here is the code. In the Settings class, I have set the default value as “yes“. So the app runs for the first time, the value should be “yes“. Then  the MainPage page will open. And when the app ran for the first time, it  sets the “IsFirstTime value to “no“.

Then when the user run the app after the first time, it will load the second page which is Logging Page.

9-check-first-time


public App()
{
InitializeComponent();

// Check is the app running for the first time
if (IsFirstTime == "yes")
{
// if this is the first time, set it to "No" and load the
// Main Page ,which will show at the first time use
IsFirstTime = "no";
MainPage = new FirstTimeUse.MainPage();
}
else
{
// If this is not the first time,
// Go to the login page
MainPage = new FirstTimeUse.LoginPage();
}
}

8. The Build and run the app using emulator. I’m using my Samsung Galaxy J7 as the emulator. And the App was run  successfully.

screenshot_20170219-173522

First time it will open the Main Page

screenshot_20170219-173745

And When I run the app after the first time, It loads the Login page..

 

References…

https://github.com/jamesmontemagno/SettingsPlugin

https://components.xamarin.com/gettingstarted/settingsplugin

 

Thanks !

How to Fix Error “C:\Program Files (Access is Denied)” When Proguard has Enabled while Build a Android app

Why ?

When I was trying to build one of my android apps in “Release” mode to deploy, I got and Error that  “C:\Program Files (Access is Denied)” and the File was “PROGUARD”.

2-errror

Then I looked for a solution to avoid the error.

What is Proguard ?

The Reason For The Error

In the Android project, I have set the Proguard Enabled before I build the app.

The reason for the error is there is a space in the path to the PROGUARD. Proguard is in the Android folder in Program Files (x86) and there is a spaces between “Program Files (x86)”.

C:\Program Files (x86)\Android\android-sdk\tools\proguard

0-program-file-spaces

So PROGUARD may unable to find the path..

So How to Fix This ?

What we have to do is Place the android-sdk folder to a path without spaces..

To do that I created a symbolic Link(sym-link) ..

Here are steps to create a symbolic link..

1 .First we have to download and Install the  Link Shell Extension.

To Download the Link Shell Extension , Click Here .. 

2. After Installed the Extension then we are ready to create the sym-link.

How To Create a Symbolic Link, Click Here…

Here are steps How I created according to my Folder structure..

First I create a Folder in C: drive outside of Program Files x86 which is “AndroidSysLink”. So we have to Link the Android-SDK path to this folder.

First Go to Program Files x86 and Right Click on Android Folder and we can see a new context menu “Pick Link Source”. Then Click it..

1-pick

Then Go back and Select “AndroidSysLink” Folder -> Right Click . Then We can see a new context menu “Drop As” . When we click on it and we will see few options in another context menu. Then Select “Junction”. And then The link will be created.

2-drop-symbolic-link

3. Then We have to change the Android SDK path in Visual Studio.

So go to Tools -> Options -> Xamarin and Click the “change” button inside of the Android SDK location…

Then we can see a dialogue to select the sdk path..

3-existing-sdk-path

4. Go to the Linked folder and copy the path in it..

4-select-new-path

5. Paste the Path in the sdk-path selection dialogue box.

5-new-sdk-path

Then Click OK…

6. Now The Path has changed an Click OK to conform the new SDK path..

6-new-sdk-path

7. Now we are ready to release the app. But before Build the app recheck the configuration in properties.

First Verify Target Android versions..

0-selectandroid-versions

Make Sure the Confutation has set to “Release” and Proguard is Enabled..

1-enable-proguard

8. Then Build The app in Release Mode..

The app will build successfully..

3-build-success

9. Now we are ready to Archive the Android App.

Right Click on the Android project and click “Archive“…

4-archieve

We can see Archiving Progress…

5-archieving

We can see a Settings I con with a Green icon when the app has archived successfully and in the bottom of the dialogue we can see build information.

6-archieved-successfully

Click the “Open” folder and the created .apk file will see in that folder.

7-open-the-path

References…

https://developer.xamarin.com/guides/android/deployment,_testing,_and_metrics/publishing_an_application/part_1_-_preparing_an_application_for_release/

https://developer.xamarin.com/guides/android/application_fundamentals/cpu_architectures/

https://developer.xamarin.com/guides/android/deployment,_testing,_and_metrics/proguard/

https://www.howtogeek.com/howto/16226/complete-guide-to-symbolic-links-symlinks-on-windows-or-linux/

http://schinagl.priv.at/nt/hardlinkshellext/linkshellextension.html

https://forums.xamarin.com/discussion/45210/enable-proguard-error-c-program-files-access-is-denied

Thanks !

How to Fix Error : Xamarin.Forms.Xaml.XamlParseException: Position 39:8. Type local:NoBorderEntry not found in xmlns clr-namespace:LoginApp;assembly=LoginApp

Why ?

I created a sample login form using Xamarin  and I wanted to remove the underline of the Entry controls. So I had to use a custom render to change the Entry Control .

Below Image describes what I was going to do…

2-uis

So I wrote a custom render to customize the Entry Control in Android(Droid) project and when I was trying to run the app , It gave me an exception that..

Xamarin.Forms.Xaml.XamlParseException: Position 39:8.

Type local:NoBorderEntry not found in xmlns clr-namespace:LoginApp; assembly=LoginApp

1-error

How to Solve the issue ?

So I  looked for a solution and I found the issue is in the assembly name that I have defined in the XAML file.

What I had to do is change the assembly name.

 

Now I’ll describe you what was the wrong and How did I solve the issue..

First to learn How to write a custom render for Entry Control, Click here …

Here is the architecture of my app..

3-architectire

My code..

NoBorderEntry  Class


using Xamarin.Forms;

namespace LoginApp
{
public class NoBorderEntry : Entry
{

}
}

NoBorderEntryEntryRenderer Class


using Android.Graphics.Drawables;
using LoginApp;
using LoginApp.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(NoBorderEntry), typeof(NoBorderEntryEntryRenderer))]
namespace LoginApp.Droid
{
public class NoBorderEntryEntryRenderer : EntryRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);

if (Control != null)
{
Control.Background = new ColorDrawable(Android.Graphics.Color.Transparent);
}
}
}
}

5-code-csharp-namespace

 

MainPage.Xaml

The XAML code is too large in my file. SO I’ll write only the important parts of the XAML code..


<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:LoginApp;assembly=LoginApp"
x:Class="LoginApp.MainPage" >

<local:NoBorderEntry Grid.Row="0"  Grid.Column="1"  Placeholder="User Name"  PlaceholderColor="Silver" TextColor="#D6FCE6" />

</ContentPage>

And here you can see the namespace that I have declared and how we can use it to the Entry render..

4-xaml-code-1

You can see the highlighted texts in above images and according to them the namespace in the NoBorderEntryRenderer is “LoginApp.Droid” but in the in the MainPage.Xaml file the assembly name id “LoginApp”.

So “assembly=LoginApp” should me changed to “assembly=LoginApp.Droid” and the Error will be fixed.

6-fix-error

Then the correct XAML namespace declaration should be like below..

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms&quot;
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml&quot;
xmlns:local="clr-namespace:LoginApp;assembly=LoginApp.Droid"
x:Class="LoginApp.MainPage" >

</ContentPage>

Now the app will run without any error…

screenshot_20170215-233357

 

References

https://developer.xamarin.com/guides/xamarin-forms/custom-renderer/entry/

Thanks !

java.lang.UnsupportedClassVersionError: com/android/dx/command/Main : Unsupported major.minor version 52.0 – How To Fix this Error ?

Why ?

When I was trying to compile one of my sample Xamarin Forms Android project, I got the below error …

java.lang.UnsupportedClassVersionError: com/android/dx/command/Main : Unsupported major.minor version 52.0
LoginApp.Droid  

1-error

Reason :

Then I looked for a solution and finally I found the reason is Android API 24 Requires Android JDK 8. But Still I had Android JDK 7 in my machine which came with Xamarin 4.2 with Visual Studio 2015.

Solution :

The solution was to download the Android JDK 8 and change the Android JDK path in Visual Studio to jdk 1.7 to jdk 1.8. It fixed the error and Finally my project built successfully.

Here Are Steps to Install the JDK 1.8 and how to fix the error..

  1. Go to Java SE Development Kit 8 Downloads and download the suitable file which is compatible with your OS. I have windows 10 x64 , So I downloaded the file for windows x64.

2-jdk-1-8

2. Then Install The java Development Kit 8..

3-jdk-installing

3. Select the path to Install the JDK 1.8 and go through the setup wizard…

4-select-destination

4. Then Close the setup when the installation has completed…

5-update-completed

5. Open the Visual Studio 2015 and Then Go to Tools-> Options – > Xamarin -> Android Settings

6-jdk-1-7-path

6. Change the Java Development Kit Location to JDK 1.8 path  instead of JDK 1.7 path

7-select-jdk-8-path

7. Click OK when the JDK 1.8 Path selected…

8-selected-jdk-8-path

8. Now Rebuild the Project and It will work fine… (Here is the built result in my project)

9-built-successfully

9. Now you can run the emulator to ensure that the project has build successfully…

(I’m using my Samsung galaxy J7 phone as the Emulator and it worked fine…)

10-emulator-successfull

The app opened in the phone successfully…

screenshot_20170210-213844

 

References…

https://forums.xamarin.com/discussion/67720/unsupported-major-minor-version-52-0

Thanks !

Multiple substitutions specified in non-positional format; did you mean to add the formatted=”false” attribute?

Reason

My Xamarin project uses multiple languages and their translations are stored in Resource/.resx files. When I build the project in VS 2015 the android project not built successfully and it gave me an error…

Error

Multiple substitutions specified in non-positional format;
did you mean to add the formatted=”false” attribute?
Mobility_App.Droid F:\Mobility_App.Droid\Resources\Values-fr\AppResources.xml

1 error

Image 1 : Error

Reason

I search the error and I found the issue occurred because some <string> tags consists of percentage(%) symbol.

2 reason

Image 2 : Reason % symbol

Solution

To fix this error we have to add a attribute “Formatted” to <string> tags which are consists of ‘%’ symbols. and Set “Formatted” attribute’s value to “false”.

3 solution

Image 3 : add <string formatted=”false”>

Now the issue has fixed and to ensure, then rebuild the project and you can see the solution is success.

4 success

Image 4 : Successfully Build

Thanks you !

Convert from Multilingual App Toolkit v3.0 to v4.0 and Fix Error “The Multilingual App Toolkit v4.0 is not compatible with previous versions of the toolkit”

Reason

I used Multilingual App Toolkit 3.0 for my Xamarin application in Visual Studio 2013 in Windows 8.1. Then I moved to a new machine with windows 10 and I installed Visual Studio 2015. Then I opened that Xamarin project in VS 2015 and when I was building the project it gave me an error.

mla error 1

Image 1 : Error

Error

The imported project “C:\Program Files (x86)\MSBuild\Microsoft\Multilingual App Toolkit\Microsoft.Multilingual.ResxResources.targets” was not found.

Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.

Mobility_App.Android

F:\ProjectsBuddhima\mobile\Mobility\Mobility App\Mobility_App.csproj

Reason

Then I searched solutions for the error and according to the error, my new machine has not installed Multilingual App Toolkit.

Solution and Next steps

So I installed Multilingual App Toolkit v.4.0 which is compatible with Visual Studio 2015.

You can download from

https://visualstudiogallery.msdn.microsoft.com/6dab9154-a7e1-46e4-bbfa-18b5e81df520

mla error 2

Image 2 : Download Multilingual App Toolkit v4.0

Then the installer will download to your machine and you have to install it manually.

After I installed Multilingual App toolkit 4.0 I built the project again and I got another error.

Multilingual App Toolkit v4.0 upgrade blocked

The Multilingual App Toolkit v4.0 is not compatible with previous versions of the toolkit

mla error 7

Image 3 : Multilingual app Toolkit is blocked

According to above error message, I browsed the link in the http://aka.ms/mat4faq

According to their technical references I will describe steps to convert from v3 to v4.

  1. First take a backup of existing project.
  2. Then we have to open the project which has Multilingual App toolkit v3.
  3. Then we have to disable app toolkit for projects. Go to tools and click “Disable Multilingual App Toolkit”.

    1 disable MLA tool kit

    Image 4 : Disable MLA Toolkit

  4. Then Copy current .xlf files to another location as a backup and delete all .xlf files in the project.

    2 remove xlf files

    Image 5 : Remove current XLF files

  5. Then rebuild the project.

 

Sometimes these steps are not enough to fully disable toe Multilingual App toolkit. So we have to disable it using config file manually.

Here are steps to remove them manually.

1.Right click the config file in the project and open it.
2.Search the label “MultilingualAppToolkit” in the config file.

12 multi languala app label

Image 6 : Delete property group from config file

3.Then delete above <PropertyGroup> which contains <MultilingualAppToolkitVirsion> tag.
4.Then we have to search again “MultilingualAppToolkit” label. And you will see <import> element.

13 delete multi languala import label

Image 7 : Delete <import> tag which contains MLA label

And also we have to delete the <Import> tag which contains “MultilingualAppToolkit”.

 

5.Then rebuild the project.

Now we have removed configurations of Multilingual App Toolkit from our project and we are ready to add v4.0 configurations.

Then we have to enable Multilingual App Toolkit from Toolbox.

1 Enable mltk

Image 8 : Enable MLA Toolkit

When we enable the Multilingual App Toolkit v4.0, we are ready to recycle Transitions from v3.0 project’s .xlf files.

Below I have added steps for that.

1.  Please check that the Multilingual App Toolkit v4.0 is enabled.

2. Then click on the project and select Multilingual App Toolkit=> Add transition languages

3 add multilangual languages

Image 9 : Multilingual App Toolkit ->  Add Transition languages

3. We can see language list in a window like below. Select languages that previously we have added to the project.

4 select languages

Image 10 : Select Languages

When click “OK”. New xlf files will be added to our project in a folder called “MultilingualResources”.  Below image shows it.

5 added xlf files

Image 11 : Added XLF files for selected languages

4. Then click on “MultilingualAppResources” folder and click .. Multilingual App Toolkit=> Import / recycling translations

6 import recycling transactions

Image 12 : Multilingual App Toolkit -> Import/Recycle Transitions

Then you will see below window.

7 import recycling transactions

Image 13 : Import Transition window

5. Click “Add button” and then select v3 xlf files from the location that we have copied from previous project.

8 select old v3 files

Image 14 : Select and Add  XML files in v3 project.

6. Then Select xlf files that we copied from the temporary location and Click “Open”. Then selected xlf files will be added to import resources form.

9 seletec xlf v3 files

Image 15 : Added XLF files

7. And an Important thing is we have to check the “Enable resource recycling” check box. And then click the import button.

10 enable recycling and import

Image 16 : Enable resource recycling and Import

8. Then rebuild the project.

11 success

Image 17 : Successfully Built project

Then we can see those .xlf files has been added to project and the project has built successfully.

Thank you !

Add Attributes to Resource(.resx) file from Excel file in C#

SUBJECT…

Today I’m going to create a windows form app to write items to application resource (.resx) file using data in a excel file.

REASON…

The reason I decided to develop this kind of app is, I’m working on a Xamarin project and it supports for English, French and Dutch. So I had to add translations for both two languages for English.

In Visual Studio we can Add Recourse key and value attributes manually using resx file. I’ll show you how we can do it manually.

3 add attributes manually 3

Image 1 : Add attributes manually to Resource file

What I had to do is copy Name and keys from above excel file and paste in to Name field and Key field one by one.

But it is not easy when there are thousands of Names and translations (keys). Because it’ll waste time.

MY SOLUTION…

So I decided to develop a small app to write resource attributes using a excel file to resx files.

I have two resource files for French and Dutch and you can see them under project resource folder in below image.

2 project style

Image 2 : Application design and class structure

Then I created a small windows form with two buttons for French and Dutch and a List view.

Now I’ll describe the coding part for above functionality.

First I have added resource file paths as attributes to App.config file.


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <appSettings>
    <add key="resPathFr" value="F:\My softwares\Excel to RESX\TranslationMobile\Translation\Properties\AppResources.fr.resx"/>
    <add key="resPathNl" value="F:\My softwares\Excel to RESX\TranslationMobile\Translation\Properties\AppResources.nl.resx"/>
  </appSettings>
</configuration>

Then Add the Excel file “Book1.xlsx” to Startup path  “//bin”.

Here is the format of the excel file I’m going to use..

1 Excel file

Image 3 : The Excel file which contains Translations

According to this excel file, Keys are in “ID” column which is column “A”. And English definitions are in column “B”, French/FR definitions are in column “D” and Dutch/NL definitions are in column “F”.

And These keys and definitions are stored in “Sheet1”.

Then I will add useful namespaces that we have to use in Form1.cs class additionally to default namespaces .


using System.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using System.Resources;
using System.Configuration;

We have to Add Office.Interop.Excel namespace from references like below image

4 add excel namespace

Image 4 : import Excel resource from references

Then I’ll add another class called “ResourcesFr” with two property to store Key, Value collection. But you can use a Dictionary<string,string> instead of using a Generic collection to store Keys and Values. Because we are using only two properties to store data.


public class ResourcesFr
 {
 public string Key { get; set; }
 public string Value { get; set; }
 }

Then we can start coding in Form1.

I’ll add five properties in Form one for Excel Application,Workbook, Sheet, Key/value list and another one for missing values.


namespace Translation
{
 public partial class Form1 : Form
 {
 public Form1()
 {
 InitializeComponent();
 }

List<ResourcesFr> keyList = new List<ResourcesFr>();

Excel.Application xlApp;
 Excel.Workbook xlWorkBook;
 Excel.Worksheet xlWorkSheet;
 object misValue = System.Reflection.Missing.Value;

}

}

Then Double Click the “Dutch button” in the Form1 and it’ll create a Button_Click event.


private void btnDutch_Click(object sender, EventArgs e)
{

}

In this event we can add code for read the excel file and populate key,value information to the keyList property that we declared in the top of the Form1 class.


        ///<summary>
        /// Add Dutch Translations
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDutch_Click(object sender, EventArgs e)
        {
            xlApp = new Excel.Application();
            // path of the Excel file
            string path = (Application.StartupPath + "\\Book1.xlsx");
            // Get Excel file to  xlWorkBook property
            xlWorkBook = xlApp.Workbooks.Open(path);
            // Get "Sheet1" as xlWorkSheet : you can see it in excel sheet image
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            // In the excel sheet we have 322 rows, So I added go through the loop untill 322
            for (int i = 1; i < 322; i++)
            {
                ResourcesFr fr = new ResourcesFr();
                string s = "";
                string s2 = "";
                s = string.Format("A"); // The Key(ID) is in Column A
                s2 = string.Format("F"); // The Value(Text (NL)) is in Column F
                if (xlWorkSheet.Cells[i, s].Value != null)
                {
                    // Get Key
                    fr.Key = xlWorkSheet.Cells[i, s].Value.ToString();
                    //Get Value
                    fr.Value = (xlWorkSheet.Cells[i, s2].Value != null) ? xlWorkSheet.Cells[i, s2].Value.ToString() : "";
                    // Add Key and Value to List<ResourcesFr> keyList
                    keyList.Add(fr);
                }
            }
            // CLose the Excel workbook
            xlWorkBook.Close(true, misValue, misValue);
            // Exit form Excel
            xlApp.Quit();

            // Clean the memory
            ReleaseObject(xlWorkSheet);
            ReleaseObject(xlWorkBook);
            ReleaseObject(xlApp);

            AddMemoLine("Dutch");
            int c = 0;
            foreach (var f in keyList)
            {
                // Insert or Update values
                AddOrUpdateResource(f.Key, f.Value, "NL");
                c++;
                // write in List view
                AddMemoLine(string.Format("Key : {0},       Value : {1}", f.Key, f.Value));
            }
            MessageBox.Show("Dutch resx properties has updated");
        }

ReleaseObject() Method does clean the Garbage collection and get the unused memory.


private void ReleaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show(&quot;Unable to release the Object &quot; + ex.ToString());
}
finally
{
GC.Collect();
}
}

AddOrUpdate() Method does Insert new record to resource file if it is not existing or update the existing record if it is existing.


        ///
<summary>
        /// update resource file
        /// </summary>

        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="lang"></param>
        public void AddOrUpdateResource(string key, string value, string lang)
        {
            try
            {
                // Get Resource File Path
                string resPath = string.Empty;
                if (lang == "FR")
                {
                    resPath = ConfigurationManager.AppSettings["resPathFr"];
                }
                else if (lang == "NL")
                {
                    resPath = ConfigurationManager.AppSettings["resPathNl"];
                }
                else { }
                if (!string.IsNullOrWhiteSpace(resPath))
                {
                    var resx = new List<DictionaryEntry>();
                    using (var reader = new ResXResourceReader(resPath))
                    {
                        resx = reader.Cast<DictionaryEntry>().ToList();

                        // Check if the key is existing
                        var existingResource = resx.Where(r => r.Key.ToString() == key).FirstOrDefault();

                        // Insert new Record if the key is not existing
                        if (existingResource.Key == null && existingResource.Value == null) // NEW!
                        {
                            resx.Add(new DictionaryEntry() { Key = key, Value = value });
                        }
                        else // MODIFIED RESOURCE!
                        {
                            var modifiedResx = new DictionaryEntry() { Key = existingResource.Key, Value = value };
                            resx.Remove(existingResource);  // REMOVING RESOURCE!
                            resx.Add(modifiedResx);  // AND THEN ADDING RESOURCE!
                        }
                    }

                    // Write resources to resx file
                    using (var writer = new ResXResourceWriter(resPath))
                    {
                        resx.ForEach(r =>
                        {
                       // Again Adding all resource to generate with final items
                       writer.AddResource(r.Key.ToString(), r.Value.ToString());
                        });
                        writer.Generate();
                    }
                }

            }
            catch (Exception ex)
            {
                AddMemoLine(string.Format("Key : {0},  Value : {1},  Lang{2}  Throws an error {3}  ", key,value, lang,ex.Message));
            }
        }

And MemoLine() Method does insert an  item to list view.. Then user can see what is happening now..


        ///
<summary>
        /// Insert a record to List view..
        /// </summary>

        /// <param name="data"></param>
        private void AddMemoLine(string data)
        {
            txtResultList.AppendText(data);
            txtResultList.AppendText(Environment.NewLine);
        }

Then run the program and Click the “Dutch” button and you will see update/Inserted records in few seconds.

5 final result

Image 5 : Adding Attributes to resource file

Then close the program and Open the resource file Resource.nl.resx and you will see all records in the excel sheet has transferred to the resx file.

6 resx resource file updated

Added attributes to Resources.nl.resx

You can do the Same thing to “French button”. And You can download the full project using below link.

Download the project file

Thanks !

Buddhima Kudagama

kgbuddhima@gmail.com