Пример #1
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ConvertedUnits cu;

                using (ConverterClient sc = new ConverterClient())
                {
                    switch (comboBoxConvertTo.SelectedItem)
                    {
                    case "LinearMeasure":
                        cu = sc.LinearMeasure(Convert.ToDouble(textBoxValue.Text));
                        MessageBox.Show($"Foot: {cu.Foot}\nInch:{cu.Inch}\nYard: {cu.Yard}");
                        break;

                    case "CelsiusToFahrenheit":
                        cu = sc.CelsiusToFahrenheit(Convert.ToDouble(textBoxValue.Text));
                        MessageBox.Show($"Fahrenheit: {cu.Fahrenheit}");
                        break;

                    case "FahrenheitToCelsius":
                        cu = sc.FahrenheitToCelsius(Convert.ToDouble(textBoxValue.Text));
                        MessageBox.Show($"Celsius: {cu.Celsius}");
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Пример #2
0
 private void AllWork()
 {
     try
     {
         if (string.IsNullOrEmpty(TextBoxForMetrs.Text) == false)
         {
             var num = Double.Parse(TextBoxForMetrs.Text);
             using (ConverterClient client = new ConverterClient())
             {
                 var s = client.LinearMeasure(num);
                 TextBoxForFeets.Text  = s.Feets.ToString();
                 TextBoxForInches.Text = s.Inches.ToString();
                 TextBoxForYards.Text  = s.Yards.ToString();
             }
         }
         if (string.IsNullOrEmpty(TextBoxForCelsius.Text) == false)
         {
             using (ConverterClient client = new ConverterClient())
             {
                 var num = Double.Parse(TextBoxForCelsius.Text);
                 var s   = client.CelsiusToFahrenheit(num);
                 TextBoxForWriteFahrenheit.Text = s.Fahrenheit.ToString();
             }
         }
         if (string.IsNullOrEmpty(TextBoxForFahrenheit.Text) == false)
         {
             using (ConverterClient client = new ConverterClient())
             {
                 var num = Double.Parse(TextBoxForFahrenheit.Text);
                 var s   = client.FahrenheitToCelsius(num);
                 TextBoxForWriteCelsius.Text = s.Fahrenheit.ToString();
             }
         }
     }
     catch
     {
         MessageBox.Show("No data available");
     }
 }
Пример #3
0
        public void GetVideoFile(string hash, Int64 id = -1)
        {
            Stream          fileStream = null;
            ConverterClient client     = null;

            try
            {
                if (hash == null || id == -1)
                {
                    throw new FileNotFoundException("Не найден файл!");
                }

                Models.File file = _db.Files.Where(f => f.Id == id && f.Md5Hash == hash).FirstOrDefault <Models.File>();
                if (file == null)
                {
                    throw new FileNotFoundException("Не найден файл!");
                }

                client = new ConverterClient("BasicHttpBinding_IConverter");
                Int64 fileLength = client.DownloadFile(file.FilePath, out fileStream);

                if (fileStream == null)
                {
                    throw new FileNotFoundException("Не найден файл!");
                }

                Response.BufferOutput = true;   // to prevent buffering
                Response.Buffer       = true;
                byte[] buffer    = new byte[6500];
                int    bytesRead = 0;

                System.Web.HttpContext.Current.Response.Clear();
                System.Web.HttpContext.Current.Response.ClearHeaders();
                Response.BufferOutput = false;   // to prevent buffering
                Response.ContentType  = "video/mp4";
                Response.AddHeader("Content-Length", fileLength.ToString());
                Response.AddHeader("content-disposition", "attachment;filename=\"" + Path.GetFileName(file.FilePath) + "\"");

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

                while (bytesRead > 0)
                {
                    // Verify that the client is connected.
                    if (Response.IsClientConnected)
                    {
                        Response.OutputStream.Write(buffer, 0, bytesRead);
                        // Flush the data to the HTML output.
                        Response.Flush();

                        buffer    = new byte[6500];
                        bytesRead = fileStream.Read(buffer, 0, buffer.Length);
                    }
                    else
                    {
                        bytesRead = -1;
                    }
                }
            }
            catch (Exception ex)
            {
                // Trap the error, if any.
                System.Web.HttpContext.Current.Response.Write("Error : " + ex.Message);
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
                if (client != null)
                {
                    client.Close();
                }
                Response.Flush();
                Response.Close();
                //Response.End();
                //System.Web.HttpContext.Current.Response.Close();
            }
        }
Пример #4
0
        public ActionResult ConvertForm(HttpPostedFileBase fileUpload, string email = "")
        {
            if (fileUpload == null || fileUpload.ContentLength == 0)
            {
                return(Json(new { error = "Не выбран или поврежден файл!" }));
            }
            if (!Email.IsValidEmail(email))
            {
                return(Json(new { error = "Неправильный email адрес!" }));
            }

            string rootHost = Request.Url.Scheme + "://" + Request.Url.Authority;

            byte[] streamBytes = StreamUtils.ReadToEnd(fileUpload.InputStream);
            Task   newTask     = new Task(() =>
            {
                string result = String.Empty;
                try
                {
                    ConverterClient client    = new ConverterClient("BasicHttpBinding_IConverter");
                    ResponseFileInfo fileInfo = client.ConvertFile(new UploadFileInfo()
                    {
                        ByteArray = streamBytes, Email = email
                    });
                    client.Close();

                    Models.File file       = new Models.File();
                    file.Md5Hash           = fileInfo.Hash;
                    file.FilePath          = fileInfo.Path;
                    file.EmailWhoConverted = email;
                    file.Datetime          = DateTime.Now;
                    _db.Files.Add(file);
                    _db.SaveChanges();

                    string emailMessage = String.Format("Ссылка на скачивание видеофайла: {0}/Home/GetVideoFile/?hash={1}&id={2}\r\nС уважением, компания WebLMS.\r\nhttp://weblms.ru", rootHost, fileInfo.Hash, file.Id);
                    ISender emailSender = new FileSender();
                    emailSender.SendFileLink(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TempVideoFiles", fileUpload.FileName + "_done.txt"), emailMessage);

                    //ISender emailSender = new EmailSender();
                    //emailSender.SendFileLink(email, emailMessage);
                }
                catch (Exception e)
                {
                    string emailError = String.Format("Произошла ошибка при конвертации файла, попробуйте повторить операцию позже. Детали ошибки: \r\n{0}.\r\nС уважением, компания WebLMS.\r\nhttp://weblms.ru", "Message: " + e.Message + "\r\nStack: " + e.StackTrace);
                    //ISender emailSender = new EmailSender();
                    //emailSender.SendFileLink(email, emailError);

                    ISender emailSender = new FileSender();
                    emailSender.SendFileLink(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TempVideoFiles", fileUpload.FileName + "_catch.txt"), emailError);
                }
            });
            bool isAdded = WebLMSTasks.AddTask(newTask);

            if (!isAdded)
            {
                newTask.Dispose();
            }
            //WebLMSThread.StartBackgroundThread(() =>
            //{
            //    string destDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TempVideoFiles", Path.GetFileNameWithoutExtension(fileUpload.FileName));
            //    Directory.CreateDirectory(destDirectory);
            //    try
            //    {
            //        Transfer.TransferClient client = new Transfer.TransferClient("BasicHttpBinding_ITransfer");
            //        string result = client.ConvertFile(streamBytes, email);
            //    }
            //    catch (Exception e)
            //    {
            //        //System.IO.File.WriteAllText(Path.Combine(destDirectory, DateTime.Now.Day + "." + DateTime.Now.Month + "." + DateTime.Now.Year + "__" + DateTime.Now.TimeOfDay + "__catch.txt"), e.Message);
            //        //Debug.WriteLine(e.Message);
            //    }

            //});

            string messageToClient =
                WebLMSTasks.IsInPerformQueue(newTask.Id) ?
                "Файл проходит обработку. Ссылку на скачивание Вы получите по почте!" :
                WebLMSTasks.IsInLazyQueue(newTask.Id) ?
                "Файл поставлен в очередь на обработку. Ссылку на скачивание Вы получите по почте!" :
                "Сервер сейчас перегружен. Попробуйте повторить операцию позже.";


            return(Json(
                       new
            {
                status = "process",
                message = messageToClient
            }
                       ));


            //using (MD5 md5 = MD5.Create())
            //{
            //    try
            //    {
            //        string hash = Hash.GetMD5Hash(md5, fileUpload.InputStream);
            //        string destDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TempVideoFiles");
            //        string destFullDirectory = Path.Combine(destDirectory, email, hash);
            //        string videoDirectory = Path.Combine(destFullDirectory, "video");
            //        if (!Directory.Exists(destDirectory))
            //        {
            //            Directory.CreateDirectory(destDirectory);
            //        }

            //        if (!Directory.Exists(destFullDirectory))
            //        {
            //            Directory.CreateDirectory(destFullDirectory);
            //            Directory.CreateDirectory(videoDirectory);
            //            Zip.Unzip(fileUpload.InputStream, destFullDirectory);
            //        }


            //        //string error = converter.CheckArchiveCorrect();
            //        //if (error != null)
            //        //{
            //        //    Directory.Delete(destFullDirectory);
            //        //    return Json(new { error = error });
            //        //}
            //        string rootHost = Request.Url.Scheme + "://" + Request.Url.Authority;
            //        WebLMSThread.StartBackgroundThread(() => {
            //            Transfer.TransferClient client = new Transfer.TransferClient("BasicHttpBinding_ITransfer");
            //            string result = client.ConvertFile(email, fileUpload.InputStream);
            //            Trace.WriteLine(result);
            //            Debug.WriteLine(result);
            //        });
            //        //BackgroundJob.Enqueue(() => createFile(destFullDirectory, videoDirectory, hash, email, rootHost));

            //        return Json(
            //            new
            //            {
            //                status = "process",
            //                message = "Файл проходит обработку. Ссылку на скачивание Вы получите по почте!"
            //            }
            //        );
            //    }
            //    catch (Exception e)
            //    {
            //        return Json(new { status = "error", error = "Произошла ошибка при извлечении архива, повторите попытку позже!" });
            //    }
            //}
        }
Пример #5
0
 public MainForm()
 {
     InitializeComponent();
     proxy = new ConverterClient();
 }