예제 #1
0
        private void UploadFile()
        {
            if (HttpContext.Current.Session["UserID"] != null && ViewState["FolioID"] != null)
            {
                // #1- Logger variables
                System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
                string className = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;
                string methodName = stackFrame.GetMethod().Name;

                // Source: http://stackoverflow.com/questions/1998452/accessing-input-type-file-at-server-side-in-asp-net

                /* ******** Get file extension ******** */
                string fileName = MyFileUpload.PostedFile.FileName;
                string file_extension = string.Empty;

                if (!string.IsNullOrWhiteSpace(fileName))
                {
                    file_extension = fileName.Substring(fileName.LastIndexOf('.'));
                }

                /* ******** Global variables ******** */
                string userID = HttpContext.Current.Session["UserID"].ToString();
                string folioID = ViewState["FolioID"].ToString();
                string repoFilename = "", repoFilenameAUX = "", fullLocalPath = "", relativeLocalPath = "";
                bool ok = true, isFileAUX_created = false, isWavFile = false;

                // File ID
                string guid = Guid.NewGuid().ToString();

                // Get DateTimes 1-2-3...
                DateTime datetime_final = GetDateTime(uploadDate, className, methodName);

                DateTime datetime2_a = GetDateTime(camarasDate1, className, methodName);

                DateTime datetime2_b = GetDateTime(camarasDate2, className, methodName);

                // If is NOT camera recording system function
                if (string.IsNullOrWhiteSpace(txbInputCameraNumber.Value))
                {
                    if (MyFileUpload != null && MyFileUpload.PostedFile != null && !string.IsNullOrWhiteSpace(MyFileUpload.PostedFile.FileName))
                    {
                        /* ******** Configuration variables ******** */

                        string original_filePath = MyFileUpload.PostedFile.FileName;

                        // Repository path
                        string localRepoPath = string.Empty;
                        if (ConfigurationManager.AppSettings != null)
                        {
                            localRepoPath = ConfigurationManager.AppSettings["LocalRepoPath"].ToString();
                        }

                        string server = string.Empty;
                        if (ConfigurationManager.AppSettings != null)
                        {
                            server = ConfigurationManager.AppSettings["DB_Server"].ToString();
                        }

                        // File name
                        repoFilename = guid + ".bin";

                        // File name auxiliar with real extension ==> To get the real duration
                        repoFilenameAUX = guid + file_extension;

                        // Repository relative path
                        relativeLocalPath = datetime_final.Year.ToString("D4") + "\\" + datetime_final.Month.ToString("D2") + "\\" +
                            datetime_final.Day.ToString("D2") + "\\" + datetime_final.Hour.ToString("D2") + "\\";

                        fullLocalPath = localRepoPath + relativeLocalPath; // REAL

                        if (!string.IsNullOrWhiteSpace(fullLocalPath) && !string.IsNullOrWhiteSpace(repoFilenameAUX) && !string.IsNullOrWhiteSpace(file_extension))
                        {
                            try
                            {
                                if (!Directory.Exists(Path.GetDirectoryName(fullLocalPath)))
                                {
                                    Directory.CreateDirectory(Path.GetDirectoryName(fullLocalPath));
                                }

                                if (GetAutomaticConvertWavToMp3OnFileUpload())
                                {
                                    // Is WAVE format file ==> Convert to .mp3
                                    isWavFile = file_extension.ToLowerInvariant().Equals(".wav") ? true : false;
                                }

                                // File name auxiliar with real extension ==> To get real duration
                                MyFileUpload.PostedFile.SaveAs(fullLocalPath + repoFilenameAUX);
                                isFileAUX_created = true;
                            }
                            catch (Exception e)
                            {
                                // #2- Logger exception
                                Logger.LogError("(%s) (%s) -- Excepcion. Copiando archivo AUX al server. ERROR: %s", className, methodName, e.Message);
                                ok = false;
                            }
                        }
                    }
                }
                else
                {
                    // IS Camera recording system ****************************************************
                    ok = false;

                    string cameraNumber_str = txbInputCameraNumber.Value;

                    // WS InConcert Operaciones grabación settings
                    string WS_InConcert_Server = "192.168.10.31";
                    if (ConfigurationManager.AppSettings != null)
                    {
                        WS_InConcert_Server = ConfigurationManager.AppSettings["WS_InConcert_Server"].ToString();
                    }

                    string WS_InConcert_Port = "8081";
                    if (ConfigurationManager.AppSettings != null)
                    {
                        WS_InConcert_Port = ConfigurationManager.AppSettings["WS_InConcert_Port"].ToString();
                    }

                    string WS_InConcert_URL_operacionesGrabacion = "RecordingIntegration/WebServices/OperacionesGrabacion.asmx";
                    if (ConfigurationManager.AppSettings != null)
                    {
                        WS_InConcert_URL_operacionesGrabacion = ConfigurationManager.AppSettings["WS_InConcert_URL_operacionesGrabacion"].ToString();
                    }

                    // WS Endpoint
                    EndpointAddress endpointUser = new EndpointAddress(new Uri("http://" + WS_InConcert_Server + ":" + WS_InConcert_Port + "/" + WS_InConcert_URL_operacionesGrabacion));

                    // WS client
                    var wsClient = new RecordingIntegration.OperacionesGrabacionSoapBindingClient("OperacionesGrabacionSoapBinding", endpointUser);

                    // Call WS operation
                    wsClient.videoAsociado(folioID, userID, cameraNumber_str, datetime2_a.ToString("dd'/'MM'/'yyyy HH':'mm"), datetime2_b.ToString("dd'/'MM'/'yyyy HH':'mm"));
                }

                /* ******** Save in DB - ONLY in NOT Camera recording system cases ******** */

                string real_fileName = string.Empty;
                if (!string.IsNullOrWhiteSpace(fileName))
                {
                    real_fileName = Path.GetFileName(fileName);
                }

                if (ok && !string.IsNullOrWhiteSpace(file_extension) && !string.IsNullOrWhiteSpace(real_fileName)
                    && !string.IsNullOrWhiteSpace(relativeLocalPath) && !string.IsNullOrWhiteSpace(repoFilename)
                    && !string.IsNullOrWhiteSpace(fullLocalPath) && !string.IsNullOrWhiteSpace(repoFilenameAUX)
                    && MyFileUpload != null && MyFileUpload.PostedFile != null)
                {
                    // Get file MediaType
                    string mediaType = GetFileMediaType(file_extension);

                    try
                    {
                        /*************** Get Duration ***************/
                        // Source: http://stackoverflow.com/questions/1256841/c-sharp-get-video-file-duration-from-metadata

                        //Source: http://www.codeproject.com/Articles/43208/How-to-get-the-length-duration-of-a-media-File-in-.aspx
                        // http://forums.asp.net/t/1679210.aspx?Get+Video+duration+after+uploading+asp+net+C+

                        double seconds = 0;
                        ShellFile so = ShellFile.FromFilePath(fullLocalPath + repoFilenameAUX);
                        double nanoseconds;
                        double.TryParse(so.Properties.System.Media.Duration.Value.ToString(), out nanoseconds);
                        if (nanoseconds > 0)
                        {
                            seconds = Convert100NanosecondsToMilliseconds(nanoseconds) / 1000;
                        }
                        /*************** END ***************/

                        /*************** Finally save the file in server ***************/

                        if (!Directory.Exists(Path.GetDirectoryName(fullLocalPath)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(fullLocalPath));
                        }

                        bool normal_save = true;

                        // If .wav format file ==> convert to .mp3 then save the file
                        if (isWavFile)
                        {
                            // NAudio Source: http://stackoverflow.com/questions/7175701/converting-wav-file-to-wav-file-changing-format
                            try
                            {
                                WaveFormat target = new WaveFormat(44100, 16, 1);
                                using (WaveStream stream = new WaveFileReader(fullLocalPath + repoFilenameAUX))
                                {
                                    WaveFormatConversionStream str = new WaveFormatConversionStream(target, stream);
                                    WaveFileWriter.CreateWaveFile(fullLocalPath + repoFilename, str);
                                }

                                // Update file name (new format: .mp3)
                                if (!string.IsNullOrWhiteSpace(fileName))
                                {
                                    real_fileName = real_fileName.Substring(0, real_fileName.LastIndexOf('.')) + ".mp3";
                                }
                                normal_save = false;
                            }
                            catch (Exception e)
                            {
                                // #2- Logger exception
                                Logger.LogError("(%s) (%s) -- Excepcion. Convirtiendo de .wav a mp3. Si falla lo guarda como .wav. ERROR: %s", className, methodName, e.Message);
                                normal_save = true;
                            }
                        }

                        if (normal_save)
                        {
                            // If not .wav format
                            MyFileUpload.PostedFile.SaveAs(fullLocalPath + repoFilename);
                        }

                        /*************** END ***************/

                        /*************** Save in DB ***************/

                        string bd_path = relativeLocalPath.Replace("\\", "/") + repoFilename;
                        Global.GlobalMethods.AddFolioFile(userID, folioID, real_fileName, datetime_final, Convert.ToInt32(seconds), mediaType, bd_path);

                        /*************** END ***************/
                    }
                    catch (Exception e)
                    {
                        // #2- Logger exception
                        Logger.LogError("(%s) (%s) -- Excepcion. Obteniendo duración de archivo a subir, convirtiendo de .wav a mp3 si aplica, copiando archivo al server y guardando en BD. ERROR: %s", className, methodName, e.Message);
                        ok = false;
                    }
                }

                // Delete File name auxiliar with real extension
                if (isFileAUX_created)
                {
                    try
                    {
                        if (File.Exists(fullLocalPath + repoFilenameAUX))
                        {
                            File.Delete(fullLocalPath + repoFilenameAUX);
                        }
                    }
                    catch (Exception e)
                    {
                        // #2- Logger exception
                        Logger.LogError("(%s) (%s) -- Excepcion. Borrando archivo subido auxiliar para obtener duracion. ERROR: %s", className, methodName, e.Message);
                    }
                }

                // Reload elements
                SearchFolioElements();
            }
        }
        private void UploadFile()
        {
            if (HttpContext.Current.Session["UserID"] != null && ViewState["FolioID"] != null)
            {
                // #1- Logger variables
                System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
                string className = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;
                string methodName = stackFrame.GetMethod().Name;

                // Source: http://stackoverflow.com/questions/1998452/accessing-input-type-file-at-server-side-in-asp-net

                /* ******** Get file extension ******** */
                string fileName = MyFileUpload.PostedFile.FileName;
                string file_extension = string.Empty;

                if (!string.IsNullOrWhiteSpace(fileName))
                {
                    string[] extensionArray = fileName.Split('.');
                    if (extensionArray.Length > 0)
                    {
                        file_extension = extensionArray[1];
                    }
                }

                /* ******** Global variables ******** */
                string userID = HttpContext.Current.Session["UserID"].ToString();
                string folioID = ViewState["FolioID"].ToString();
                string repoFilename = "", repoFilenameAUX = "", fullLocalPath = "", relativeLocalPath = "";
                bool ok = true, isFileAUX_created = false;

                // File ID
                string guid = Guid.NewGuid().ToString();

                // Get datetime 1
                DateTime datetime_final = DateTime.Now;
                string datetimeStr = DateTime.Now.ToString("dd'-'MM'-'yyyy HH':'mm':'ss");
                if (uploadDate != null && !string.IsNullOrWhiteSpace(uploadDate.Value))
                {
                    datetimeStr = uploadDate.Value;
                    Logger.LogDebug("(%s) (%s) -- Get datetime1: Intentando convertir a datetime. Formato: dd-MM-yyyy HH:mm:ss. Dato: " + uploadDate.Value.ToString(), className, methodName);
                    if (!DateTime.TryParseExact(uploadDate.Value, "dd-MM-yyyy HH:mm:ss", null, System.Globalization.DateTimeStyles.None, out datetime_final))
                    //if (!DateTime.TryParse(uploadDate.Value.ToString(), out datetime_final))
                    {
                        datetime_final = DateTime.Now;

                        // #2- Logger exception
                        Logger.LogError("(%s) (%s) -- Excepcion. Convirtiendo a datetime.", className, methodName);
                        Logger.LogError("(%s) (%s) -- Dato: " + uploadDate.Value, className, methodName);
                    }
                }

                // Get datetime 2
                DateTime datetime2_a = DateTime.Now;
                string datetimeStr_a = DateTime.Now.ToString("dd'-'MM'-'yyyy HH':'mm':'ss");
                if (camarasDate1 != null && !string.IsNullOrWhiteSpace(camarasDate1.Value))
                {
                    datetimeStr_a = camarasDate1.Value;
                    Logger.LogDebug("(%s) (%s) -- Get datetime2_a: Intentando convertir a datetime. Formato: dd-MM-yyyy HH:mm. Dato: " + camarasDate1.Value.ToString(), className, methodName);
                    if (!DateTime.TryParseExact(camarasDate1.Value, "dd-MM-yyyy HH:mm", null, System.Globalization.DateTimeStyles.None, out datetime2_a))
                    //if (!DateTime.TryParse(camarasDate1.Value.ToString(), out datetime2_a))
                    {
                        datetime2_a = DateTime.Now;

                        // #2- Logger exception
                        Logger.LogError("(%s) (%s) -- Excepcion. Convirtiendo a datetime.", className, methodName);
                        Logger.LogError("(%s) (%s) -- Dato: " + camarasDate1.Value, className, methodName);
                    }
                }

                DateTime datetime2_b = DateTime.Now;
                string datetimeStr_b = DateTime.Now.ToString("dd'-'MM'-'yyyy HH':'mm':'ss");
                if (camarasDate2 != null && !string.IsNullOrWhiteSpace(camarasDate2.Value))
                {
                    datetimeStr_b = camarasDate2.Value;
                    Logger.LogDebug("(%s) (%s) -- Get datetime2_b: Intentando convertir a datetime. Formato: dd-MM-yyyy HH:mm. Dato: " + camarasDate2.Value.ToString(), className, methodName);
                    if (!DateTime.TryParseExact(camarasDate2.Value, "dd-MM-yyyy HH:mm", null, System.Globalization.DateTimeStyles.None, out datetime2_b))
                    //if (!DateTime.TryParse(camarasDate2.Value.ToString(), out datetime2_b))
                    {
                        datetime2_b = DateTime.Now;

                        // #2- Logger exception
                        Logger.LogError("(%s) (%s) -- Excepcion. Convirtiendo a datetime.", className, methodName);
                        Logger.LogError("(%s) (%s) -- Dato: " + camarasDate2.Value, className, methodName);
                    }
                }

                if (string.IsNullOrWhiteSpace(txbInputCameraNumber.Value))
                {
                    if (MyFileUpload != null && MyFileUpload.PostedFile != null && MyFileUpload.PostedFile.FileName.Length > 0)
                    {
                        /* ******** Configuration variables ******** */

                        // Repository path
                        string localRepoPath = string.Empty;
                        if (ConfigurationManager.AppSettings != null)
                        {
                            localRepoPath = ConfigurationManager.AppSettings["LocalRepoPath"].ToString();
                        }

                        string server = string.Empty;
                        if (ConfigurationManager.AppSettings != null)
                        {
                            server = ConfigurationManager.AppSettings["DB_Server"].ToString();
                        }

                        // File name
                        repoFilename = guid + ".bin";

                        // File name auxiliar with real extension
                        repoFilenameAUX = guid + "." + file_extension;

                        // Repository relative path
                        relativeLocalPath = datetime_final.Year.ToString("D4") + "\\" + datetime_final.Month.ToString("D2") + "\\" + datetime_final.Day.ToString("D2") + "\\" + datetime_final.Hour.ToString("D2") + "\\";

                        fullLocalPath = localRepoPath + relativeLocalPath; // REAL

                        if (!string.IsNullOrWhiteSpace(fullLocalPath) && !string.IsNullOrWhiteSpace(repoFilename))
                        {
                            try
                            {
                                if (!Directory.Exists(Path.GetDirectoryName(fullLocalPath)))
                                {
                                    Directory.CreateDirectory(Path.GetDirectoryName(fullLocalPath));
                                }
                                MyFileUpload.PostedFile.SaveAs(fullLocalPath + repoFilename);
                                MyFileUpload.PostedFile.SaveAs(fullLocalPath + repoFilenameAUX);
                                isFileAUX_created = true;
                            }
                            catch (Exception e)
                            {
                                // #2- Logger exception
                                Logger.LogError("(%s) (%s) -- Excepcion. Subiendo archivo con local test. ERROR: %s", className, methodName, e.Message);
                                ok = false;
                            }
                        }
                    }
                }
                else
                {
                    // IS CAMERA SYSTEM ****************************************************
                    ok = false;

                    string cameraNumber_str = txbInputCameraNumber.Value;

                    // WS InConcert Operaciones grabación settings
                    string WS_InConcert_Server = "192.168.10.31";
                    if (ConfigurationManager.AppSettings != null)
                    {
                        WS_InConcert_Server = ConfigurationManager.AppSettings["WS_InConcert_Server"].ToString();
                    }

                    string WS_InConcert_Port = "8081";
                    if (ConfigurationManager.AppSettings != null)
                    {
                        WS_InConcert_Port = ConfigurationManager.AppSettings["WS_InConcert_Port"].ToString();
                    }

                    string WS_InConcert_URL_operacionesGrabacion = "RecordingIntegration/WebServices/OperacionesGrabacion.asmx";
                    if (ConfigurationManager.AppSettings != null)
                    {
                        WS_InConcert_URL_operacionesGrabacion = ConfigurationManager.AppSettings["WS_InConcert_URL_operacionesGrabacion"].ToString();
                    }

                    // WS Endpoint
                    EndpointAddress endpointUser = new EndpointAddress(new Uri("http://" + WS_InConcert_Server + ":" + WS_InConcert_Port + "/" + WS_InConcert_URL_operacionesGrabacion));

                    // WS client
                    var wsClient = new RecordingIntegration.OperacionesGrabacionSoapBindingClient("OperacionesGrabacionSoapBinding", endpointUser);

                    // Call WS operation
                    wsClient.videoAsociado(folioID, userID, cameraNumber_str, datetime2_a.ToString("dd'/'MM'/'yyyy HH':'mm"), datetime2_b.ToString("dd'/'MM'/'yyyy HH':'mm"));
                }

                /* ******** Save in DB ******** */

                if (ok && !string.IsNullOrWhiteSpace(file_extension) && !string.IsNullOrWhiteSpace(fileName)
                    && !string.IsNullOrWhiteSpace(relativeLocalPath) && !string.IsNullOrWhiteSpace(repoFilename))
                {
                    // Get file MediaType
                    string mediaType = GetFileMediaType(file_extension);

                    // Get file Duration
                    // Source: http://stackoverflow.com/questions/1256841/c-sharp-get-video-file-duration-from-metadata
                    //int real_duration = GetFileDuration(fullLocalPath + repoFilename, mediaType);

                    //Source: http://www.codeproject.com/Articles/43208/How-to-get-the-length-duration-of-a-media-File-in-.aspx
                    // http://forums.asp.net/t/1679210.aspx?Get+Video+duration+after+uploading+asp+net+C+

                    try
                    {
                        double seconds = 0;
                        ShellFile so = ShellFile.FromFilePath(fullLocalPath + repoFilenameAUX);
                        double nanoseconds;
                        double.TryParse(so.Properties.System.Media.Duration.Value.ToString(), out nanoseconds);
                        if (nanoseconds > 0)
                        {
                            seconds = Convert100NanosecondsToMilliseconds(nanoseconds) / 1000;
                        }

                        string bd_path = relativeLocalPath.Replace("\\", "/") + repoFilename;

                        Global.GlobalMethods.AddFolioFile(userID, folioID, fileName, datetime_final, Convert.ToInt32(seconds), mediaType, bd_path);
                    }
                    catch (Exception e)
                    {
                        // #2- Logger exception
                        Logger.LogError("(%s) (%s) -- Excepcion. Obteniendo duración de archivo a subir y guardando en BD. ERROR: %s", className, methodName, e.Message);
                        ok = false;
                    }
                }

                if (isFileAUX_created)
                {
                    try
                    {
                        if (File.Exists(fullLocalPath + repoFilenameAUX))
                        {
                            File.Delete(fullLocalPath + repoFilenameAUX);
                        }
                    }
                    catch (Exception e)
                    {
                        // #2- Logger exception
                        Logger.LogError("(%s) (%s) -- Excepcion. Borrando archivo subido auxiliar para obtener duracion. ERROR: %s", className, methodName, e.Message);
                    }
                }

                // Reload elements
                SearchFolioElements();
            }
        }