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(@"\'", "'");
        }
Exemple #2
0
        private void bwDataRequest_DoWork(object sender, DoWorkEventArgs e)
        {
            byte[] responseBytes;

            // 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())
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(state.currentLang);
                responseBytes = Encoding.UTF8.GetBytes("{'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);
            double         currentspeed  = -1;
            string         boundary      = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            var            boundarybytes = Encoding.ASCII.GetBytes(Constants.vbCrLf + "--" + boundary + Constants.vbCrLf);
            HttpWebRequest wr            = (HttpWebRequest)WebRequest.Create(url);

            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method      = "POST";
            wr.KeepAlive   = true;
            wr.Credentials = CredentialCache.DefaultCredentials;
            var    rs = wr.GetRequestStream();
            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"" + Constants.vbCrLf + Constants.vbCrLf + "{1}";

            for (int i = 0, loopTo1 = PostData.Count - 1; i <= loopTo1; i++)
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);
                string formitem      = string.Format(formdataTemplate, PostData.Keys.ElementAtOrDefault(i), PostData[PostData.Keys.ElementAtOrDefault(i)]);
                var    formitembytes = Encoding.UTF8.GetBytes(formitem);
                rs.Write(formitembytes, 0, formitembytes.Length);
            }

            rs.Write(boundarybytes, 0, boundarybytes.Length);
            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + Constants.vbCrLf + "Content-Type: {2}" + Constants.vbCrLf + Constants.vbCrLf;
            string header         = string.Format(headerTemplate, "file", Path.GetFileName(queue.filenameOrSavePath), "application/octet-stream");
            var    headerbytes    = Encoding.UTF8.GetBytes(header);

            rs.Write(headerbytes, 0, headerbytes.Length);
            var              fileStream     = new FileStream(queue.filenameOrSavePath, FileMode.Open, FileAccess.Read);
            var              buffer         = new byte[4096];
            int              bytesRead      = 0;
            double           totalBytesRead = 0;
            int              readings       = 0;
            var              speedtimer     = new Stopwatch();
            _data_statistics dataStatisticsItem;

            System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(state.currentLang);
            dataStatisticsItem.filesize          = Conversions.ToDouble(resources.GetString("size", CultureInfo.CurrentCulture) + ": " + Math.Round(fileStream.Length / (double)1024, 0) + " " + resources.GetString("bytes", CultureInfo.CurrentCulture));
            dataStatisticsItem.bytesSentReceived = 0;
            dataStatisticsItem.speed             = 0;
            dataStatistics[queueBWorker[Index]]  = dataStatisticsItem;
            bytesRead = fileStream.Read(buffer, 0, buffer.Length);
            while (bytesRead != 0)
            {
                rs.Write(buffer, 0, bytesRead);
                dataStatisticsItem.bytesSentReceived += bytesRead;
                dataStatistics[queueBWorker[Index]]   = dataStatisticsItem;
                readings += 1;
                if (readings >= 5)
                {
                    dataStatisticsItem.speed            = 20480 / (speedtimer.ElapsedMilliseconds / (double)1000);
                    dataStatistics[queueBWorker[Index]] = dataStatisticsItem;
                    speedtimer.Reset();
                    readings = 0;
                    updateProgressStatistics?.Invoke(this, queue.misc);
                }

                bytesRead = fileStream.Read(buffer, 0, buffer.Length);
            }

            fileStream.Close();
            var trailer = Encoding.ASCII.GetBytes(Constants.vbCrLf + "--" + boundary + "--" + Constants.vbCrLf);

            rs.Write(trailer, 0, trailer.Length);
            rs.Close();
            WebResponse wresp = null;

            try
            {
                wresp = wr.GetResponse();
                var stream2 = wresp.GetResponseStream();
                var reader2 = new StreamReader(stream2);
                responseBytes = Encoding.UTF8.GetBytes(reader2.ReadToEnd());
            }
            catch (Exception ex)
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(state.currentLang);
                responseBytes = Encoding.UTF8.GetBytes("{'error':true,'message':'" + resources.GetString("contactingCommServer", CultureInfo.CurrentCulture) + ":" + ex.Message + "'}");
                if (wresp is object)
                {
                    wresp.Close();
                    wresp = null;
                }
            }

            wr       = null;
            e.Result = responseBytes;
        }
        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 + "'}";
            }
        }