Esempio n. 1
0
        private void DecodeFileFromBase64(object parameterObject)
        {
            try
            {
                //_encodingSucceeded = false;
                List <object> parms              = (List <object>)parameterObject;
                PFFileEncoder encoder            = (PFFileEncoder)parms[0];
                string        encryptedInputFile = Convert.ToString(parms[1]);
                string        tempFileName       = Convert.ToString(parms[2]);
                StatusTimer   st = (StatusTimer)parms[3];

                encoder.DecodeFileFromBase64(encryptedInputFile, tempFileName);

                //_encodingSucceeded = true;
            }
            catch (System.Exception ex)
            {
                //_encodingSucceeded = false;
                _msg.Length = 0;
                _msg.Append(AppGlobals.AppMessages.FormatErrorMessage(ex));
                AppMessages.DisplayErrorMessage(_msg.ToString());
            }
            finally
            {
                ;
            }
        }
        private void HandleStatusTimerTick(object sender, EventArgs e)
        {
            StatusTimer.Stop();
            var status = VideoDedupDlg.WcfProxy.GetVideoComparisonStatus(
                ComparisonToken.Value,
                ImageComparisonIndex);

            UpdateVideoComparisonResult(status.VideoCompareResult);
            UpdateImageComparisonResult(status);

            if (!status.ImageComparisons.Any())
            {
                StatusTimer.Start();
                return;
            }

            ImageComparisonIndex = status.ImageComparisons
                                   .Max(kvp => kvp.Item1);
            ImageComparisonIndex += 1;
            var maxImages = (int)NumMaxImageComparison.Value;

            if (ImageComparisonIndex >= maxImages)
            {
                VideoDedupDlg.WcfProxy.CancelCustomVideoComparison(
                    ComparisonToken.Value);
                return;
            }

            StatusTimer.Start();
        }
Esempio n. 3
0
        /// <summary>
        /// Shutsdown the ClientManager server and socket
        /// </summary>
        public void Shutdown()
        {
            // Stop accepting new connections
            IgnoreNewConnections = true;
            Exiting = true;

            // Discard the poll timer
            PollTimer.Stop();
            PollTimer.Dispose();
            StatusTimer.Stop();
            StatusTimer.Dispose();

            // Disconnected all connected clients
            Console.WriteLine("Disconnecting all users...");
            Parallel.ForEach(Clients.Values, client => client.Disconnect(DisconnectReason.ForcedServerShutdown));
            Parallel.ForEach(Processing.Values, client => client.Disconnect(DisconnectReason.ForcedServerShutdown));

            // Update the database
            try
            {
                // Set everyone's online session to 0
                databaseDriver.Execute("UPDATE profiles SET status=0, sesskey = NULL");
            }
            catch (Exception e)
            {
                LogWriter.Log.WriteException(e);
            }

            // Update Connected Clients in the Database
            Clients.Clear();

            // Tell the base to dispose all free objects
            Dispose();
        }
Esempio n. 4
0
        private void AlarmsActivate_Click(object sender, EventArgs e)
        {
            AlarmsLoad.Enabled = false;
            Active             = !Active;
            if (Active)
            {
                BattlelistTimer          = new Timer(AlarmTimeIntervals);
                BattlelistTimer.Execute += BattlelistTimer_Execute;
                StatusTimer.Interval     = StatusTimeInterval;
                StatusTimer.Enabled      = true;
                StatusTimer.Start();
                AlarmsActivate.Text = "Deactivate";
                BattlelistTimer.Start();
            }
            else
            {
                StatusTimer.Stop();
                StatusTimer.Enabled = false;
                AlarmsActivate.Text = "Activate";
                BattlelistTimer.Stop();
            }

            statusText         = "";
            RunStatus          = false;
            Tabs.Enabled       = !Active;
            AlarmsLoad.Enabled = !Active;
        }
Esempio n. 5
0
        private void stTimer()
        {
            Random rand = new Random();

            fortimerinterval1    = rand.Next(300, 500);
            StatusTimer.Interval = fortimerinterval1;
            StatusTimer.Enabled  = true;
            StatusTimer.Start();
        }
 protected override void OnClosed(EventArgs e)
 {
     if (ComparisonToken.HasValue)
     {
         StatusTimer.Stop();
         VideoDedupDlg.WcfProxy.CancelCustomVideoComparison(
             ComparisonToken.Value);
     }
     base.OnClosed(e);
 }
Esempio n. 7
0
        private void StatusTimer_Tick(object sender, EventArgs e)

        {
            SplashScreenStatus.Text = "در حال " + LoadingModules[i];
            stTimer();
            i++;
            if (i >= 7)
            {
                StatusTimer.Stop();
                k = 1;
            }
        }
Esempio n. 8
0
 public Form1()
 {
     InitializeComponent();
     //启动timer,默认5分钟
     StatusTimer.Interval = 60000;
     StatusTimer.Elapsed += StatusTimer_Elapsed;
     StatusTimer.Start();
     //打开后自动连接
     //ConnectSocketServer();
     ConnectSocketServerNew();
     //结束已打开进程
     closeOpenedProcess();
 }
            private bool disposedValue = false; // To detect redundant calls

            protected virtual void Dispose(bool disposing)
            {
                if (!disposedValue)
                {
                    if (disposing)
                    {
                        TaskTimer?.Dispose();
                        TaskTimer = null;
                        StatusTimer?.Dispose();
                        StatusTimer = null;
                    }
                    disposedValue = true;
                }
            }
Esempio n. 10
0
        private void BtnClientConfig_Click(object sender, EventArgs e)
        {
            using (var dlg = new ClientConfigDlg())
            {
                dlg.Settings = Settings;

                if (dlg.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                Settings = dlg.Settings;
                SaveConfig(Settings);
                _ = StatusTimer.StartSingle(Settings.StatusRequestInterval);
            }
        }
Esempio n. 11
0
    //called from the StatusTimer
    public void TriggerStatus(Status status, StatusTimer timer, float acumTime, StatusEffects effect)
    {
        if (isEnemy)
        {
            effect.ProcEffect(timer);
            enemy.CalculateStatus(effect);
            //if the monster has been inflicted with the status for longer than the duration that the status can be inflicted for, then it is no longer afflicted. if not, run the status trigger again
            if (acumTime <= status.duration)
            {
                StartCoroutine(timer.TriggerEffect());
                var display = Instantiate(enemy.damageText, transform.position, Quaternion.identity);
                display.transform.SetParent(enemy.enemyCanvas.transform, true);
                display.GetComponentInChildren <TMP_Text>().text = "-" + status.name;
                Destroy(display, display.GetComponent <Animator>().GetCurrentAnimatorStateInfo(0).length);
            }
            else
            {
                if (statuses.Contains(status))
                {
                    effect.HealStatus(this, status);
                }
            }
        }
        else
        {
            //StatusEffects effect = new StatusEffects(this, status, false);
            effect.ProcEffect(timer);
            CalculateStatus(effect);

            //if the monster has been inflicted with the status for longer than the duration that the status can be inflicted for, then it is no longer afflicted. if not, run the status trigger again
            if (acumTime <= status.duration)
            {
                StartCoroutine(timer.TriggerEffect());
                var display = Instantiate(enemy.damageText, transform.position, Quaternion.identity);
                display.transform.SetParent(enemy.enemyCanvas.transform, false);
                display.GetComponentInChildren <TMP_Text>().text = "-" + status.name;
                Destroy(display, display.GetComponent <Animator>().GetCurrentAnimatorStateInfo(0).length);
            }
            else
            {
                if (statuses.Contains(status))
                {
                    effect.HealStatus(this, status);
                }
            }
        }
    }
Esempio n. 12
0
    //public StatusEffects(Monster monster, Status status, bool isEnemy)
    //{


    //}

    public void ProcEffect(StatusTimer timer)
    {
        Monster monster = timer.Monster;
        //Enemy Enemy = timer.Enemy;
        Status status = timer.Status;


        //monster.attack -= monster.attack * status.atkDrop;
        //monster.defense -= monster.defense * status.defDrop;
        //monster.evasion -= monster.evasion * status.evasionDrop;
        //monster.hp -= (monster.hp * status.hpDrop);
        //monster.speed -= monster.speed * status.speedDrop;
        //monster.energyGeneration -= monster.energyGeneration * status.enGenDrop;
        //monster.precision -= monster.precision * status.precDrop;

        if (status.hpDrop != 0)
        {
            monster.info.HP.AddModifier(new StatModifier(status.hpDrop, StatModType.PercentMult, this, timer.Status.name));
        }
        monster.info.currentHP = monster.info.currentHP - (monster.info.maxHP * -status.hpDrop);
        if (status.atkDrop != 0)
        {
            monster.info.Attack.AddModifier(new StatModifier(status.atkDrop, StatModType.PercentMult, this, timer.Status.name));
        }
        if (status.defDrop != 0)
        {
            monster.info.Defense.AddModifier(new StatModifier(status.defDrop, StatModType.PercentMult, this, timer.Status.name));
        }
        if (status.speedDrop != 0)
        {
            monster.info.Speed.AddModifier(new StatModifier(status.speedDrop, StatModType.PercentMult, this, timer.Status.name));
        }
        if (status.enGenDrop != 0)
        {
            monster.info.EnergyGeneration.AddModifier(new StatModifier(status.enGenDrop, StatModType.PercentMult, this, timer.Status.name));
        }
        if (status.precDrop != 0)
        {
            monster.info.Precision.AddModifier(new StatModifier(status.precDrop, StatModType.PercentMult, this, timer.Status.name));
        }

        Monster = monster;


        monster.MonsterStatMods();
    }
Esempio n. 13
0
    //statuses are added from monster attacks or from tiles on the map. they are added here and the statuses being calculating
    public void AddStatus(Status status)
    {
        StatusTimer timer = new StatusTimer(gameObject.GetComponent <Monster>(), status);

        StartCoroutine(timer.TriggerEffect());
        if (statuses.Contains(status))
        {
            //
        }
        else
        {
            statuses.Add(status);
            if (GameManager.Instance.GetComponent <AllStatusEffects>().allStatusDict.ContainsKey(status.name))
            {
                statusIcons[statuses.Count - 1].GetComponent <SpriteRenderer>().sprite = GameManager.Instance.GetComponent <AllStatusEffects>().allStatusDict[status.name].statusSprite;
            }
        }
    }
Esempio n. 14
0
        private void tsb_SaveImageToFile_Click(object sender, EventArgs e)
        {
            string strMsg;
            string strImageFile;

            fnc_ClearStatus();
            strImageFile = fnc_SaveImageToFile();
            if (strImageFile != "")
            {
                strMsg = "Save image file [ " + strImageFile + " ] finshed.";
            }
            else
            {
                strMsg = "Save image file [ " + strImageFile + " ] failed.";
            }

            tsl_msg.Text = strMsg;
            StatusTimer.Start();
        }
Esempio n. 15
0
        private void tsb_SaveToClipboard_Click(object sender, EventArgs e)
        {
            string strMsg;
            bool   blRes;

            fnc_ClearStatus();
            blRes = fnc_SaveIamgeToClip();
            if (blRes == true)
            {
                strMsg = "Save image to clipboard finshed.";
            }
            else
            {
                strMsg = "Save image to clipboard failed.";
            }

            tsl_msg.Text = strMsg;
            StatusTimer.Start();
        }
Esempio n. 16
0
        /// <summary>
        /// Shutsdown the ClientManager server and socket
        /// </summary>
        public void Shutdown()
        {
            // Stop accepting new connections
            base.IgnoreNewConnections = true;
            Exiting = true;

            // Unregister events so we dont get a shit ton of calls
            GpcmClient.OnSuccessfulLogin -= GpcmClient_OnSuccessfulLogin;
            GpcmClient.OnDisconnect      -= GpcmClient_OnDisconnect;

            // Discard the poll timer
            PollTimer.Stop();
            PollTimer.Dispose();
            StatusTimer.Stop();
            StatusTimer.Dispose();

            // Disconnected all connected clients
            Console.WriteLine("Disconnecting all users...");
            Parallel.ForEach(Clients.Values, client => client.Disconnect(DisconnectReason.ForcedServerShutdown));
            Parallel.ForEach(Processing.Values, client => client.Disconnect(DisconnectReason.ForcedServerShutdown));

            // Update the database
            try
            {
                // Set everyone's online session to 0
                using (Database.GamespyDatabase db = new Database.GamespyDatabase())
                    db.Execute("UPDATE player SET online=0");
            }
            catch (Exception e)
            {
                Program.ErrorLog.Write("WARNING: [GpcmServer.Shutdown] Failed to update client database: " + e.Message);
            }

            // Update Connected Clients in the Database
            Clients.Clear();

            // Shutdown the listener socket
            base.ShutdownSocket();

            // Tell the base to dispose all free objects
            base.Dispose();
        }
        private void BtnStartComparison_Click(object sender, EventArgs e)
        {
            if (ComparisonToken.HasValue)
            {
                StatusTimer.Stop();
                VideoDedupDlg.WcfProxy.CancelCustomVideoComparison(
                    ComparisonToken.Value);
            }

            CleanUpResult();

            if ((int)NumMaxImageComparison.Value <= 0)
            {
                return;
            }

            var startData = VideoDedupDlg.WcfProxy.StartCustomVideoComparison(
                new CustomVideoComparisonData
            {
                AlwaysLoadAllImages       = true,
                LeftFilePath              = TxtLeftFilePath.Text,
                RightFilePath             = TxtRightFilePath.Text,
                MaxImageCompares          = (int)NumMaxImageComparison.Value,
                MaxImageDifferencePercent =
                    (int)NumMaxDifferentPercentage.Value,
                MaxDifferentImages = (int)NumMaxDifferentImages.Value,
            });

            if (startData.ComparisonToken == null)
            {
                _ = MessageBox.Show(
                    "Couldn't start comparison." + Environment.NewLine
                    + startData.ErrorMessage,
                    "Erro starting comparison",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }
            ComparisonToken = startData.ComparisonToken;

            StatusTimer.Start();
        }
Esempio n. 18
0
        /// <summary>
        /// Shutsdown the ClientManager server and socket
        /// </summary>
        public void Shutdown()
        {
            // Stop accepting new connections
            IgnoreNewConnections = true;
            Exiting = true;


            // Unregister events so we dont get a shit ton of calls
            GPCMClient.OnSuccessfulLogin -= ClientSuccessfulLogin;
            GPCMClient.OnDisconnect      -= ClientDisconnected;

            // Discard the poll timer
            PollTimer.Stop();
            PollTimer.Dispose();
            StatusTimer.Stop();
            StatusTimer.Dispose();

            // Disconnected all connected clients
            Console.WriteLine("Disconnecting all users...");
            Parallel.ForEach(Clients.Values, client => client.DisconnectByReason(DisconnectReason.ForcedServerShutdown));
            Parallel.ForEach(Processing.Values, client => client.DisconnectByReason(DisconnectReason.ForcedServerShutdown));

            // Update the database
            try
            {
                // Set everyone's online session to 0
                LoginQuery.ResetStatusAndSessionKey();
            }
            catch (Exception e)
            {
                LogWriter.Log.WriteException(e);
            }

            // Update Connected Clients in the Database
            Clients.Clear();

            DB.Dispose();

            // Tell the base to dispose all free objects
            Dispose();
        }
Esempio n. 19
0
 protected override void Dispose(bool disposingManagedResources)
 {
     if (_disposed)
     {
         return;
     }
     _disposed = true;
     if (disposingManagedResources)
     {
     }
     PollTimer?.Stop();
     PollTimer?.Dispose();
     StatusTimer?.Stop();
     StatusTimer?.Dispose();
     // Disconnected all connected clients
     Console.WriteLine("Disconnecting all users...");
     //Parallel.ForEach(LoggedInSession.Values, client => client.DisconnectByReason(DisconnectReason.ForcedServerShutdown));
     //Parallel.ForEach(InLoginSession.Values, client => client.DisconnectByReason(DisconnectReason.ForcedServerShutdown));
     //LoginQuery.ResetAllStatusAndSessionKey();
     LoggedInSession.Clear();
     DB.Dispose();
     base.Dispose(disposingManagedResources);
 }
Esempio n. 20
0
        private bool fnc_DeleteListItem(int int_sel_idx)
        {
            bool blRes;
            int  intCnt;

            string[] strTempList;
            string   strSelText;
            string   strMsg;

            try
            {
                strTempList = new string[CON_COB_URL_CNT];

                intCnt = 0;
                // コンボアイテム取得
                for (intCnt = 0; intCnt < CON_COB_URL_CNT; intCnt++)
                {
                    if (intCnt < cob_url.Items.Count)
                    {
                        strTempList[intCnt] = cob_url.Items[intCnt].ToString().Trim();
                    }
                    else
                    {
                        strTempList[intCnt] = "";
                    }
                }

                // 指定されたアイテムをコンボリストから削除
                strSelText = "";
                cob_url.Items.Clear();
                for (intCnt = 0; intCnt < CON_COB_URL_CNT; intCnt++)
                {
                    if (strTempList[intCnt] != "")
                    {
                        if (intCnt != int_sel_idx)
                        {
                             cob_url.Items.Add(strTempList[intCnt]);
                        }
                        else
                        {
                            strSelText = strTempList[intCnt];
                        }
                    }
                }

                // URL再設定
                if (int_sel_idx == 0)
                {
                    cob_url.Text = cob_url.Items[0].ToString();
                }
                else
                {
                    cob_url.Text = cob_url.Items[int_sel_idx - 1].ToString();
                }

                // 削除されたURLをステータスバーに表示
                strMsg       = "Delete Url [" + strSelText + "] From List ComboBox.";
                tsl_msg.Text = strMsg;
                StatusTimer.Start();

                //// 設定されたURLに遷移
                //if (cob_url.Text.Trim() != "")
                //{
                //    TargetWebBrowser.Navigate(cob_url.Text);
                //}

                blRes = true;
            }
            catch (Exception ex)
            {
                blRes = false;
                CommonLogger.WriteLine(ex.Message);
            }
            return(blRes);
        }
Esempio n. 21
0
        /// <summary>
        ///  Decrypts using a byte array. The encrypted input file is loaded into a stream and then decrypted and saved as unencrypted data to the output file.
        ///  Method uses techniques to handle cases where file being decrypted is very large.
        ///  This helps deal with very large files that can cause out of memory exceptions during decryption process.
        /// </summary>
        /// <param name="encryptedInputFile">Full path to file containing the encrypted data.</param>
        /// <param name="outputFile">Full path to file that will contain decrypted data.</param>
        /// <param name="st">A StatusTimer object to use for timing the decryption.</param>
        /// <returns>Returns path to output file.</returns>
        public string DecryptBinary(string encryptedInputFile, string outputFile, StatusTimer st)
        {
            if (st == null)
            {
                throw new ArgumentNullException("StatusTime must be specified for this routine.");
            }
            if (String.IsNullOrEmpty(encryptedInputFile) || String.IsNullOrEmpty(outputFile))
            {
                throw new ArgumentNullException("Paths to both the encrypted input file and the output file need to be specified.");
            }

            if (KeyIsValid(GetStringFromByteArray(_key)) == false)
            {
                throw new System.Exception("Invalid length for Key.");
            }
            if (IVIsValid(GetStringFromByteArray(_iv)) == false)
            {
                throw new System.Exception("Invalid length for IV.");
            }


            FileStream   fsInput      = null;
            FileStream   fsEncrypted  = null;
            CryptoStream cryptoStream = null;

            try
            {
                fsInput      = new FileStream(encryptedInputFile, FileMode.Open, FileAccess.Read);
                fsEncrypted  = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
                cryptoStream = new CryptoStream(fsEncrypted, _cryptoProvider.CreateDecryptor(_key, _iv), CryptoStreamMode.Write);

                int    bufferLength  = _bufferLength;
                byte[] buffer        = new byte[bufferLength];
                int    contentLength = 0;
                long   totalBytes    = 0;

                contentLength = fsInput.Read(buffer, 0, bufferLength);
                while (contentLength != 0)
                {
                    cryptoStream.Write(buffer, 0, contentLength);
                    cryptoStream.Flush();
                    contentLength = fsInput.Read(buffer, 0, bufferLength);
                    totalBytes   += contentLength;
                    if (currentStatusReport != null)
                    {
                        if (st.StatusReportDue())
                        {
                            currentStatusReport("Decryption", "In Progress", totalBytes, (int)st.GetElapsedTime().TotalSeconds, st.GetFormattedElapsedTime());
                        }
                    }
                }
                if (currentStatusReport != null)
                {
                    currentStatusReport("Decryption", "Completed", totalBytes, (int)st.GetElapsedTime().TotalSeconds, st.GetFormattedElapsedTime());
                }
                cryptoStream.FlushFinalBlock();
                cryptoStream.Close();
            }
            catch (System.Exception ex)
            {
                _msg.Length = 0;
                _msg.Append("Attempt to decrypt file ");
                _msg.Append(encryptedInputFile);
                _msg.Append(" failed. Verify you are using same key/iv pair used to encrypt.  Error message: ");
                _msg.Append("\r\n");
                _msg.Append(AppMessages.FormatErrorMessage(ex));
                throw new System.Exception(_msg.ToString());
            }
            finally
            {
                if (fsInput != null)
                {
                    fsInput.Close();
                }
                if (fsEncrypted != null)
                {
                    fsEncrypted.Close();
                }
            }


            return(outputFile);
        }
Esempio n. 22
0
 /// <summary>
 /// Handles the Tick event of the statusTimer control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
 private void statusTimer_Tick(object sender, EventArgs e)
 {
     StatusTimer.Stop();
     this.InfoStatusLabel.Visible = false;
 }
Esempio n. 23
0
        public string DecryptFile(pfEncryptorRequest decryptorRequest, ref bool decryptionSuccessful)
        {
            PFFileEncryptor decryptor       = null;
            string          decryptedResult = string.Empty;
            StatusTimer     st = new StatusTimer();

            try
            {
                if (String.IsNullOrEmpty(decryptorRequest.SourceObject))
                {
                    _msg.Length = 0;
                    _msg.Append("You must specify path to a file to decrypt.");
                    throw new System.Exception(_msg.ToString());
                }

                if (String.IsNullOrEmpty(decryptorRequest.DestinationObject))
                {
                    decryptorRequest.DestinationObject = decryptorRequest.SourceObject + ".decrypted";
                }

                if (string.IsNullOrEmpty(decryptorRequest.EncryptionKey) ||
                    string.IsNullOrEmpty(decryptorRequest.EncryptionIV))
                {
                    _msg.Length = 0;
                    _msg.Append("You must specify both Key and IV values.");
                    throw new System.Exception(_msg.ToString());
                }

                if (decryptorRequest.SourceObject == decryptorRequest.DestinationObject)
                {
                    _msg.Length = 0;
                    _msg.Append("Source and destination file paths are the same. They must be different for decryption routine to work.");
                    throw new System.Exception(_msg.ToString());
                }


                decryptor = new PFFileEncryptor(decryptorRequest.EncryptionAlgorithm);
                decryptor.currentStatusReport        += UpdateStatus;
                decryptor.StatusReportIntervalSeconds = _statusReportIntervalSeconds;

                decryptor.Key = decryptorRequest.EncryptionKey;
                decryptor.IV  = decryptorRequest.EncryptionIV;

                st.ShowElapsedTimeMilliseconds = false;
                st.Start();

                if (decryptorRequest.UseBinaryEncryption == false)
                {
                    if (decryptorRequest.DestinationObjectType == pfEncryptorObjectType.File)
                    {
                        decryptedResult = decryptor.Decrypt(decryptorRequest.SourceObject, decryptorRequest.DestinationObject, st);
                    }
                    else
                    {
                        decryptedResult = decryptor.Decrypt(decryptorRequest.SourceObject);
                    }
                }
                else
                {
                    decryptedResult = decryptor.DecryptBinary(decryptorRequest.SourceObject, decryptorRequest.DestinationObject, st);
                }

                decryptorRequest.DestinationObject = decryptedResult;

                decryptionSuccessful = true;
            }
            catch (System.Exception ex)
            {
                decryptionSuccessful = false;
                _msg.Length          = 0;
                _msg.Append(AppGlobals.AppMessages.FormatErrorMessage(ex));
                DisplayErrorMessage(_msg.ToString(), _saveErrorMessagesToAppLog);
            }
            finally
            {
                if (decryptor != null)
                {
                    decryptor.currentStatusReport -= UpdateStatus;
                    decryptor = null;
                }
                if (st != null)
                {
                    if (st.StatusTimerIsRunning)
                    {
                        st.Stop();
                    }
                    st = null;
                }
            }


            return(decryptedResult);
        }
Esempio n. 24
0
        private void SetStatus(string Text, Color Color, bool Temp = true)
        {
            if (StatusTimer != null && StatusTimer.IsEnabled)
            {
                StatusTimer.Stop();

                StatusText.Text      = Text;
                StatusBar.Background = new SolidColorBrush(Color);

                if (Temp)
                {
                    StatusTimer = new DispatcherTimer()
                    {
                        Interval = TimeSpan.FromSeconds(5)
                    };
                    StatusTimer.Tick += delegate
                    {
                        StatusBar.BeginAnimation(MarginProperty, new ThicknessAnimation()
                        {
                            From           = StatusBar.Margin,
                            To             = new Thickness(0, 0, 0, -30),
                            Duration       = TimeSpan.FromSeconds(0.5),
                            EasingFunction = new ExponentialEase()
                            {
                                EasingMode = EasingMode.EaseIn
                            }
                        });
                        StatusTimer.Stop();
                    };
                    StatusTimer.Start();
                }
            }
            else
            {
                StatusText.Text      = Text;
                StatusBar.Background = new SolidColorBrush(Color);

                if (Temp)
                {
                    StatusTimer = new DispatcherTimer()
                    {
                        Interval = TimeSpan.FromSeconds(5)
                    };
                    StatusTimer.Tick += delegate
                    {
                        StatusBar.BeginAnimation(MarginProperty, new ThicknessAnimation()
                        {
                            From           = StatusBar.Margin,
                            To             = new Thickness(0, 0, 0, -30),
                            Duration       = TimeSpan.FromSeconds(0.5),
                            EasingFunction = new ExponentialEase()
                            {
                                EasingMode = EasingMode.EaseIn
                            }
                        });
                        StatusTimer.Stop();
                    };
                }

                if (StatusBar.Margin.Bottom > -30)
                {
                    return;
                }
                var Animation = new ThicknessAnimation()
                {
                    From           = StatusBar.Margin,
                    To             = new Thickness(0, 0, 0, 0),
                    Duration       = TimeSpan.FromSeconds(0.5),
                    EasingFunction = new ExponentialEase()
                    {
                        EasingMode = EasingMode.EaseOut
                    }
                };
                if (Temp)
                {
                    Animation.Completed += delegate { StatusTimer.Start(); }
                }
                ;
                StatusBar.BeginAnimation(MarginProperty, Animation);
            }
        }
        //WARNING: Status timer can slow down processing significantly if processing is in a tight loop.
        public void StatusTimerTest(MainForm frm)
        {
            StatusTimer timer          = new StatusTimer();
            long        loopMax        = 100000000;
            int         statusInterval = 5;

            try
            {
                _msg.Length = 0;
                _msg.Append("StatusTimerTest started ...\r\n");
                WriteMessageToLog(_msg.ToString());

                timer.NumSecondsInterval = statusInterval;
                timer.Start();  //report status every two seconds

                _msg.Length = 0;
                _msg.Append("\r\nLooping ");
                _msg.Append(loopMax.ToString("#,##0"));
                _msg.Append(" times... \r\n");
                WriteMessageToLog(_msg.ToString());

                for (long num = 1; num <= loopMax; num++)
                {
                    if (timer.StatusReportDue())
                    {
                        _msg.Length = 0;
                        _msg.Append("Loop count = ");
                        _msg.Append(num.ToString("#,##0"));
                        _msg.Append(" Elapsed time to this point: ");
                        _msg.Append(timer.GetFormattedElapsedTime());
                        WriteMessageToLog(_msg.ToString());
                    }
                }
                _msg.Length = 0;
                _msg.Append("Loop count = ");
                _msg.Append(loopMax.ToString("#,##0"));
                _msg.Append(" Elapsed time to this point: ");
                _msg.Append(timer.GetFormattedElapsedTime());
                WriteMessageToLog(_msg.ToString());


                _msg.Length = 0;
                _msg.Append(Environment.NewLine);
                _msg.Append(Environment.NewLine);
                _msg.Append("Total Elapsed Time:   ");
                _msg.Append(timer.GetFormattedElapsedTime());
                _msg.Append(Environment.NewLine);
                _msg.Append("Elapsed milliseconds: ");
                _msg.Append(timer.GetElapsedTime().TotalMilliseconds.ToString("#,##0"));
                _msg.Append(Environment.NewLine);
                WriteMessageToLog(_msg.ToString());

                timer.Stop();
            }
            catch (System.Exception ex)
            {
                _msg.Length = 0;
                _msg.Append(AppGlobals.AppMessages.FormatErrorMessage(ex));
                WriteMessageToLog(_msg.ToString());
                AppMessages.DisplayErrorMessage(_msg.ToString(), _saveErrorMessagesToAppLog);
            }
            finally
            {
                _msg.Length = 0;
                _msg.Append("\r\n... StatusTimerTest finished.");
                WriteMessageToLog(_msg.ToString());
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Decrypts by loading encryptedInputFile to a string and then decrypting the string. Decrypted string is then written out as text to the outputFile.
        /// </summary>
        /// <param name="encryptedInputFile">Full path to file containing the encrypted data.</param>
        /// <param name="outputFile">Full path to file that will contain decrypted data.</param>
        /// <param name="st">A StatusTimer object to use for timing the encryption.</param>
        /// <returns>Returns path to output file.</returns>
        /// <remarks>This routine assumes the encrypted data is in base64 text format.</remarks>
        public string Decrypt(string encryptedInputFile, string outputFile, StatusTimer st)
        {
            //IStringEncryptor encryptor = new StringEncryptorAES();
            //PFStringEncryptor encryptor = new PFStringEncryptor(_encryptionAlgorithm);

            if (st == null)
            {
                throw new ArgumentNullException("StatusTime must be specified for this routine.");
            }
            if (String.IsNullOrEmpty(encryptedInputFile) || String.IsNullOrEmpty(outputFile))
            {
                throw new ArgumentNullException("Paths to both the encrypted input file and the output file need to be specified.");
            }

            if (KeyIsValid(GetStringFromByteArray(_key)) == false)
            {
                throw new System.Exception("Invalid length for Key.");
            }
            if (IVIsValid(GetStringFromByteArray(_iv)) == false)
            {
                throw new System.Exception("Invalid length for IV.");
            }


            try
            {
                //string encryptedData = File.ReadAllText(encryptedInputFile);
                //encryptor.Key = this.Key;
                //encryptor.IV = this.IV;
                //string decryptedData = encryptor.Decrypt(encryptedData);
                //File.WriteAllText(outputFile, decryptedData);

                PFFileEncoder encoder  = new PFFileEncoder();
                PFTempFile    tempFile = new PFTempFile();
                FileInfo      fi       = new FileInfo(encryptedInputFile);
                //**************************************************************************************************
                //dont't setup the timer callback: EncodeFileToBase64 routine slows down by a factor of 3x slower.
                //encoder.currentStatusReport += FileEncoderStatusReport;
                //st.NumSecondsInterval = 60;
                //**************************************************************************************************
                currentStatusReport("DecodeFromBase64", "In Progress", fi.Length, (int)st.GetElapsedTime().TotalSeconds, st.GetFormattedElapsedTime());
                //encoder.DecodeFileFromBase64(encryptedInputFile, tempFile.TempFileName);
                DecodeFileOnSeparateThread(encoder, encryptedInputFile, tempFile.TempFileName, st);
                fi = new FileInfo(tempFile.TempFileName);
                currentStatusReport("DecodeFromBase64", "Completed", fi.Length, (int)st.GetElapsedTime().TotalSeconds, st.GetFormattedElapsedTime());
                DecryptBinary(tempFile.TempFileName, outputFile, st);
            }
            catch (System.Exception ex)
            {
                _msg.Length = 0;
                _msg.Append("Attempt to decrypt file ");
                _msg.Append(encryptedInputFile);
                _msg.Append(" failed. Verify you are using same key/iv pair used to encrypt.  Error message: ");
                _msg.Append("\r\n");
                _msg.Append(AppMessages.FormatErrorMessage(ex));
                throw new System.Exception(_msg.ToString());
            }
            finally
            {
                ;
            }


            return(outputFile);
        }
Esempio n. 27
0
        private void StatusTimerCallback(object param)
        {
            try
            {
                var status = WcfProxy.GetCurrentStatus();

                this.InvokeIfRequired(() =>
                {
                    if (logToken != status.LogToken)
                    {
                        // Has to be in this order
                        // Otherwise clearing the DGV causes cell value requests
                        // in this thread before continuing here.
                        // Which has a high chance of adding items in the
                        // LogEntries list, which are subsequently cleared,
                        // leaving empty cells in the DGV that won't be filled.
                        DgvLog.RowCount = 0;
                        LogEntries.Clear();
                    }
                    logToken = status.LogToken;

                    // If we are scrolled down, we auto scroll
                    var prevRowCount = DgvLog.RowCount;
                    DgvLog.RowCount  = status.LogCount;
                    if (DgvLog.GetLastDisplayedScrollingRowIndex(false) + 1
                        >= prevRowCount)
                    {
                        DgvLog.FirstDisplayedScrollingRowIndex =
                            DgvLog.RowCount - 1;
                    }

                    UpdateOperation(status.Operation);

                    DuplicateCount         = status.DuplicateCount;
                    LblDuplicateCount.Text = string.Format(
                        StatusInfoDuplicateCount,
                        DuplicateCount);
                    BtnResolveDuplicates.Enabled = DuplicateCount > 0;
                    BtnDiscardDuplicates.Enabled = DuplicateCount > 0;
                });
            }
            catch (Exception ex) when(
                ex is EndpointNotFoundException ||
                ex is CommunicationException ||
                ex is TimeoutException)
            {
                Debug.Print("Status request failed with: " + ex.Message);
                this.InvokeIfRequired(() =>
                {
                    BtnResolveDuplicates.Enabled = false;
                    UpdateOperation(new OperationInfo
                    {
                        Message       = "Connecting...",
                        ProgressStyle = ProgressStyle.Marquee,
                    });
                });
            }
            finally
            {
                _ = StatusTimer.StartSingle(Settings.StatusRequestInterval);
            }
        }
Esempio n. 28
0
        private void DecodeFileOnSeparateThread(PFFileEncoder encoder, string encryptedInputFile, string tempFileName, StatusTimer st)
        {
            TimeSpan      ts    = new TimeSpan(0, 0, _statusReportIntervalSeconds);
            PFThread      t     = new PFThread(new ParameterizedThreadStart(DecodeFileFromBase64), "DecodeFileFromBase64");
            List <object> parms = new List <object>();

            parms.Add(encoder);
            parms.Add(encryptedInputFile);
            parms.Add(tempFileName);
            parms.Add(st);
            t.ThreadDescription       = "Decode File from Base64 Text.";
            t.ShowElapsedMilliseconds = false;
            t.StartTime = DateTime.Now;
            st.ShowElapsedTimeMilliseconds = false;
            st.NumSecondsInterval          = _statusReportIntervalSeconds;
            if (st.StatusTimerIsRunning == false)
            {
                st.Start();
            }
            t.Start(parms);
            while (t.ThreadObject.Join(ts) == false)
            {
                if (st.StatusReportDue())
                {
                    FileInfo fi = new FileInfo(tempFileName);
                    currentStatusReport("DecodeEncryptionFromBase64", "InProgress", fi.Length, (int)st.GetElapsedTime().TotalSeconds, st.GetFormattedElapsedTime());
                    fi = null;
                }
            }
            t.FinishTime = DateTime.Now;
        }
Esempio n. 29
0
 public void SetStatus(string status)
 {
     Status.Value   = status;
     Status.Visible = true;
     StatusTimer.Restart();
 }
Esempio n. 30
0
        //methods
        /// <summary>
        /// Converts file to base64 encoding.
        /// </summary>
        /// <param name="srcFile">File containing data to be encoded.</param>
        /// <param name="targetFile">Output file that will contain the base64 encoded data.</param>
        /// <param name="st">A StatusTimer object to use for timing the encode operation.</param>
        public void EncodeFileToBase64(string srcFile, string targetFile, StatusTimer st)
        {
            byte[]       bytes          = new byte[BufferSize];
            FileStream   fs             = null;
            StreamWriter sw             = null;
            FileStream   fsOut          = null;
            int          bytesRead      = 0;
            long         totalBytesRead = 0;
            bool         errorOccurred  = false;

            // Open srcFile in read-only mode.
            try
            {
                if (st == null)
                {
                    throw new ArgumentNullException("StatusTime must be specified for this routine.");
                }
                st.NumSecondsInterval = _statusReportIntervalSeconds;

                fs = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize);
                long sourceSize = new FileInfo(srcFile).Length;

                if (sourceSize <= BufferSize)
                {
                    // Open stream writer
                    sw        = new StreamWriter(targetFile, false, Encoding.ASCII);
                    bytesRead = fs.Read(bytes, 0, BufferSize);

                    if (bytesRead > 0)
                    {
                        if (currentStatusReport != null)
                        {
                            if (st.StatusReportDue())
                            {
                                currentStatusReport("EncodeToBase64", "In Progress", totalBytesRead, (int)st.GetElapsedTime().TotalSeconds, st.GetFormattedElapsedTime());
                            }
                        }
                        string base64String = Convert.ToBase64String(bytes, 0, bytesRead);
                        totalBytesRead += bytesRead;
                        sw.Write(base64String);
                        if (currentStatusReport != null)
                        {
                            if (st.StatusReportDue())
                            {
                                currentStatusReport("EncodeToBase64", "Completed", totalBytesRead, (int)st.GetElapsedTime().TotalSeconds, st.GetFormattedElapsedTime());
                            }
                        }
                    }
                }
                else
                {
                    // Instantiate a ToBase64Transform object.
                    ToBase64Transform transf = new ToBase64Transform();
                    // Arrays to hold input and output bytes.
                    byte[] inputBytes  = new byte[transf.InputBlockSize];
                    byte[] outputBytes = new byte[transf.OutputBlockSize];
                    int    bytesWritten;

                    fsOut = new FileStream(targetFile, FileMode.Create, FileAccess.Write);

                    do
                    {
                        if (currentStatusReport != null)
                        {
                            if (st.StatusReportDue())
                            {
                                currentStatusReport("EncodeToBase64", "In Progress", totalBytesRead, (int)st.GetElapsedTime().TotalSeconds, st.GetFormattedElapsedTime());
                            }
                        }
                        bytesRead       = fs.Read(inputBytes, 0, inputBytes.Length);
                        totalBytesRead += bytesRead;
                        bytesWritten    = transf.TransformBlock(inputBytes, 0, bytesRead, outputBytes, 0);
                        fsOut.Write(outputBytes, 0, bytesWritten);
                    } while (sourceSize - totalBytesRead > transf.InputBlockSize);

                    // Transform the final block of data.
                    bytesRead       = fs.Read(inputBytes, 0, inputBytes.Length);
                    totalBytesRead += bytesRead;
                    byte[] finalOutputBytes = transf.TransformFinalBlock(inputBytes, 0, bytesRead);
                    fsOut.Write(finalOutputBytes, 0, finalOutputBytes.Length);

                    if (currentStatusReport != null)
                    {
                        currentStatusReport("EncodeToBase64", "Completed", totalBytesRead, (int)st.GetElapsedTime().TotalSeconds, st.GetFormattedElapsedTime());
                    }

                    // Clear Base64Transform object.
                    transf.Clear();
                }
            }
            catch (IOException ex)
            {
                errorOccurred = true;
                _msg.Length   = 0;
                _msg.Append(AppMessages.FormatErrorMessage(ex));
                throw new IOException(_msg.ToString());
            }
            catch (SecurityException ex)
            {
                errorOccurred = true;
                _msg.Length   = 0;
                _msg.Append(AppMessages.FormatErrorMessage(ex));
                throw new SecurityException(_msg.ToString());
            }
            catch (UnauthorizedAccessException ex)
            {
                errorOccurred = true;
                _msg.Length   = 0;
                _msg.Append(AppMessages.FormatErrorMessage(ex));
                throw new UnauthorizedAccessException(_msg.ToString());
            }
            finally
            {
                if (errorOccurred)
                {
                    if (currentStatusReport != null)
                    {
                        currentStatusReport("EncodeToBase64", "ErrorCancel", totalBytesRead, (int)st.GetElapsedTime().TotalSeconds, st.GetFormattedElapsedTime());
                    }
                }

                if (sw != null)
                {
                    sw.Close();
                }
                if (fs != null)
                {
                    fs.Dispose();
                    fs.Close();
                }
                if (fsOut != null)
                {
                    fsOut.Dispose();
                    fsOut.Close();
                }
            }
        }