/* TODO ERROR: Skipped EndRegionDirectiveTrivia */
        /* TODO ERROR: Skipped RegionDirectiveTrivia */
        public environmentVarsCore load()
        {
            state.secretKey = state.SettingsSecretKey;
            var encryption   = new AesCipher(state);
            var settingsFile = new FileInfo(Path.Combine(state.libraryPath, "ScrewDriver.eon"));

            settingsFile.Refresh();
            if (settingsFile.Exists)
            {
                try
                {
                    var    bytes     = File.ReadAllBytes(Path.Combine(state.libraryPath, "ScrewDriver.eon"));
                    string encrypted = Convert.ToBase64String(bytes, 0, bytes.Length);
                    string decrypted = encryption.decrypt(encrypted);
                    var    data      = JsonConvert.DeserializeObject <Dictionary <string, object> >(decrypted);
                    state.country            = data["country"].ToString();
                    state.currentLang        = data["language"].ToString();
                    state.ServerBaseAddr     = data["serverAddress"].ToString();
                    state.ApiServerAddrPath  = data["ApiServerAddrPath"].ToString();
                    state.secretKey          = data["ApiEncryptionKey"].ToString();
                    state.SendDiagnosticData = Convert.ToBoolean(data["sendDiags"]);
                    state.SendCrashData      = Convert.ToBoolean(data["sendCrash"]);
                    return(state);
                }
                catch (Exception ex)
                {
                    hasError     = true;
                    errorMessage = ex.ToString();
                    return(default);
예제 #2
0
        private void bwDataRequest_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            // Find out the Index of the bWorker that called this DoWork (could be cleaner, I know)
            int Y;
            int Index  = default;
            var loopTo = Information.UBound(bwDataRequest);

            for (Y = 0; Y <= loopTo; Y++)
            {
                if (sender.Equals(bwDataRequest[Y]))
                {
                    Index = Y;
                    break;
                }
            }

            string             responseFromServer = Encoding.UTF8.GetString((byte[])e.Result);
            string             decrypted          = "";
            var                encryption         = new AesCipher(state);
            _queue_data_struct data;

            try
            {
                if (IsBase64String(responseFromServer) & !responseFromServer.Equals(""))
                {
                    decrypted = encryption.decrypt(responseFromServer);
                }
                else
                {
                    System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(state.currentLang);
                    decrypted = "{'error':true,'message':'" + resources.GetString("contactingCommServer", CultureInfo.CurrentCulture) + " |" + responseFromServer + "|'}";
                }
            }
            catch (Exception ex)
            {
                decrypted = "{'error':true,'message':'" + ex.Message.ToString().Replace("'", @"\'") + "'}";
            }

            if (!ManagementNetwork.IsResponseOk(decrypted))
            {
                data        = new _queue_data_struct();
                data        = queue[queueBWorker[Index]];
                data.status = 0; // re queue the file
                lock (queueLock)
                    queue[queueBWorker[Index]] = data;
                string          errorMsg = ManagementNetwork.GetMessage(decrypted);
                _retry_attempts retry;
                retry.counter         = retryAttempts.counter;
                retry.previousPattern = retryAttempts.previousPattern;
                retry.pattern         = retryAttempts.pattern;
                retry.errorMessage    = retryAttempts.errorMessage;
                retry.errorMessage    = retryAttempts.errorMessage.IndexOf(errorMsg) > -1 ? retryAttempts.errorMessage : retryAttempts.errorMessage + System.Environment.NewLine + errorMsg;
                retry.pattern         = QueuesMultiHash(queue);
                if (retry.previousPattern.Equals(retry.pattern))
                {
                    retry.counter += 1;
                }
                else
                {
                    retry.counter         = 1;
                    retry.previousPattern = retryAttempts.pattern;
                }

                retryAttempts = retry;
                return;
            }

            data        = new _queue_data_struct();
            data        = queue[queueBWorker[Index]];
            data.status = -1; // completed sucessfully status
            lock (queueLock)
                queue[queueBWorker[Index]] = data;
            loadingCounter      += 1;
            CompletionPercentage = (int)(loadingCounter / (double)queue.Count * 100);
            statusMessage        = "Uploading data to the cloud ...";
            dataArrived?.Invoke(this, decrypted, queue[queueBWorker[Index]].misc);
        }
예제 #3
0
        /* TODO ERROR: Skipped EndRegionDirectiveTrivia */
        /* TODO ERROR: Skipped RegionDirectiveTrivia */
        public void loadConfig()
        {
            changeDataLoadedState(true);
            var cfgstate = new AeonLabs.Environment.environmentVarsCore();

            cfgstate.secretKey = enVars.secretKey;
            var encryption   = new AesCipher(cfgstate);
            var settingsFile = new FileInfo(Path.Combine(cfgstate.libraryPath, "ScrewDriver.cfg"));

            settingsFile.Refresh();
            if (settingsFile.Exists)
            {
                {
                    var withBlock = enVars;
                    try
                    {
                        var    bytes     = File.ReadAllBytes(Path.Combine(cfgstate.libraryPath, "ScrewDriver.cfg"));
                        string encrypted = Convert.ToBase64String(bytes, 0, bytes.Length);
                        string decrypted = encryption.decrypt(encrypted);
                        var    data      = JsonConvert.DeserializeObject <Dictionary <string, object> >(decrypted);

                        // datatable color schemes
                        withBlock.layoutDesign.buttonColor  = Color.FromArgb(Conversions.ToInteger(data["buttonColor"].ToString()));
                        withBlock.layoutDesign.dividerColor = Color.FromArgb(Conversions.ToInteger(data["dividerColor"].ToString()));
                        withBlock.colorSite                  = Color.FromArgb(Conversions.ToInteger(data["colorSite"].ToString()));
                        withBlock.colorSection               = Color.FromArgb(Conversions.ToInteger(data["colorSection"].ToString()));
                        withBlock.colorCompany               = Color.FromArgb(Conversions.ToInteger(data["colorCompany"].ToString()));
                        withBlock.colorWorkCategories        = Color.FromArgb(Conversions.ToInteger(data["colorWorkCategories"].ToString()));
                        withBlock.colorAbsense               = Color.FromArgb(Conversions.ToInteger(data["colorAbsense"].ToString()));
                        withBlock.colorWithoutRecord         = Color.FromArgb(Conversions.ToInteger(data["colorWithoutRecord"].ToString()));
                        withBlock.colorWeekends              = Color.FromArgb(Conversions.ToInteger(data["colorWeekends"].ToString()));
                        withBlock.colorHolidays              = Color.FromArgb(Conversions.ToInteger(data["colorHolidays"].ToString()));
                        withBlock.colorWithRecord            = Color.FromArgb(Conversions.ToInteger(data["colorWithRecord"].ToString()));
                        withBlock.colorAbsentDay             = Color.FromArgb(Conversions.ToInteger(data["colorAbsentDay"].ToString()));
                        withBlock.colorFermetureAnnual       = Color.FromArgb(Conversions.ToInteger(data["colorFermetureAnnual"].ToString()));
                        withBlock.colorPartialDayValidated   = Color.FromArgb(Conversions.ToInteger(data["colorPartialDayValidated"].ToString()));
                        withBlock.colorPlannedChangeOfSite   = Color.FromArgb(Conversions.ToInteger(data["colorPlannedChangeOfSite"].ToString()));
                        withBlock.colorPlannedTeam           = Color.FromArgb(Conversions.ToInteger(data["colorPlannedTeam"].ToString()));
                        withBlock.colorFullDayValidated      = Color.FromArgb(Conversions.ToInteger(data["colorFullDayValidated"].ToString()));
                        withBlock.layoutDesign.colorMainMenu = Color.FromArgb(Conversions.ToInteger(data["colorMainMenu"].ToString()));
                        // font files
                        withBlock.layoutDesign.fontTitleFile = data["fontTitleFile"].ToString();
                        withBlock.layoutDesign.fontTextFile  = data["fontTextFile"].ToString();
                        // delay Days Validation Attendance
                        withBlock.delayDaysValidationAttendance = Conversions.ToInteger(data["delayDaysValidationAttendance"].ToString());
                        withBlock.layoutDesign.fontTitle.AddFontFile(withBlock.fontsPath + withBlock.layoutDesign.fontTitleFile);
                        withBlock.layoutDesign.fontText.AddFontFile(withBlock.fontsPath + withBlock.layoutDesign.fontTextFile);
                    }
                    catch (Exception ex)
                    {
                        withBlock.stateErrorMessage = ex.ToString();
                    }
                }
            }
            else
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(enVars.currentLang);
                enVars.stateErrorMessage = My.Resources.strings.errorDataFileNotFound;
            }

            changeDataLoadedState(false, LOAD_CONFIG);
        }
        private void bwDataRequest_DoWork(object sender, DoWorkEventArgs e)
        {
            // Find out the Index of the bWorker that called this DoWork (could be cleaner, I know)
            int Y;
            int Index  = default;
            var loopTo = Information.UBound(bwDataRequest);

            for (Y = 0; Y <= loopTo; Y++)
            {
                if (sender.Equals(bwDataRequest[Y]))
                {
                    Index = Y;
                    break;
                }
            }

            _queue_data_struct queue;

            queue = (_queue_data_struct)e.Argument;
            var vars = new Dictionary <string, string>();

            vars = queue.vars;

            // TODO translation need to be local
            if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(state.currentLang);
                e.Result = "{'error':true,'message':'" + resources.GetString("errorNoNetwork", CultureInfo.CurrentCulture) + "'}";
                return;
            }

            if (vars is null)
            {
                e.Result = "{'error':true,'message':'missconfiguration vars'}";
                return;
            }

            if (!vars.ContainsKey("id"))
            {
                vars.Add("id", state.userId);
            }

            if (!vars.ContainsKey("pid"))
            {
                var appId = new FingerPrint();
                vars.Add("pid", appId.Value());
            }

            if (!vars.ContainsKey("language"))
            {
                vars.Add("language", state.currentLang);
            }

            if (!vars.ContainsKey("origin"))
            {
                vars.Add("origin", state.customization.softwareAccessMode);
            }

            string json               = JsonConvert.SerializeObject(vars, Formatting.Indented);
            var    encryption         = new AesCipher(state);
            string encrypted          = HttpUtility.UrlEncode(encryption.encrypt(json));
            var    PostData           = "origin=" + state.customization.softwareAccessMode + "&data=" + encrypted;
            var    request            = WebRequest.Create(url);
            string responseFromServer = "";
            string decrypted          = "";

            request.Method = "POST";
            var byteArray = Encoding.UTF8.GetBytes(PostData);

            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers.Add("Authorization", state.ApiHttpHeaderToken + "-" + state.customization.softwareAccessMode);
            request.ContentLength = (long)byteArray.Length;
            try
            {
                var dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                dataStream = response.GetResponseStream();
                var reader = new StreamReader(dataStream);
                responseFromServer = reader.ReadToEnd();
                reader.Close();
                dataStream.Close();
                response.Close();
                if (response.StatusCode == HttpStatusCode.Accepted | (int)response.StatusCode == 200)
                {
                    if (IsBase64String(responseFromServer) & !responseFromServer.Equals(""))
                    {
                        decrypted = encryption.decrypt(responseFromServer).Replace(@"\'", "'");
                    }
                    else
                    {
                        System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(state.currentLang);
                        decrypted = "{'error':true,'encrypted':false,'message':'" + resources.GetString("contactingCommServer", CultureInfo.CurrentCulture) + " |" + responseFromServer + "|'}";
                    }
                }
                else
                {
                    System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(state.currentLang);
                    decrypted = "{'error':true,'message':'" + resources.GetString("contactingCommServer", CultureInfo.CurrentCulture) + " (" + ((int)response.StatusCode).ToString() + ")', 'statuscode':'" + ((int)response.StatusCode).ToString() + "'}";
                }
            }
            catch (Exception ex)
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(state.currentLang);
                decrypted = "{'error':true,'message':'" + resources.GetString("contactingCommServer", CultureInfo.CurrentCulture) + " (" + ex.Message.ToString().Replace("'", @"\'") + ")'}";
            }

            e.Result = decrypted.Replace(@"\'", "'");
        }
        private void bwDataRequest_DoWork(object sender, DoWorkEventArgs e)
        {
            // Find out the Index of the bWorker that called this DoWork (could be cleaner, I know)
            int Y;
            int Index  = default;
            var loopTo = Information.UBound(bwDataRequest);

            for (Y = 0; Y <= loopTo; Y++)
            {
                if (sender.Equals(bwDataRequest[Y]))
                {
                    Index = Y;
                    break;
                }
            }

            if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                e.Result = false;
                System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(state.currentLang);
                fileExtension[queueBWorker[Index]] = "{'error':true,'message':'" + resources.GetString("errorNoNetwork", CultureInfo.CurrentCulture) + "'}";
                return;
            }

            _queue_data_struct queue;

            queue = (_queue_data_struct)e.Argument;
            var vars = new Dictionary <string, string>();

            vars = queue.vars;
            if (!vars.ContainsKey("id"))
            {
                vars.Add("id", state.userId);
            }

            if (!vars.ContainsKey("pid"))
            {
                var appId = new FingerPrint();
                vars.Add("pid", appId.Value());
            }

            if (!vars.ContainsKey("language"))
            {
                vars.Add("language", state.currentLang);
            }

            string json       = JsonConvert.SerializeObject(vars, Formatting.Indented);
            var    encryption = new AesCipher(state);
            string encrypted  = HttpUtility.UrlEncode(encryption.encrypt(json));
            var    PostData   = new Dictionary <string, string>();

            PostData.Add("origin", state.customization.softwareAccessMode);
            PostData.Add("data", encrypted);
            string Data2Send = "";

            for (int i = 0, loopTo1 = PostData.Count - 1; i <= loopTo1; i++)
            {
                Data2Send += HttpUtility.UrlEncode(PostData.Keys.ElementAtOrDefault(i)) + "=" + HttpUtility.UrlEncode(PostData[PostData.Keys.ElementAtOrDefault(i)]) + "&";
            }
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Method = "POST";
            var data = Encoding.UTF8.GetBytes(Data2Send);

            request.ContentType   = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            var requestStream = request.GetRequestStream();

            requestStream.Write(data, 0, data.Length);
            requestStream.Close();
            int readings   = 0;
            var speedtimer = new Stopwatch();
            _data_statistics dataStatisticsItem;

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (var stream = response.GetResponseStream())
                    {
                        using (var bytes = new MemoryStream())
                        {
                            var Buffer = new byte[257];
                            dataStatisticsItem.filesize          = Math.Round(bytes.Length / (double)1024, 0);
                            dataStatisticsItem.bytesSentReceived = 0;
                            dataStatisticsItem.speed             = 0;
                            dataStatistics[queueBWorker[Index]]  = dataStatisticsItem;
                            while (bytes.Length < response.ContentLength)
                            {
                                int read = stream.Read(Buffer, 0, Buffer.Length);
                                if (read > 0)
                                {
                                    bytes.Write(Buffer, 0, read);
                                }
                                else
                                {
                                    break;
                                }

                                readings += 1;
                                if (readings >= 5)
                                {
                                    dataStatisticsItem.speed            = 20480 / (speedtimer.ElapsedMilliseconds / (double)1000);
                                    dataStatistics[queueBWorker[Index]] = dataStatisticsItem;
                                    speedtimer.Reset();
                                    readings = 0;
                                    updateProgressStatistics?.Invoke(this, dataStatisticsItem, queue.misc);
                                }
                            }

                            var utf8Encoding = new UTF8Encoding(true);
                            if (response.StatusCode == HttpStatusCode.Accepted | (int)response.StatusCode == 200)
                            {
                                string responseFromServer = utf8Encoding.GetString(bytes.ToArray());
                                string decrypted          = "";
                                if (IsBase64String(responseFromServer) & !responseFromServer.Equals(""))
                                {
                                    decrypted = encryption.decrypt(responseFromServer).Replace(@"\'", "'");
                                    fileExtension[queueBWorker[Index]] = decrypted;
                                    e.Result = false;
                                }
                                else if (response.GetResponseHeader("Content-Disposition") is object && !response.GetResponseHeader("Content-Disposition").Equals(""))
                                {
                                    fileExtension[queueBWorker[Index]] = response.GetResponseHeader("Content-Disposition").Substring(response.GetResponseHeader("Content-Disposition").IndexOf("filename=") + 9);
                                    e.Result = bytes.ToArray();
                                }
                                else
                                {
                                    System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(state.currentLang);
                                    fileExtension[queueBWorker[Index]] = "{'error':true,'message':'" + resources.GetString("contactingCommServer", CultureInfo.CurrentCulture) + " (" + ((int)response.StatusCode).ToString() + ")'}";
                                    e.Result = false;
                                }
                            }
                            else
                            {
                                System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(state.currentLang);
                                fileExtension[queueBWorker[Index]] = "{'error':true,'message':'" + resources.GetString("contactingCommServer", CultureInfo.CurrentCulture) + " (" + ((int)response.StatusCode).ToString() + ")', 'statuscode':'" + ((int)response.StatusCode).ToString() + "'}";
                                e.Result = false;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                e.Result = false;
                fileExtension[queueBWorker[Index]] = "{'error':true,'message':'" + ex.Message + "'}";
            }
        }