Click here to Skip to main content
15,893,790 members
Articles / Desktop Programming / WPF

Localization Sync

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
23 Feb 2012CPOL4 min read 21.3K   625   9  
Small utility to keep localized resources synchronized
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows;
using System.Collections.ObjectModel;
using System.Threading;

namespace LocalizationSync
{
    public class TranslationManager : INotifyPropertyChanged
	{
		#region Members
        private static TranslationManager singleton = null;
        public event PropertyChangedEventHandler PropertyChanged;
        private Translation sourceTranslation = null;
        private BackgroundWorker worker = null;
        private ObservableCollection<DestinationItem> destinationElements = null;
        private Info status = null;
		#endregion

		#region Constructors
		/// <summary>
		/// Private constructor
		/// </summary>
		private TranslationManager()
		{
            sourceTranslation = new Translation();
            destinationElements = new ObservableCollection<DestinationItem>();

            worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.DoWork += new System.ComponentModel.DoWorkEventHandler(BackgroundWorker_DoWork);
            worker.ProgressChanged += new ProgressChangedEventHandler(Worker_ProgressChanged);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Worker_RunWorkerCompleted);
		}
		#endregion

		#region Properties
        public static TranslationManager Singleton
        {
            get
            {
                if (singleton == null)
                    singleton = new TranslationManager();

                return singleton;
            }
        }

        public ObservableCollection<DestinationItem> DestinationElements
        {
            get { return destinationElements; }
            set
            {
                if (value != this.destinationElements)
                {
                    this.destinationElements = value;
                    NotifyPropertyChanged("DestinationElements");
                }
            }
        }

        public Info Status
        {
            get { return status; }
            set
            {
                if (value != this.status)
                {
                    this.status = value;
                    NotifyPropertyChanged("Status");
                }
            }
        }

        public Translation SourceTranslation 
        { 
            get { return sourceTranslation; }
            set
            {
                if (value != this.sourceTranslation)
                {
                    this.sourceTranslation = value;
                    NotifyPropertyChanged("Status");
                }
            }

        }
		#endregion

		#region Methods
        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }

        public bool LoadSourceTranslation()
        {
            if (!sourceTranslation.LoadDocument())
                return false;

            return true;
        }

        public void RunWorker()
        {
            if (!worker.IsBusy)
                worker.RunWorkerAsync();
        }

        /// <summary>
        /// Load and process translations. Report progress to the main page.
        /// </summary>
        void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            // There is no need for a try/catch here because any exception that will happen here
            // will be catch in RunWorkerCompleted event handler
            BackgroundWorker worker = sender as BackgroundWorker;
            if (!TranslationManager.Singleton.LoadSourceTranslation())
            {
                e.Result = new Info("Processing was canceled because source translation could not be loaded", InfoType.Error);
                return;
            }

            int i = 0;
            bool success = true;
            foreach (object destination in destinationElements)
            {
                // Create destination translation
                DestinationItem destinationItem = destination as DestinationItem;
                TranslationDestination destinationTranslation = new TranslationDestination()
                {
                    DocumentPath = destinationItem.FileName,
                    DestinationItem = destinationItem
                };

                // Process destination translation
                if (!destinationTranslation.Process())
                {
                    if (success)
                        success = false;
                }

                // Report translation progress
                worker.ReportProgress((++i) * 100 / destinationElements.Count, destinationTranslation);

                // Sleep a bit to let progress be visible in case of fast processing
                Thread.Sleep(300);
            }

            if (!success)
                e.Result = new Info("Reports not successfully generated for all translations", InfoType.Error);
            else
                e.Result = new Info("Translation reports successfully created", InfoType.Success);
        }

        void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                Status = new Info(String.Format("An error occurred during processing. Message: {0}", e.Error.Message), InfoType.Error);
            }
            else
            {
                if (e.Result != null)
                {
                    Info resultInfo = e.Result as Info;
                    if (resultInfo != null)
                        Status = resultInfo;
                }
            }

            // Display resulting status in main window
            MainWindow mainWindow = Application.Current.MainWindow as MainWindow;
            mainWindow.DisplayInfo();
        }

        /// <summary>
        /// Called each time a translation was parsed
        /// </summary>
        void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            // Update final status for current destination translation
            TranslationDestination destinationTranslation = e.UserState as TranslationDestination;
            destinationTranslation.FinalizeStatus();

            // Update progress bar in main page
            MainWindow mainWindow = Application.Current.MainWindow as MainWindow;
            mainWindow.WorkInProgress(e.ProgressPercentage);
        }
		#endregion
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Romania Romania
I have been a software developer for a while and still find this an interesting job.

Comments and Discussions