Example #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="_token"></param>
        public TelegramBotObjectModel(string _token)
        {
            resMan        = new ResourceLoader();
            TelegramUsers = new ObservableCollection <TelegramUser>();

            try {
                Token = _token;

                Bot = new TelegramBotClient(token);
            }

            catch (Exception e)
            {
                LogWriter.CreateLogEntry(string.Format("{0};{1};{2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""));

                throw e;
            }

            Bot.OnCallbackQuery      += BotOnCallbackQueryReceived;
            Bot.OnMessage            += BotOnMessageReceived;
            Bot.OnMessageEdited      += BotOnMessageReceived;
            Bot.OnInlineQuery        += BotOnInlineQueryReceived;
            Bot.OnInlineResultChosen += BotOnChosenInlineResultReceived;
            Bot.OnReceiveError       += BotOnReceiveError;
        }
Example #2
0
        public async void ResetRelay(string _hostName, int _portNumber, string _userName, string _password)
        {
            try
            {
                HTTP_Req                   = "http://" + _hostName + ":" + _portNumber.ToString() + ConvertIntToResetRelay(RelayNumber); //relays.cgi?relay=5
                myWebRequest               = WebRequest.Create(HTTP_Req);
                myWebRequest.Credentials   = new NetworkCredential(_userName, _password);
                myWebRequest.Method        = "POST";
                myWebRequest.ContentType   = "";
                myWebRequest.ContentLength = 0;
                myWebResponse              = await myWebRequest.GetResponseAsync();

                State = false;
                t.Stop();
                myWebRequest = null;
                myWebResponse.Dispose();
                return;
            }
            catch (Exception e)
            {
                LogWriter.CreateLogEntry(string.Format("{0}\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""));
                State = true;
                return;
            }
        }
Example #3
0
 private void OnNewRemoveBotCommand()
 {
     try
     {
         SelectedTelegramBotObject.StopBot();
         TelegramBotObjectCollection.Remove(SelectedTelegramBotObject);
         SelectedTelegramBotObject = null;
     }
     catch (Exception e)
     {
         LogWriter.CreateLogEntry(string.Format("{0}\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""));
         return;
     }
 }
Example #4
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public User CreateBot()
        {
            try {
                User me = null;

                if (Bot == null)
                {
                    Bot = new TelegramBotClient(Token);


                    Bot.OnCallbackQuery      += BotOnCallbackQueryReceived;
                    Bot.OnMessage            += BotOnMessageReceived;
                    Bot.OnMessageEdited      += BotOnMessageReceived;
                    Bot.OnInlineQuery        += BotOnInlineQueryReceived;
                    Bot.OnInlineResultChosen += BotOnChosenInlineResultReceived;
                    Bot.OnReceiveError       += BotOnReceiveError;
                }

                me = Bot.GetMeAsync().Result;
                                #if DEBUG
                Trace.WriteLine(me.Username);
                                #endif
                Bot.StartReceiving();


                if (me != null)
                {
                    BotName = me.Username;
                    return(me);
                }

                return(new User());
            }

            catch (Exception e)
            {
                LogWriter.CreateLogEntry(string.Format("{0};{1};{2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.InnerException.Message : ""));

                throw e;
            }
        }
Example #5
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public bool SaveSettings(string _path = "")
        {
            try
            {
                TextWriter textWriter;
                var        serializer = new XmlSerializer(typeof(DefaultSpecification));

                textWriter = new StreamWriter(!string.IsNullOrEmpty(_path) ? @_path : @Path.Combine(appDataPath, _settingsFileFileName), false);

                serializer.Serialize(textWriter, defaultSpecification);

                textWriter.Close();

                return(true);
            }
            catch (XmlException e)
            {
                LogWriter.CreateLogEntry(string.Format("{0}\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""));
                return(false);
            }
        }
Example #6
0
        public async void SetRelay(string _hostName, int _portNumber, string _userName, string _password)
        {
            hostName = _hostName;
            port     = _portNumber;
            username = _userName;
            password = _password;

            try
            {
                HTTP_Req                   = "http://" + _hostName + ":" + _portNumber.ToString() + ConvertIntToSetRelay(RelayNumber); //relays.cgi?relay=5
                myWebRequest               = WebRequest.Create(HTTP_Req);
                myWebRequest.Credentials   = new NetworkCredential(_userName, _password);
                myWebRequest.Method        = "POST";
                myWebRequest.ContentType   = "";
                myWebRequest.ContentLength = 0;
                myWebResponse              = await myWebRequest.GetResponseAsync();


                State = true;
                myWebResponse.Dispose();
                myWebRequest = null;

                if (Behavior == KMTronicRelayContactBehavior.RelayContactIsTimed)
                {
                    t.Interval = Time * 1000;
                    t.Start();
                }

                return;
            }
            catch (Exception e)
            {
                LogWriter.CreateLogEntry(string.Format("{0}\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""));
                State = false;
                return;
            }
        }
Example #7
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public bool ReadSettings(string _fileName = "")
        {
            TextReader reader;
            int        verInfo;

            if (!string.IsNullOrWhiteSpace(_fileName) && !File.Exists(_fileName))
            {
                return(false);
            }

            if (File.Exists(_fileName) || (string.IsNullOrWhiteSpace(_fileName) && File.Exists(Path.Combine(appDataPath, _settingsFileFileName))))
            {
                //Path.Combine(appDataPath,databaseFileName)
                var doc = new XmlDocument();

                try
                {
                    var serializer = new XmlSerializer(typeof(DefaultSpecification));

                    if (string.IsNullOrWhiteSpace(_fileName) && File.Exists(Path.Combine(appDataPath, _settingsFileFileName)))
                    {
                        doc.Load(@Path.Combine(appDataPath, _settingsFileFileName));

                        var node = doc.SelectSingleNode("//ManifestVersion");
                        verInfo = Convert.ToInt32(node.InnerText.Replace(".", string.Empty));

                        reader = new StreamReader(Path.Combine(appDataPath, _settingsFileFileName));
                    }
                    else
                    {
                        doc.Load(_fileName);

                        XmlNode node = doc.SelectSingleNode("//ManifestVersion");
                        verInfo = Convert.ToInt32(node.InnerText.Replace(".", string.Empty));

                        reader = new StreamReader(_fileName);
                    }

                    if (verInfo > Convert.ToInt32(string.Format("{0}{1}{2}", Version.Major, Version.Minor, Version.Build)))
                    {
                        throw new Exception(
                                  string.Format("database that was tried to open is newer ({0}) than this version of eventmessenger ({1})"
                                                , verInfo, Convert.ToInt32(string.Format("{0}{1}{2}", Version.Major, Version.Minor, Version.Build))
                                                )
                                  );
                    }

                    //defaultSpecification = new DefaultSpecification();
                    defaultSpecification = (serializer.Deserialize(reader) as DefaultSpecification);

                    reader.Close();
                }
                catch (Exception e)
                {
                    LogWriter.CreateLogEntry(string.Format("{0}\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""));
                    return(true);
                }

                return(false);
            }
            return(true);
        }
Example #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="_selectedSetupViewModel"></param>
        /// <param name="_dialogs"></param>
        public MifareUltralightSetupViewModel(object _selectedSetupViewModel, ObservableCollection <IDialogViewModel> _dialogs)
        {
            try
            {
                MefHelper.Instance.Container.ComposeParts(this);                 //Load Plugins

                databaseReaderWriter = new DatabaseReaderWriter();

                chipModel = new MifareUltralightChipModel(string.Format("Task Description: {0}", SelectedTaskDescription), CARD_TYPE.MifareUltralight);

                pageModel            = new MifareUltralightPageModel(new byte[4], 0);
                pageModel.PageNumber = selectedUltralightPageCurrentAsInt;

                childNodeViewModelFromChip = new RFiDChipChildLayerViewModel(pageModel, null, CARD_TYPE.MifareUltralight, null, true);
                childNodeViewModelTemp     = new RFiDChipChildLayerViewModel(pageModel, null, CARD_TYPE.MifareUltralight, null, true);

                if (_selectedSetupViewModel is MifareUltralightSetupViewModel)
                {
                    PropertyInfo[] properties = typeof(MifareUltralightSetupViewModel).GetProperties(BindingFlags.Public | BindingFlags.Instance);

                    foreach (PropertyInfo p in properties)
                    {
                        // If not writable then cannot null it; if not readable then cannot check it's value
                        if (!p.CanWrite || !p.CanRead)
                        {
                            continue;
                        }

                        MethodInfo mget = p.GetGetMethod(false);
                        MethodInfo mset = p.GetSetMethod(false);

                        // Get and set methods have to be public
                        if (mget == null)
                        {
                            continue;
                        }
                        if (mset == null)
                        {
                            continue;
                        }

                        p.SetValue(this, p.GetValue(_selectedSetupViewModel));
                    }
                }

                else
                {
                    SelectedTaskIndex       = "0";
                    SelectedTaskDescription = "Enter a Description";
                }

                MifareUltralightPages = CustomConverter.GenerateStringSequence(0, 15).ToArray();

                SelectedUltralightPageCurrent = "0";

                HasPlugins = items != null?items.Any() : false;

                if (HasPlugins)
                {
                    SelectedPlugin = Items.FirstOrDefault();
                }
            }
            catch (Exception e)
            {
                LogWriter.CreateLogEntry(string.Format("{0}: {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""));
            }
        }
Example #9
0
        /// <summary>
        /// Updates this instance.
        /// </summary>
        private void Update()
        {
            Log.Write("Updating '{0}' files.", this._remoteConfig.Payloads.Length);

            // Clean up failed attempts.
            if (Directory.Exists(Path.Combine(appDataPath, WorkPath)))
            {
                Log.Write("WARNING: Work directory already exists.");
                try { Directory.Delete(Path.Combine(appDataPath, WorkPath), true); }
                catch (IOException e)
                {
                    LogWriter.CreateLogEntry(string.Format("{0}\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""));
                    return;
                }
            }

            else
            {
                try
                {
                    Directory.CreateDirectory(Path.Combine(appDataPath, WorkPath));
                }
                catch (Exception e)
                {
                    LogWriter.CreateLogEntry(string.Format("{0}\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""));
                    return;
                }
            }


            // Download files in manifest.
            foreach (string update in this._remoteConfig.Payloads)
            {
                Log.Write("Fetching '{0}'.", update);
                var url  = this._remoteConfig.BaseUri + update; //TODO: make this localizable e.g. + (_settings.DefaultSpecification.DefaultLanguage == "german" ? "de-de/" : "en-us/")
                var file = Fetch.Get(url);
                if (file == null)
                {
                    Log.Write("Fetch failed.");
                    return;
                }
                var info = new FileInfo(Path.Combine(Path.Combine(appDataPath, WorkPath), update));
                Directory.CreateDirectory(info.DirectoryName);
                File.WriteAllBytes(Path.Combine(Path.Combine(appDataPath, WorkPath), update), file);

                // Unzip
                if (Regex.IsMatch(update, @"\.zip"))
                {
                    try
                    {
                        var zipfile = Path.Combine(Path.Combine(appDataPath, WorkPath), update);
                        using (var zip = ZipFile.Read(zipfile))
                            zip.ExtractAll(Path.Combine(appDataPath, WorkPath), ExtractExistingFileAction.Throw);
                        File.Delete(zipfile);
                    }
                    catch (Exception e)
                    {
                        LogWriter.CreateLogEntry(string.Format("{0}\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""));
                        return;
                    }
                }
            }

            if (isUserNotified && allowUpdate)
            {
                Process          p    = new Process();
                ProcessStartInfo info = new ProcessStartInfo(Path.Combine(appDataPath, WorkPath, "RFiDGearBundleSetup.exe"));
                //info.Arguments = string.Format("/i {0}", Path.Combine(appDataPath, WorkPath, "RFiDGearBundleSetup.exe"));
                info.UseShellExecute = false;

                try
                {
                    p.StartInfo = info;
                    p.Start();

                    thisprocess.Dispose();

                    Environment.Exit(0);
                }

                catch (Exception e)
                {
                    LogWriter.CreateLogEntry(string.Format("{0}\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""));
                    return;
                }
            }
        }
Example #10
0
        /// <summary>
        /// This method compares a 'dynamic' event object with all 'static' events in the user created list and fires the accociated responses.
        /// </summary>
        private void EventComparer()
        {
            try{
                using (var resMan = new ResourceLoader())
                {
                    //perform check for each created 'static' event
                    foreach (EventObjectModel staticEventObject in listOfStaticEvents)
                    {
                        #region check 'static' <=> 'dynamic' event filter
                        if (staticEventObject.IsEnabled)
                        {
                            //TODO: consider using enums instead
                            if (staticEventObject.EventType == "UnlockingEvent")
                            {
                                if (dynamicEventObject.EventType == staticEventObject.EventType)
                                {
                                    //overwrite 'dynamic' event fields with fields from 'static' events if $dontcare flag is set
                                    var TransponderNameCopy = staticEventObject.TransponderModel.TransponderName == "$dont care" ? staticEventObject.TransponderModel.TransponderName : dynamicEventObject.TransponderModel.TransponderName;
                                    var TransponderPHICopy  = staticEventObject.TransponderModel.TransponderPHI == "$dont care" ? staticEventObject.TransponderModel.TransponderPHI : dynamicEventObject.TransponderModel.TransponderPHI;

                                    foreach (LockModel lm in staticEventObject.TransponderModel.LockModels)
                                    {
                                        var LockNameCopy = lm.LockName == "$dont care" ? lm.LockName : dynamicEventObject.TransponderModel.LockModels[0].LockName;
                                        var LockPHICopy  = lm.LockPHI == "$dont care" ? lm.LockPHI : dynamicEventObject.TransponderModel.LockModels[0].LockPHI;

                                        var tempDynamicEventObject = new EventObjectModel(null,
                                                                                          "UnlockingEvent",
                                                                                          null,
                                                                                          TransponderNameCopy,
                                                                                          LockNameCopy,
                                                                                          0,
                                                                                          TransponderPHICopy,
                                                                                          LockPHICopy,


                                                                                          staticEventObject.TransponderModel.SelectedTransponderTriggerType == "TriggerBoth" ?
                                                                                          "TriggerBoth" :
                                                                                          dynamicEventObject.TransponderModel.SelectedTransponderTriggerType);

                                        if (staticEventObject.Equals(tempDynamicEventObject))
                                        {
                                            staticEventObject.LastSeenDataGridRowContent = DateTime.Now.ToString();

                                            if (tb != null)
                                            {
                                                tb.ShowBalloonTip(resMan.getResource("taskBarIconBalloonHeaderNewUnlockingEvent"), resMan.getResource("taskBarIconBalloonMessageNewUnlockingEvent"), BalloonIcon.Info);
                                            }

                                            foreach (ResponseObjectModel rom in staticEventObject.ResponseCollection)
                                            {
                                                responseQueue.Add(rom);
                                            }
                                        }
                                    }
                                }
                            }

                            else if (staticEventObject.EventType == "InputEvent")
                            {
                                if (dynamicEventObject.EventType == staticEventObject.EventType)
                                {
                                    if (staticEventObject.Equals(dynamicEventObject))
                                    {
                                        staticEventObject.LastSeenDataGridRowContent = DateTime.Now.ToString();

                                        if (tb != null)
                                        {
                                            tb.ShowBalloonTip(resMan.getResource("taskBarIconBalloonHeaderNewInputEvent"), resMan.getResource("taskBarIconBalloonMessageNewInputEvent"), BalloonIcon.Info);
                                        }

                                        foreach (ResponseObjectModel rom in staticEventObject.ResponseCollection)
                                        {
                                            responseQueue.Add(rom);
                                        }
                                    }
                                }
                            }

                            else if (staticEventObject.EventType == "DoorMonitoringEvent")
                            {
                                if (Enum.IsDefined(typeof(DoorMonEventType), dynamicEventObject.EventType))
                                {
                                    foreach (LockModel lm in staticEventObject.TransponderModel.LockModels)
                                    {
                                        var LockNameCopy = lm.LockName == "$dont care" ? lm.LockName : dynamicEventObject.TransponderModel.LockModels[0].LockName;
                                        var LockPHICopy  = lm.LockPHI == "$dont care" ? lm.LockPHI : dynamicEventObject.TransponderModel.LockModels[0].LockPHI;

                                        var tempDynamicEventObject = new EventObjectModel(null, dynamicEventObject.TransponderModel.LockModels[0].DoorMonitoringTrigger[0], null, LockNameCopy, 0, LockPHICopy);

                                        if (staticEventObject.Equals(tempDynamicEventObject))
                                        {
                                            staticEventObject.LastSeenDataGridRowContent = DateTime.Now.ToString();

                                            if (tb != null)
                                            {
                                                tb.ShowBalloonTip(resMan.getResource("taskBarIconBalloonHeaderNewDoorMonitoringEvent"), resMan.getResource("taskBarIconBalloonMessageNewDoorMonitoringEvent"), BalloonIcon.Info);
                                            }

                                            foreach (ResponseObjectModel rom in staticEventObject.ResponseCollection)
                                            {
                                                responseQueue.Add(rom);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        #endregion

                        #region fire responses

                        if (responseQueue.Count > 0)
                        {
                            bool canExecute = true;

                            foreach (ResponseObjectModel response in responseQueue)
                            {
                                if (response.HasSchedule)
                                {
                                    if (response.Scheduler != null && response.Scheduler.Schedule.Count > 0)
                                    {
                                        if (response.Scheduler.IsOnTime())
                                        {
                                            canExecute = true;
                                        }
                                        else
                                        {
                                            canExecute = false;
                                        }
                                    }

                                    else
                                    {
                                        canExecute = false;
                                    }
                                }

                                if (response.ResponseObject as TelegramMessageObjectModel != null && canExecute && response.IsEnabled && (response.ResponseObject as TelegramMessageObjectModel).Bot2Use.IsReceiving)
                                {
                                    if (string.IsNullOrEmpty
                                            ((response.ResponseObject as TelegramMessageObjectModel).MessageToSend))
                                    {
                                        switch (staticEventObject.EventType)
                                        {
                                        case "UnlockingEvent":
                                            (response.ResponseObject as TelegramMessageObjectModel)
                                            .SendTextMessageToChat(
                                                string.Format(resMan.getResource("defaultMessageTelegramMessageUnlockingEventMessage"),
                                                              dynamicEventObject.TransponderModel.TransponderName,
                                                              dynamicEventObject.TransponderModel.TransponderPHI,
                                                              dynamicEventObject.TransponderModel.LockModels[0].LockName,
                                                              dynamicEventObject.TransponderModel.LockModels[0].LockPHI,
                                                              DateTime.Now, resMan.getResource(string.Format("ENUM.{0}", dynamicEventObject.TransponderModel.SelectedTransponderTriggerType))),
                                                (response.ResponseObject as TelegramMessageObjectModel).Bot2Use);
                                            break;

                                        case "DoorMonitoringEvent":

                                            (response.ResponseObject as TelegramMessageObjectModel)
                                            .SendTextMessageToChat(
                                                string.Format(resMan.getResource("defaultMessageTelegramMessageDoorMonitoringMessage"),
                                                              dynamicEventObject.TransponderModel.LockModels[0].LockName,
                                                              dynamicEventObject.TransponderModel.LockModels[0].LockPHI,
                                                              DateTime.Now, resMan.getResource(string.Format("ENUM.{0}", dynamicEventObject.EventType))),
                                                (response.ResponseObject as TelegramMessageObjectModel).Bot2Use);
                                            break;

                                        case "InputEvent":

                                            (response.ResponseObject as TelegramMessageObjectModel)
                                            .SendTextMessageToChat(
                                                string.Format(resMan.getResource("defaultMessageTelegramMessageInputEventMessage"),
                                                              resMan.getResource(string.Format("ENUM.{0}", dynamicEventObject.InputModel.InputName)),
                                                              resMan.getResource(string.Format("ENUM.{0}", dynamicEventObject.InputModel.InputTriggerType)),
                                                              dynamicEventObject.InputModel.Address,
                                                              DateTime.Now, resMan.getResource(string.Format("ENUM.{0}", dynamicEventObject.EventType))),
                                                (response.ResponseObject as TelegramMessageObjectModel).Bot2Use);
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        string message = (response.ResponseObject as TelegramMessageObjectModel).MessageToSend;

                                        if (message.IndexOf("$lockname", StringComparison.CurrentCultureIgnoreCase) != -1)
                                        {
                                            message = message.Replace("$lockname", dynamicEventObject.TransponderModel.LockModels[0].LockName);
                                        }
                                        if (message.IndexOf("$lockphi", StringComparison.CurrentCultureIgnoreCase) != -1)
                                        {
                                            message = message.Replace("$lockphi", dynamicEventObject.TransponderModel.LockModels[0].LockPHI);
                                        }
                                        if (message.IndexOf("$transpondername", StringComparison.CurrentCultureIgnoreCase) != -1)
                                        {
                                            message = message.Replace("$transpondername", dynamicEventObject.TransponderModel.TransponderName);
                                        }
                                        if (message.IndexOf("$transponderphi", StringComparison.CurrentCultureIgnoreCase) != -1)
                                        {
                                            message = message.Replace("$transponderphi", dynamicEventObject.TransponderModel.TransponderPHI);
                                        }
                                        if (message.IndexOf("$datetime", StringComparison.CurrentCultureIgnoreCase) != -1)
                                        {
                                            message = message.Replace("$datetime", DateTime.Now.ToString());
                                        }
                                    }
                                }

                                else if (response.ResponseObject as EMailResponseObjectModel != null && canExecute && response.IsEnabled)
                                {
                                    if (string.IsNullOrEmpty((response.ResponseObject as EMailResponseObjectModel).MessageBody))
                                    {
                                        switch (staticEventObject.EventType)
                                        {
                                        case "UnlockingEvent":
                                            (response.ResponseObject as EMailResponseObjectModel).MessageBody = string.Format(
                                                resMan.getResource("defaultMessageTelegramMessageUnlockingEventMessage"),
                                                dynamicEventObject.TransponderModel.TransponderName,
                                                dynamicEventObject.TransponderModel.TransponderPHI,
                                                dynamicEventObject.TransponderModel.LockModels[0].LockName,
                                                dynamicEventObject.TransponderModel.LockModels[0].LockPHI,
                                                DateTime.Now, resMan.getResource(string.Format("ENUM.{0}", dynamicEventObject.TransponderModel.SelectedTransponderTriggerType)));
                                            break;

                                        case "DoorMonitoringEvent":

                                            (response.ResponseObject as EMailResponseObjectModel).MessageBody = string.Format(
                                                resMan.getResource("defaultMessageTelegramMessageDoorMonitoringMessage"),
                                                dynamicEventObject.TransponderModel.LockModels[0].LockName,
                                                dynamicEventObject.TransponderModel.LockModels[0].LockPHI,
                                                DateTime.Now, resMan.getResource(string.Format("ENUM.{0}", dynamicEventObject.EventType)));
                                            break;
                                        }


                                        (response.ResponseObject as EMailResponseObjectModel).SendMessage();
                                        (response.ResponseObject as EMailResponseObjectModel).MessageBody = "";
                                    }
                                    else
                                    {
                                        string message = (response.ResponseObject as EMailResponseObjectModel).MessageBody;

                                        if (message.IndexOf("$lockname", StringComparison.CurrentCultureIgnoreCase) != -1)
                                        {
                                            message = message.Replace("$lockname", dynamicEventObject.TransponderModel.LockModels[0].LockName);
                                        }
                                        if (message.IndexOf("$lockphi", StringComparison.CurrentCultureIgnoreCase) != -1)
                                        {
                                            message = message.Replace("$lockphi", dynamicEventObject.TransponderModel.LockModels[0].LockPHI);
                                        }
                                        if (message.IndexOf("$transpondername", StringComparison.CurrentCultureIgnoreCase) != -1)
                                        {
                                            message = message.Replace("$transpondername", dynamicEventObject.TransponderModel.TransponderName);
                                        }
                                        if (message.IndexOf("$transponderphi", StringComparison.CurrentCultureIgnoreCase) != -1)
                                        {
                                            message = message.Replace("$transponderphi", dynamicEventObject.TransponderModel.TransponderPHI);
                                        }
                                        if (message.IndexOf("$datetime", StringComparison.CurrentCultureIgnoreCase) != -1)
                                        {
                                            message = message.Replace("$datetime", DateTime.Now.ToString());
                                        }

                                        (response.ResponseObject as EMailResponseObjectModel).MessageBody = message;

                                        (response.ResponseObject as EMailResponseObjectModel).SendMessage();

                                        (response.ResponseObject as EMailResponseObjectModel).MessageBody = null;
                                    }
                                }

                                else if (response.ResponseObject as KNXInterface != null && canExecute && response.IsEnabled)
                                {
                                }

                                else if (response.ResponseObject as KMTronicModel != null && canExecute && response.IsEnabled)
                                {
                                    (response.ResponseObject as KMTronicModel).ProcessRelays();
                                }
                            }
                        }

                        #endregion

                        responseQueue.Clear();
                    }
                    responseQueue.Clear();
                }

                dynamicEventObject = null;
            }
            catch (Exception e)
            {
                LogWriter.CreateLogEntry(string.Format("Unable to Parse Message: {0}; {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""));
                return;
            }
        }
Example #11
0
        /// <summary>
        /// init main
        /// </summary>
        public MainWindowViewModel()
        {
            RunMutex(this, null);

            try{
                dialogs = new ObservableCollection <IDialogViewModel>();
                updater = new Updater();

                updater.isUserNotified = Environment.GetCommandLineArgs().Contains <string>("IAmNotified_DoUpdate");

                runSilent = Environment.GetCommandLineArgs().Contains <string>("runSilent");
            }

            catch (Exception e) {
                LogWriter.CreateLogEntry(string.Format("{0}\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""));
                return;
            }

            if (!updater.isUserNotified)
            {
                settingsReaderWriter = new SettingsReaderWriter();
                dbReaderWriter       = new DatabaseReaderWriter();
            }
            else
            {
                updater.allowUpdate = true;
                firstRun            = false;

                updater.StartMonitoring();
            }

            try{
                resLoader          = new ResourceLoader();
                pipeServer         = new PipeServer();
                eventObjectHandler = new EventObjectHandler();

                tb = (TaskbarIcon)Application.Current.FindResource("TrayNotifyIcon");
            }
            catch (Exception e) {
                LogWriter.CreateLogEntry(string.Format("{0}\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""));
            }

            mainWindowIcon = new BitmapImage();
            mainWindowIcon.BeginInit();
            mainWindowIcon.UriSource = new Uri("pack://application:,,,/EventMessenger;component/Resources/logo.ico");

            mainWindowIcon.EndInit();

            tb.IconSource = mainWindowIcon;

            //logReader = new LogFileReaderWriter(10000, true); // just for testing purposes

            _cmdDeleteEntry    = new RelayCommand(DeleteRow);
            _cmdAddNewEvent    = new RelayCommand(AddNewEvent);
            _cmdAddNewResponse = new RelayCommand(AddNewResponse);

            rowContextMenuItems        = new ObservableCollection <MenuItem>();
            emptySpaceContextMenuItems = new ObservableCollection <MenuItem>();

            emptySpaceContextMenuItems.Add(new MenuItem()
            {
                Header  = resLoader.getResource("contextMenuItemAddNewEvent"),
                Command = _cmdAddNewEvent
            });

            rowContextMenuItems.Add(new MenuItem()
            {
                Header  = resLoader.getResource("contextMenuItemAddOrEditResponse"),
                Command = _cmdAddNewResponse
            });
            rowContextMenuItems.Add(new MenuItem()
            {
                Header = resLoader.getResource("contextMenuItemEditEvent"),
                //ToolTip = "this will be the helptext",
                Command = _cmdAddNewEvent
            });

            rowContextMenuItems.Add(new MenuItem()
            {
                Header  = resLoader.getResource("contextMenuItemDeleteSelectedItem"),
                Command = _cmdDeleteEntry
            });

            //dataGridSource = new ObservableCollection<EventObjectModel>();

            Application.Current.MainWindow.Closing   += new CancelEventHandler(CloseThreads);
            Application.Current.MainWindow.Activated += new EventHandler(LoadCompleted);
            updater.newVersionAvailable += new EventHandler(AskForUpdateNow);
            tb.TrayLeftMouseDown        += new RoutedEventHandler(RestoreMainWindow);
            tb.MouseDown += new MouseButtonEventHandler(RestoreMainWindow);
            //any dialog boxes added in the constructor won't appear until DialogBehavior.DialogViewModels gets bound to the Dialogs collection.
        }
Example #12
0
        private void RestoreFromDB()
        {
            EventObjectModel tempModel = new EventObjectModel();

            foreach (EventObjectModel eo in dbReaderWriter.eventObjects)
            {
                foreach (ResponseObjectModel rom in eo.ResponseCollection)
                {
                    if (rom.ResponseObject is TelegramMessageObjectModel)
                    {
                        var botListQuery = DataGridSource.SelectMany(
                            u => u.ResponseCollection.Where(
                                v => v.ResponseObject is TelegramMessageObjectModel).Select(
                                w => w.ResponseObject as TelegramMessageObjectModel).Select(x => x.Bot2Use).ToList()
                            ).ToList();

                        var selectedBotQuery = DataGridSource.SelectMany(
                            u => u.ResponseCollection.Where(
                                v => v.ResponseObject is TelegramMessageObjectModel).Select(
                                w => w.ResponseObject as TelegramMessageObjectModel).Select(
                                x => x.Bot2Use)
                            ).ToList();

                        if ((rom.ResponseObject is TelegramMessageObjectModel) &&
                            !(botListQuery.Select(y => y.Token).Contains((rom.ResponseObject as TelegramMessageObjectModel).Bot2Use.Token)))
                        {
                            try{
                                (rom.ResponseObject as TelegramMessageObjectModel).Bot2Use.CreateBot();
                            }
                            catch (Exception e)
                            {
                                if (e.InnerException.GetType().ToString() == "System.Net.Http.HttpRequestException")
                                {
                                    LogWriter.CreateLogEntry(string.Format("{0}\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""));

                                    this.Dialogs.Add(new CustomDialogViewModel {
                                        Message = e.InnerException.InnerException.Message,
                                        Caption = "Error",

                                        OnOk = (sender2) => {
                                            sender2.Close();
                                        },

                                        OnCancel = (sender2) => {
                                            sender2.Close();
                                        },

                                        OnCloseRequest = (sender2) => {
                                            sender2.Close();
                                        }
                                    });
                                }
                            }
                        }

                        else if (botListQuery.Select(y => y.Token).Contains((rom.ResponseObject as TelegramMessageObjectModel).Bot2Use.Token))
                        {
                            (rom.ResponseObject as TelegramMessageObjectModel).Bot2Use = selectedBotQuery.Where(z => z.Token == (rom.ResponseObject as TelegramMessageObjectModel).Bot2Use.Token).FirstOrDefault();
                        }
                    }

                    else if (rom.ResponseObject is EMailResponseObjectModel)
                    {
                    }
                }

                DataGridSource.Add(eo);
                SelectedDataGridItem = eo;
                SelectedResponse     = SelectedDataGridItem.ResponseCollection.FirstOrDefault();
            }
        }
Example #13
0
 private void BotOnReceiveError(object sender, ReceiveErrorEventArgs receiveErrorEventArgs)
 {
     LogWriter.CreateLogEntry(string.Format("error: {0}; {1}",
                                            receiveErrorEventArgs.ApiRequestException.Message,
                                            receiveErrorEventArgs.ApiRequestException.InnerException));
 }
Example #14
0
//		public EMailResponseObjectModel(string hostName, int port)
//		{
//			mailMessageToSend = new MailMessage();
//			smtpClient = new SmtpClient(hostName, port);
//		}

//		public void SendMessage(MailMessage message)
//		{
//			smtpClient.SendAsync(message, message.GetHashCode().ToString());
//		}

//		public void SendMessage(string from, string to, string subject, string message)
//		{
//			MailAddress fromMailAddr;
//			MailAddress toMailAddr;
//			MailMessage mailMessage;
//
//			if(from.IndexOf(',') != -1)
//			{
//				string fromAddr = from.Remove(from.IndexOf(','),from.Length);
//				string fromAddrDisplayAs = from.Remove(0,from.IndexOf(','));
//				fromMailAddr = new MailAddress(fromAddr,
//				                               fromAddrDisplayAs,
//				                               System.Text.Encoding.UTF8);
//			}
//			else
//			{
//				fromMailAddr = new MailAddress(from, from, System.Text.Encoding.UTF8);
//			}
//
//			toMailAddr = new MailAddress(to);
//
//			mailMessage = new MailMessage(fromMailAddr.Address,toMailAddr.Address, subject, message);
//			mailMessage.BodyEncoding = Encoding.UTF8;
//			mailMessage.SubjectEncoding = Encoding.UTF8;
//
//			smtpClient.UseDefaultCredentials = useDefaultCredentials;
//
//			if(smtpCredentials != null)
//			{
//				smtpClient.Credentials = smtpCredentials;
//			}
//
//			smtpClient.SendAsync(mailMessage, mailMessage.GetHashCode().ToString());
//
//		}

        /// <summary>
        ///
        /// </summary>
        public async void SendMessage()
        {
            try{
                smtpClient = new SmtpClient(this.SMTPServerName, this.PortNumber);

                smtpClient.SendCompleted += (s, e) => {
                    if (e.Error != null)
                    {
                        LogWriter.CreateLogEntry(string.Format("{0}\n{1}", e.Error.Message, e.Error.InnerException != null ? e.Error.InnerException.Message : ""));
                    }
                    //smtpClient.Dispose();
                    //mailMessageToSend.Dispose();
                };

                MailAddress fromMailAddr;
                MailAddress toMailAddr;
                MailMessage mailMessage = new MailMessage();

                if (FromAddress.IndexOf(',') != -1)
                {
                    string fromAddr          = FromAddress.Remove(FromAddress.IndexOf(','), FromAddress.Length);
                    string fromAddrDisplayAs = FromAddress.Remove(0, FromAddress.IndexOf(','));
                    fromMailAddr = new MailAddress(fromAddr,
                                                   fromAddrDisplayAs,
                                                   System.Text.Encoding.UTF8);
                }
                else
                {
                    fromMailAddr = new MailAddress(FromAddress, FromAddress, System.Text.Encoding.UTF8);
                }

                mailMessage.From = fromMailAddr;

                string[] receipents = ToAddress.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                if (this.UseDefaultCredentials)
                {
                    smtpClient.UseDefaultCredentials = this.UseDefaultCredentials;
                }
                else
                {
                    smtpClient.UseDefaultCredentials = this.UseDefaultCredentials;
                    smtpClient.Credentials           = new NetworkCredential(this.SMTPCredentials.UserName, this.SMTPCredentials.SecurePassword);
                }

                smtpClient.EnableSsl      = this.IsSSLEnabled;
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;

                foreach (string receipent in receipents)
                {
                    if (receipent.IndexOf(',') != -1)
                    {
                        string toAddr          = receipent.Remove(receipent.IndexOf(','), receipent.Length);
                        string toAddrDisplayAs = receipent.Remove(0, receipent.IndexOf(','));
                        toMailAddr = new MailAddress(toAddr,
                                                     toAddrDisplayAs,
                                                     System.Text.Encoding.UTF8);
                    }
                    else
                    {
                        toMailAddr = new MailAddress(receipent, receipent, System.Text.Encoding.UTF8);
                    }

                    mailMessage.To.Add(toMailAddr);
                }
                mailMessage.Body    = MessageBody;
                mailMessage.Subject = Subject;

                mailMessage.BodyEncoding    = Encoding.UTF8;
                mailMessage.SubjectEncoding = Encoding.UTF8;


                await smtpClient.SendMailAsync(mailMessage);
            }

            catch (Exception e)
            {
                LogWriter.CreateLogEntry(string.Format("{0}; {1}; {2}", DateTime.Now, e.Message, e.InnerException.Message));
            }
        }
Example #15
0
        /// <summary>
        /// Register to PipeServer enableing to receive messages from lsm
        /// </summary>
        public void Register()
        {
            Messenger.Default.Register <NotificationMessage <string> >(
                this, nm => {
                string[] cmdLineArgs = nm.Notification.Split(';');

                /* Processing the Message from LSM.Basic.Online
                 *
                 * possible contents (copy of pipeserver):
                 *
                 * int version = _ttoi(param[0]);
                 * int eventId = _ttoi(param[1]);
                 * CString date = param[2];
                 * CString wnAddr = param[3];
                 * CString serNumb = param[4];
                 * CString param1 = param[5];
                 * CString param2 = param[6];
                 * CString param3 = param[7];
                 * CString saName = param[8];
                 * CString lockName = param[9];
                 * CString transName = param[10];
                 *
                 */

                try
                {
                    switch (nm.Content)
                    {
                    case "PipeServerMessage":
                        switch (Enum.GetName(typeof(EventType), Convert.ToInt32(cmdLineArgs[1])))
                        {
                        case "UnlockingEvent":
                            dynamicEventObject = new EventObjectModel(null,
                                                                      Enum.GetName(typeof(EventType),
                                                                                   Convert.ToInt32(cmdLineArgs[1])),
                                                                      cmdLineArgs[8],
                                                                      string.IsNullOrWhiteSpace(cmdLineArgs[10].Replace("/", string.Empty).Replace("\"", string.Empty)) ?
                                                                      string.Format("G1 TID: {0}", cmdLineArgs[6]) :
                                                                      cmdLineArgs[10].Remove(
                                                                          (cmdLineArgs[10].IndexOf('/') >= 0 ? cmdLineArgs[10].IndexOf('/') : 0),
                                                                          (cmdLineArgs[10].Length - (cmdLineArgs[10].IndexOf('/') >= 0 ? cmdLineArgs[10].IndexOf('/') : cmdLineArgs[10].Length))),

                                                                      cmdLineArgs[9].Remove(
                                                                          (cmdLineArgs[9].IndexOf('/') >= 0 ? cmdLineArgs[9].IndexOf('/') : 0),
                                                                          (cmdLineArgs[9].Length - (cmdLineArgs[9].IndexOf('/') >= 0 ? cmdLineArgs[9].IndexOf('/') : cmdLineArgs[9].Length))),

                                                                      Convert.ToInt32(cmdLineArgs[5]),

                                                                      string.IsNullOrWhiteSpace(cmdLineArgs[10].Replace("/", string.Empty).Replace("\"", string.Empty)) ?
                                                                      string.Format("G1 TID: {0}", cmdLineArgs[6]) :
                                                                      cmdLineArgs[10].Remove(0, cmdLineArgs[10].IndexOf('/') >= 0 ? cmdLineArgs[10].IndexOf('/') : 0),
                                                                      cmdLineArgs[9].Remove(0, cmdLineArgs[9].IndexOf('/') >= 0 ? cmdLineArgs[9].IndexOf('/') : 0),

                                                                      Enum.GetName(typeof(AccessType), Convert.ToInt32(cmdLineArgs[7])));



                            EventComparer();
                            break;

                        case "InputEvent":

                            string inputNum;
                            string edgeType;

                            if (cmdLineArgs[7] != "0")
                            {
                                inputNum = Enum.GetName(typeof(InputsByName), InputsByName.Input3);
                                edgeType = Enum.GetName(typeof(InputEdgeTriggerType), Convert.ToInt32(cmdLineArgs[7]));
                            }


                            else if (cmdLineArgs[6] != "0")
                            {
                                inputNum = Enum.GetName(typeof(InputsByName), InputsByName.Input2);
                                edgeType = Enum.GetName(typeof(InputEdgeTriggerType), Convert.ToInt32(cmdLineArgs[6]));
                            }


                            else
                            {
                                inputNum = Enum.GetName(typeof(InputsByName), InputsByName.Input1);
                                edgeType = Enum.GetName(typeof(InputEdgeTriggerType), Convert.ToInt32(cmdLineArgs[5]));
                            }



                            dynamicEventObject = new EventObjectModel(null,
                                                                      Enum.GetName(typeof(EventType), Convert.ToInt32(cmdLineArgs[1])),
                                                                      cmdLineArgs[3],
                                                                      inputNum,
                                                                      edgeType);

                            EventComparer();
                            break;

                        case "DoorHasBeenOpened":
                        case "DoorStaysOpenTooLong":
                        case "DoorHasBeenClosed":
                        case "DoorHasBeenLocked":
                        case "DoorHasBeenSecured":
                        case "DoorHasBeenManipulated":
                        case "DoorSensorError":
                        case "DoorHasBeenClosedAfterTooLongOpened":

                            dynamicEventObject = new EventObjectModel(null,
                                                                      Enum.GetName(typeof(EventType), Convert.ToInt32(cmdLineArgs[1])),
                                                                      cmdLineArgs[8],
                                                                      cmdLineArgs[9].Remove(
                                                                          (cmdLineArgs[9].IndexOf('/') >= 0 ? cmdLineArgs[9].IndexOf('/') : 0),
                                                                          (cmdLineArgs[9].Length - (cmdLineArgs[9].IndexOf('/') >= 0 ? cmdLineArgs[9].IndexOf('/') : cmdLineArgs[9].Length))),

                                                                      Convert.ToInt32(cmdLineArgs[5]),

                                                                      cmdLineArgs[9].Remove(0, cmdLineArgs[9].IndexOf('/') >= 0 ? cmdLineArgs[9].IndexOf('/') : 0));

                            EventComparer();

                            break;
                        }


                        break;

                    default:
                        break;
                    }
                }catch (Exception e)
                {
                    LogWriter.CreateLogEntry(string.Format("Unable to Parse Message: {0}; {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""));
                    return;
                }
            });
        }
Example #16
0
        /// <summary>
        /// Checks the specified state.
        /// </summary>
        /// <param name="state">The state.</param>
        private void Check(object state)
        {
            try
            {
                if (isUserNotified && !allowUpdate)
                {
                    return;
                }

                if (allowUpdate && !_updating)
                {
                    _timer.Change(5000, DefaultCheckInterval * 1000);

                    _updating = true;
                    Update();
                    _updating      = false;
                    isUserNotified = false;
                    Log.Write("Check ending.");
                    return;
                }
                Log.Write("Check starting.");

                if (_updating)
                {
                    Log.Write("Updater is already updating.");
                    Log.Write("Check ending.");
                    return;
                }

                var remoteUri = new Uri(_localConfig.RemoteConfigUri);

                Log.Write("Fetching '{0}'.", remoteUri.AbsoluteUri);
                var http = new Fetch {
                    Retries = 5, RetrySleep = 30000, Timeout = 30000
                };
                try
                {
                    http.Load(remoteUri.AbsoluteUri);

                    if (!http.Success)
                    {
                        Log.Write("Fetch error: {0}", http.Response.StatusDescription);
                        this._remoteConfig = null;
                        return;
                    }
                }

                catch (Exception e)
                {
                    LogWriter.CreateLogEntry(string.Format("{0}\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""));
                    this._remoteConfig = null;
                    return;
                }

                string data = Encoding.UTF8.GetString(http.ResponseData);
                this._remoteConfig = new Manifest(data);

                //string.Format("{0}{1}",this._localConfig.RemoteConfigUri,_settings.DefaultLanguage == "german" ? "/de-de" : "/en-us")
                if (this._remoteConfig == null)
                {
                    return;
                }

                if (this._localConfig.SecurityToken != this._remoteConfig.SecurityToken)
                {
                    Log.Write("Security token mismatch.");
                    return;
                }
                Log.Write("Remote config is valid.");
                Log.Write("Local version is  {0}.", this._localConfig.Version);
                Log.Write("Remote version is {0}.", this._remoteConfig.Version);

                if (this._remoteConfig.Version == this._localConfig.Version)
                {
                    Log.Write("Versions are the same.");
                    Log.Write("Check ending.");
                    return;
                }
                if (this._remoteConfig.Version < this._localConfig.Version)
                {
                    Log.Write("Remote version is older. That's weird.");
                    Log.Write("Check ending.");
                    return;
                }

                Log.Write("Remote version is newer. Updating.");
                _timer.Change(0, 1000);

                if (!allowUpdate && !isUserNotified)
                {
                    isUserNotified = true;
                    newVersionAvailable(this, null);
                    return;
                }
            }
            catch (Exception e)
            {
                LogWriter.CreateLogEntry(string.Format("{0}: {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""));
            }
        }
Example #17
0
        public SettingsReaderWriter()
        {
            try
            {
                appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

                appDataPath = Path.Combine(appDataPath, "RFiDGear");

                if (!Directory.Exists(appDataPath))
                {
                    Directory.CreateDirectory(appDataPath);
                }

                XmlWriterSettings xmlSettings = new XmlWriterSettings();
                xmlSettings.Encoding = new UTF8Encoding(false);

                xmlWriter = XmlWriter.Create(Path.Combine(appDataPath, _updateConfigFileFileName), xmlSettings);
                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("Manifest");
                xmlWriter.WriteAttributeString("version", string.Format("{0}.{1}.{2}", Version.Major, Version.Minor, Version.Build));

                xmlWriter.WriteEndElement();
                xmlWriter.Close();

                var doc = new XmlDocument();
                doc.Load(Path.Combine(appDataPath, _updateConfigFileFileName));

                if (doc.SelectSingleNode("//CheckInterval") == null)
                {
                    XmlElement CheckIntervalElem   = doc.CreateElement("CheckInterval");
                    XmlElement RemoteConfigUriElem = doc.CreateElement("RemoteConfigUri");
                    XmlElement SecurityTokenElem   = doc.CreateElement("SecurityToken");
                    XmlElement BaseUriElem         = doc.CreateElement("BaseUri");
                    XmlElement PayLoadElem         = doc.CreateElement("Payload");

                    doc.DocumentElement.AppendChild(CheckIntervalElem);
                    doc.DocumentElement.AppendChild(RemoteConfigUriElem);
                    doc.DocumentElement.AppendChild(SecurityTokenElem);
                    doc.DocumentElement.AppendChild(BaseUriElem);
                    doc.DocumentElement.AppendChild(PayLoadElem);

                    CheckIntervalElem.InnerText   = _updateInterval.ToString();
                    RemoteConfigUriElem.InnerText = _updateURL;
                    SecurityTokenElem.InnerText   = _securityToken;
                    BaseUriElem.InnerText         = _baseUri;
                    PayLoadElem.InnerText         = _payload;

                    doc.Save(Path.Combine(appDataPath, _updateConfigFileFileName));
                }
            }
            catch (Exception e)
            {
                LogWriter.CreateLogEntry(string.Format("{0}\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""));
            }

            if (!File.Exists(Path.Combine(appDataPath, _settingsFileFileName)))
            {
                try
                {
                    defaultSpecification = new DefaultSpecification(true);

                    var serializer = new XmlSerializer(defaultSpecification.GetType());

                    var txtWriter = new StreamWriter(Path.Combine(appDataPath, _settingsFileFileName));

                    serializer.Serialize(txtWriter, defaultSpecification);

                    txtWriter.Close();
                }
                catch (Exception e)
                {
                    LogWriter.CreateLogEntry(string.Format("{0}; {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""));
                }
            }
            //else
            //ReadSettings();
        }
Example #18
0
        /// <summary>
        /// Updates this instance.
        /// </summary>
        private void Update()
        {
            Log.Write("Updating '{0}' files.", this._remoteConfig.Payloads.Length);

            // Clean up failed attempts.
            if (Directory.Exists(Path.Combine(appDataPath, WorkPath)))
            {
                Log.Write("WARNING: Work directory already exists.");
                try { Directory.Delete(Path.Combine(appDataPath, WorkPath), true); }
                catch (IOException e)
                {
                    LogWriter.CreateLogEntry(string.Format("{0}\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""));
                    return;
                }
            }

            else
            {
                try{
                    Directory.CreateDirectory(Path.Combine(appDataPath, WorkPath));
                }
                catch (Exception e)
                {
                    LogWriter.CreateLogEntry(string.Format("{0}\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""));
                    return;
                }
            }


            // Download files in manifest.
            foreach (string update in this._remoteConfig.Payloads)
            {
                Log.Write("Fetching '{0}'.", update);
                var url  = this._remoteConfig.BaseUri + (_settings.DefaultLanguage == "german" ? "de-de/" : "en-us/") + update;                //TODO: make this localizable
                var file = Fetch.Get(url);
                if (file == null)
                {
                    Log.Write("Fetch failed.");
                    return;
                }
                var info = new FileInfo(Path.Combine(Path.Combine(appDataPath, WorkPath), update));
                Directory.CreateDirectory(info.DirectoryName);
                File.WriteAllBytes(Path.Combine(Path.Combine(appDataPath, WorkPath), update), file);

                // Unzip
                if (Regex.IsMatch(update, @"\.zip"))
                {
                    try
                    {
                        var zipfile = Path.Combine(WorkPath, update);
                        using (var zip = ZipFile.Read(zipfile))
                            zip.ExtractAll(WorkPath, ExtractExistingFileAction.Throw);
                        File.Delete(zipfile);
                    }
                    catch (Exception e)
                    {
                        LogWriter.CreateLogEntry(string.Format("{0}\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""));
                        return;
                    }
                }
            }

            if (isUserNotified && allowUpdate)
            {
                Process          p    = new Process();
                ProcessStartInfo info = new ProcessStartInfo("msiexec.exe");
                info.Arguments = string.Format("/i {0}", Path.Combine(appDataPath, WorkPath, "Setup.msi"));


                try{
                    p.StartInfo = info;
                    p.Start();

                    thisprocess.Dispose();

                    Environment.Exit(0);
                }

                catch (Exception e)
                {
                    LogWriter.CreateLogEntry(string.Format("{0}\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""));
                    return;
                }
            }

            // Change the currently running executable so it can be overwritten.
//			Process thisprocess = Process.GetCurrentProcess();
//			string me = thisprocess.MainModule.FileName;
//
//			var rootDirectory = new DirectoryInfo(Path.GetDirectoryName(me));
//			var rootFiles = rootDirectory.GetFiles("*.*", SearchOption.TopDirectoryOnly);
//
//			foreach (FileInfo file in rootFiles)
//			{
//				string bak = file.FullName + ".bak";
//				Log.Write("Renaming current file to '{0}'.", bak);
//				File.Move(file.FullName, bak);
//			}
//
//			// Write out the new manifest.
//			_remoteConfig.Write(Path.Combine(WorkPath, _localConfigFile.Name));
//
//			// Copy everything.
//			var workDirectory = new DirectoryInfo(WorkPath);
//			var workFiles = workDirectory.GetFiles("*.*", SearchOption.AllDirectories);
//			foreach (FileInfo file in workFiles)
//			{
//				Log.Write("installing file '{0}'.", rootDirectory + "\"" + file.Name);
//				//Directory.CreateDirectory(new FileInfo(destination).DirectoryName);
//				file.CopyTo(Path.Combine(rootDirectory.FullName, file.Name), true);
//				if(File.Exists(Path.Combine(rootDirectory.FullName, file.Name + ".bak" )))
//					try {
//					File.Delete(Path.Combine(rootDirectory.FullName, file.Name + ".bak"));
//				}
//				catch(Exception e) {
//
//				}
//
//			}

            // Clean up.
        }