Example #1
0
 public override void OnHeaderStartAnimator(IRefreshHeader header, int headerHeight, int extendHeight)
 {
     mHeaderStartAnimator = String.Format(Locale.China, "%s\nheight=%03d extend=%03d",
                                          FORMAT.Format(new Date()),
                                          headerHeight, extendHeight);
     updateContent();
 }
Example #2
0
 public override void OnFooterReleasing(IRefreshFooter footer, float percent, int offset, int footerHeight, int extendHeight)
 {
     mFooterReleasing = String.Format(Locale.China, "%s\npercent=%.02f\noffset=%03d height=%03d\nextend=%03d",
                                      FORMAT.Format(new Date()),
                                      percent, offset, footerHeight, extendHeight);
     updateContent();
 }
Example #3
0
        void convert(FORMAT conFormat)
        {
            long val = 0;

            try
            {
                if (conFormat == FORMAT.BINARY && tbxConBin.Text != string.Empty)
                {
                    val = Convert.ToInt64(tbxConBin.Text, 2);
                }
                else if (conFormat == FORMAT.HEX && tbxConHex.Text != string.Empty)
                {
                    val = Convert.ToInt64(tbxConHex.Text, 16);
                }
                else if (conFormat == FORMAT.DECIMAL && tbxConDec.Text != string.Empty)
                {
                    val = Convert.ToInt64(tbxConDec.Text, 10);
                }

                tbxConBin.Text = Convert.ToString(val, 2);
                tbxConDec.Text = Convert.ToString(val, 10);
                tbxConHex.Text = Convert.ToString(val, 16);
            }
            catch (Exception) {  }
        }
        public static void ConvertTask(TASK Task, FORMAT formatToConvert)
        {
            try
            {
                Task.STATUS = (int)EnumManager.PARAM_TASK_STATUS.EN_COURS;
                new TASK_Service().UpdateTask(Task);
                FFMpegService.Execute(Task.FILE_URL_TEMP, formatToConvert.FORMAT_FFMPEG_VALUE, Task.FILE_URL_DESTINATION);
                bool fileIsAvailable = CheckFileIsAvailable(Task.FILE_URL_DESTINATION);

                if (!fileIsAvailable)
                {
                    throw new Exception();
                }

                Task.DATE_END_CONVERSION = DateTime.Now;
                Task.STATUS = (int)EnumManager.PARAM_TASK_STATUS.EFFECTUE;
            }
            catch (Exception e)
            {
                Task.DATE_END_CONVERSION = DateTime.Now;
                Task.STATUS = (int)EnumManager.PARAM_TASK_STATUS.ERREUR;
                new TASK_Service().UpdateTask(Task);

                TRACE Trace = new TRACE {
                    FK_ID_TASK = Task.PK_ID_TASK, FK_ID_SERVER = 1, DATE_TRACE = DateTime.Now, NOM_SERVER = System.Environment.MachineName, DESCRIPTION = e.Message + " " + e.InnerException + " " + e.InnerException, METHOD = "Conversion FFMPEG Convert Task", TYPE = "ERROR"
                };
                new TRACE_Service().AddTrace(Trace);
            }
        }
Example #5
0
 public override void OnHeaderReleasing(IRefreshHeader header, float percent, int offset, int headerHeight, int extendHeight)
 {
     mHeaderReleasing = String.Format(Locale.China, "%s\npercent=%.02f offset=%03d\nheight=%03d extend=%03d",
                                      FORMAT.Format(new Date()),
                                      percent, offset, headerHeight, extendHeight);
     updateContent();
 }
Example #6
0
 public override void OnStateChanged(IRefreshLayout refreshLayout, RefreshState oldState, RefreshState newState)
 {
     mStateChanged = String.Format(Locale.China, "%s\nnew=%s\nold=%s",
                                   FORMAT.Format(new Date()),
                                   newState.Name(),
                                   oldState.Name());
     updateContent();
 }
        /// <summary>
        /// Очитсить содержимое книги MS Excel
        /// </summary>
        /// <param name="strNameSettingsExcelFile">Полный путь + наименование для очищаемой книги (файла конфигурации)</param>
        /// <param name="format">Формат книги MS Excel</param>
        private static void clearWorkbook(string strNameSettingsExcelFile = @"", FORMAT format = FORMAT.ORDER)
        {
            string strNameSettings = getFullNameSettingsExcelFile(strNameSettingsExcelFile);
            int    i = -1, j = -1;

            try {
                closeWorkbook(strNameSettings);

                ExcelFile ef = new ExcelFile();
                ef.LoadXls(strNameSettings, XlsOptions.None);

                if (ef.Protected == false)
                {
                    foreach (ExcelWorksheet ews in ef.Worksheets)
                    {
                        GemBox.Spreadsheet.CellRange range = ews.GetUsedCellRange();

                        Logging.DebugCaller(MethodBase.GetCurrentMethod(), string.Format(@"{0}Очистка листа с имененм = {1}", Environment.NewLine, ews.Name));

                        if ((range.LastRowIndex + 1) > 0)
                        {
                            // создать структуру таблицы - добавить поля в таблицу, при необходимости создать таблицу
                            createDataTableWorksheet(ews.Name, range);
                            // удалить значения, если есть
                            if (_dictDataTableOfExcelWorksheet[ews.Name].Rows.Count > 0)
                            {
                                _dictDataTableOfExcelWorksheet[ews.Name].Rows.Clear();
                            }
                            else
                            {
                                ;
                            }

                            for (i = range.FirstRowIndex + (format == FORMAT.HEAP ? 0 : format == FORMAT.ORDER ? 1 : 0); !(i > (range.LastRowIndex + 1)); i++)
                            {
                                for (j = range.FirstColumnIndex; !(j > range.LastColumnIndex); j++)
                                {
                                    range[i - range.FirstRowIndex, j - range.FirstColumnIndex].Value = string.Empty;
                                }
                            }
                        }
                        else
                        {
                            ;
                        }
                    }

                    ef.SaveXls(strNameSettings);
                }
                else
                {
                    Logging.DebugCaller(MethodBase.GetCurrentMethod(), string.Format(@"{0}Очистка книги с имененм = {1} невозможна", Environment.NewLine, strNameSettings));
                }
            } catch (Exception e) {
                Logging.DebugCaller(MethodBase.GetCurrentMethod(), string.Format(@"{0}Сохранение MSExcel-книги исключение: {1}{0}{2}", Environment.NewLine, e.Message, e.StackTrace));
            }
        }
Example #8
0
        public static bool GetTaskAndSetIfTaskIsSplitted(TASK Task, FORMAT Format)
        {
            bool result = false;

            try
            {
                TRACE Trace = new TRACE {
                    FK_ID_TASK = Task.PK_ID_TASK, FK_ID_SERVER = 1, DATE_TRACE = DateTime.Now, NOM_SERVER = System.Environment.MachineName, METHOD = "CREATION DES FICHIERS TEMPORAIRES", TYPE = "INFO"
                };
                new TRACE_Service().AddTrace(Trace);

                string fileUrl  = Task.FILE_URL;
                int    count    = (fileUrl.LastIndexOf(@"\") + 1);
                string fileName = fileName = fileUrl.Substring(count);

                // si le fichier n'a pas été encore splitté
                if (Task.FILE_URL_TEMP == null)
                {
                    Task.FILE_URL_TEMP = sourceFolder + @"\" + fileName;
                    if (File.Exists(fileUrl))
                    {
                        if (File.Exists(Task.FILE_URL_TEMP))
                        {
                            File.Delete(Task.FILE_URL_TEMP);
                        }
                        File.Copy(fileUrl, Task.FILE_URL_TEMP);
                    }
                }

                if (VerifyTaskLengthAndSplitTask(Task))
                {
                    Task.STATUS = (int)EnumManager.PARAM_TASK_STATUS.DECOUPE;
                    result      = true;
                }
                else
                {
                    count    = (fileName.LastIndexOf('.') + 1);
                    fileName = fileName.Substring(0, count);
                    Task.FILE_URL_DESTINATION = destinationFolder + @"\" + fileName + Format.FORMAT_NAME;
                    result = false;
                }
                new TASK_Service().AddOrUpdateTask(Task);

                return(result);
            }
            catch (Exception e)
            {
                TRACE Trace = new TRACE {
                    FK_ID_TASK = Task.PK_ID_TASK, FK_ID_SERVER = 1, DATE_TRACE = DateTime.Now, NOM_SERVER = System.Environment.MachineName, DESCRIPTION = e.Message, METHOD = "CREATION DES FICHIERS TEMPORAIRES", TYPE = "ERROR"
                };
                new TRACE_Service().AddTrace(Trace);
                return(false);
            }
        }
Example #9
0
 private void CbxFormat_SelectedIndexChanged(object sender, EventArgs e)
 {
     foreach (FORMAT fmat in Enum.GetValues(typeof(FORMAT)))
     {
         if (fmat.ToString().Equals(cbxFormat1.Text))
         {
             inFormat1 = fmat;
             break;
         }
     }
 }
        /// <summary>
        /// Создать таблицу для проецирования значений с листа книги MS Excel
        ///  , где наименования полей таблицы содержатся в 0-ой строке листа книги MS Excel
        /// </summary>
        /// <param name="nameWorksheet">Наименование листа книги MS Excel</param>
        /// <param name="rg">Регион на листе(странице) книги MS Excel</param>
        /// <param name="format">Формат книги MS Excel</param>
        private static void createDataTableWorksheet(string nameWorksheet
                                                     , GemBox.Spreadsheet.CellRange rg
                                                     , FORMAT format = FORMAT.ORDER)
        {
            string nameColumn = string.Empty;

            if (_dictDataTableOfExcelWorksheet == null)
            {
                // добавить элемент
                _dictDataTableOfExcelWorksheet = new Dictionary <string, System.Data.DataTable>();
            }
            else
            {
                ;
            }

            if (_dictDataTableOfExcelWorksheet.Keys.Contains(nameWorksheet) == false)
            {
                // добавить таблицу (пустую)
                _dictDataTableOfExcelWorksheet.Add(nameWorksheet, new System.Data.DataTable());
            }
            else
            {
                ;
            }

            if (!(_dictDataTableOfExcelWorksheet[nameWorksheet].Columns.Count == (rg.LastColumnIndex + 1)))
            {
                _dictDataTableOfExcelWorksheet[nameWorksheet].Columns.Clear();

                for (int j = rg.FirstColumnIndex; !(j > rg.LastColumnIndex); j++)
                {
                    // наименование столбцов таблицы всегда в 0-ой строке листа книги MS Excel
                    switch (format)
                    {
                    case FORMAT.HEAP:
                        nameColumn = string.Format(@"{0:000}", j);
                        break;

                    case FORMAT.ORDER:
                    default:
                        nameColumn = rg[0, j - rg.FirstColumnIndex].Value.ToString();
                        break;
                    }
                    // все поля в таблице типа 'string'
                    _dictDataTableOfExcelWorksheet[nameWorksheet].Columns.Add(nameColumn, typeof(string));
                }
            }
            else
            {
                ;
            }
        }
 public CellStyle(FORMAT format        = FORMAT.NORMAL, BORDER border = BORDER.NORMAL,
                  HALIGNMENT alignment = HALIGNMENT.NORMAL, VALIGNMENT valignment = VALIGNMENT.NORMAL,
                  COLOR color          = COLOR.NORMAL, CONTROL control = CONTROL.NORMAL,
                  FONTSTYLE font       = FONTSTYLE.NORMAL)
 {
     this.format     = format;
     this.border     = border;
     this.alignment  = alignment;
     this.valignment = valignment;
     this.color      = color;
     this.control    = control;
     this.font       = font;
 }
 public void ArrayWrite(Array array, FORMAT f)
 {
     foreach (Object o in array)
     {
         if (f == FORMAT.vertical)
         {
             Console.WriteLine(o.ToString());
         }
         else
         {
             Console.Write(o.ToString() + " ");
         }
     }
 }
        /// <summary>
        /// Сохранить внесенные изменения в книге MS Excel
        /// </summary>
        /// <param name="strNameSettingsExcelFile">Полный путь + наименование для сохраняемой книги (файла конфигурации)</param>
        /// <param name="format">Формат книги MS Excel</param>
        private static void saveWorkbook(string strNameSettingsExcelFile = @"", FORMAT format = FORMAT.ORDER)
        {
            string strNameSettings = getFullNameSettingsExcelFile(strNameSettingsExcelFile);
            int    i = -1, j = -1;

            try {
                closeWorkbook(strNameSettings);

                ExcelFile ef = new ExcelFile();
                ef.LoadXls(strNameSettings, XlsOptions.None);

                if (ef.Protected == false)
                {
                    foreach (ExcelWorksheet ews in ef.Worksheets)
                    {
                        GemBox.Spreadsheet.CellRange range = ews.GetUsedCellRange();

                        Logging.DebugCaller(MethodBase.GetCurrentMethod(), string.Format(@"{0}Сохранение листа с имененм = {1}", Environment.NewLine, ews.Name));

                        try {
                            ews.InsertDataTable(_dictDataTableOfExcelWorksheet[ews.Name]
                                                , range.FirstRowIndex + (format == FORMAT.HEAP ? 0 : format == FORMAT.ORDER ? 1 : 0)
                                                , range.FirstColumnIndex
                                                , false
                                                );

                            //if ((range.LastRowIndex + 1) > 0) {
                            //    for (i = range.FirstRowIndex + 1; !(i > (range.LastRowIndex + 1)); i++) {
                            //        for (j = range.FirstColumnIndex; !(j > range.LastColumnIndex); j++) {
                            //            range[i - range.FirstRowIndex, j - range.FirstColumnIndex].Value = string.Empty;
                            //        }
                            //    }
                            //} else
                            //    ;
                        } catch (Exception e) {
                            Logging.DebugCaller(MethodBase.GetCurrentMethod(), string.Format(@"{0}Сохранение книги с имененм = {1}, лист = {2} невозможна", Environment.NewLine, strNameSettings, ews.Name));
                        }
                    }

                    ef.SaveXls(strNameSettings);
                }
                else
                {
                    Logging.DebugCaller(MethodBase.GetCurrentMethod(), string.Format(@"{0}Сохранение книги с имененм = {1} невозможна", Environment.NewLine, strNameSettings));
                }
            } catch (Exception e) {
                Logging.DebugCaller(MethodBase.GetCurrentMethod(), string.Format(@"{0}Сохранение MSExcel-книги исключение: {1}{0}{2}", Environment.NewLine, e.Message, e.StackTrace));
            }
        }
Example #14
0
        private FORMAT getInputFormat()
        {
            return(this.Dispatcher.Invoke(() =>
            {
                FORMAT inputFormat = FORMAT.MONO16;

                if ((bool)formatRadio_mono16.IsChecked)
                {
                    inputFormat = FORMAT.MONO16;
                }
                else if ((bool)formatRadio_mono12p.IsChecked)
                {
                    inputFormat = FORMAT.MONO12p;
                }
                return inputFormat;
            }));
        }
        public static bool GetTaskAndSetIfTaskIsSplitted(TASK Task, FORMAT Format)
        {
            bool result = false;

            try
            {
                TRACE Trace = new TRACE {
                    FK_ID_TASK = Task.PK_ID_TASK, FK_ID_SERVER = 1, NOM_SERVER = System.Environment.MachineName, DATE_TRACE = DateTime.Now, METHOD = "GetTaskAndSetIfTaskIsSplitted", TYPE = "INFO"
                };
                new TRACE_Service().AddTrace(Trace);

                string fileName = GetFileName(Task);

                // si le fichier n'a pas été encore copié, on le copie dans notre repertoire temporaire.
                CopyFileInTempFolder(fileName, Task);

                // On verifie si la tache doit être splittée ou non, si c'est le cas nous la splittons
                bool isSplitted = VerifyTaskLengthAndSplitTask(Task);
                if (isSplitted)
                {
                    Task.STATUS = (int)EnumManager.PARAM_TASK_STATUS.DECOUPE;
                    result      = true;
                }
                else
                {
                    int count = (fileName.LastIndexOf('.') + 1);
                    fileName = fileName.Substring(0, count);
                    Task.FILE_URL_DESTINATION = destinationFolder + @"\" + fileName + Format.FORMAT_NAME;
                    result = false;
                }
                new TASK_Service().UpdateTask(Task);

                return(result);
            }
            catch (Exception e)
            {
                TRACE Trace = new TRACE {
                    FK_ID_TASK = Task.PK_ID_TASK, FK_ID_SERVER = 1, DATE_TRACE = DateTime.Now, NOM_SERVER = System.Environment.MachineName, DESCRIPTION = e.Message + " " + e.InnerException + " " + e.InnerException, METHOD = "CREATION DES FICHIERS TEMPORAIRES", TYPE = "ERROR"
                };
                new TRACE_Service().AddTrace(Trace);
                return(false);
            }
        }
Example #16
0
        void parse(string txt, FORMAT f, out string res, out long res2)
        {
            res = "";

            txt = txt.Replace(" ", "").ToLower();
            long?val = null;

            try
            {
                if (f == FORMAT.DECIMAL)
                {
                    val = Convert.ToInt64(txt, 10);
                    res = Convert.ToString((long)val, 2);
                }
                else if (f == FORMAT.HEX)
                {
                    txt = txt.Replace("0x", "");
                    val = Convert.ToInt64(txt, 16);
                    res = Convert.ToString((long)val, 2);
                }
                else if (f == FORMAT.BINARY)
                {
                    txt = txt.Replace("0b", "");
                    val = Convert.ToInt64(txt, 2);
                    res = Convert.ToString((long)val, 2);
                }
            }
            catch (Exception) { }

            string bitOverflow = "You have a bit overflow! Check your architecture";


            if (val == null)
            {
                MessageBox.Show("Invalid input! Please ensure that your format is correct.");
                res  = "";
                res2 = 0;
            }
            else
            {
                res = formatStr(res);

                int totBits = res.Replace(" ", "").Length - 1;

                res2 = (long)val;
                if (res2 < 0 && signed)
                {
                    return;
                }

                bool overflow =
                    ((ulong)res2 > UInt64.MaxValue && bitArchitecture == 64 && !signed) ||
                    (res2 > UInt32.MaxValue && bitArchitecture == 32 && !signed) ||
                    (res2 > UInt16.MaxValue && bitArchitecture == 16 && !signed) ||
                    totBits > bitArchitecture;

                if (overflow)
                {
                    MessageBox.Show(bitOverflow);
                }
            }
        }
Example #17
0
        private void ProcessRAW(string[] srcRGBTriplet, ShotSetting[] shotSettings, string targetFilename, TARGETFORMAT targetFormat, FORMAT inputFormat, int maxThreads, float HDRClippingPoint, float HDRFeatherMultiplier, bool EXRIntegrityVerification)
        {
            int groupLength = shotSettings.Length;

            byte[][] buffers = new byte[groupLength][];
            for (int i = 0; i < groupLength; i++)
            {
                buffers[i] = File.ReadAllBytes(srcRGBTriplet[i]);
                if (inputFormat == FORMAT.MONO12p)
                {
                    buffers[i] = convert12pto16bit(buffers[i]);
                }
            }


            int width  = 4096;
            int height = 3000;

            this.Dispatcher.Invoke(() =>
            {
                width = 1;
                int.TryParse(rawWidth.Text, out width);
                height = 1;
                int.TryParse(rawHeight.Text, out height);
            });


            byte[][] RGBBuffers = HDRMerge(buffers, shotSettings, HDRClippingPoint, HDRFeatherMultiplier);

            byte[] buffR = RGBBuffers[0];
            byte[] buffG = RGBBuffers[1];
            byte[] buffB = RGBBuffers[2];

            // Interleave
            int pixelCount  = width * height;
            int totalLength = width * height * 3;

            byte[] buff = new byte[totalLength * 2];


            if (buffR.Count() < pixelCount * 2)
            {
                this.Dispatcher.Invoke(() =>
                {
                    MessageBox.Show("Red file too short: " + srcRGBTriplet[0]);
                });
                return;
            }
            if (buffG.Count() < pixelCount * 2)
            {
                this.Dispatcher.Invoke(() =>
                {
                    MessageBox.Show("Green file too short: " + srcRGBTriplet[1]);
                });
                return;
            }
            if (buffB.Count() < pixelCount * 2)
            {
                this.Dispatcher.Invoke(() =>
                {
                    MessageBox.Show("Blue file too short: " + srcRGBTriplet[2]);
                });
                return;
            }

            for (int pixelIndex = 0; pixelIndex < pixelCount; pixelIndex++)
            {
                /*
                 * // BGR
                 * buff[pixelIndex * 3 * 2] = buffB[pixelIndex * 2];
                 * buff[pixelIndex * 3 * 2 + 1] = buffB[pixelIndex * 2 + 1];
                 * buff[pixelIndex * 3 * 2 +4] = buffR[pixelIndex*2];
                 * buff[pixelIndex * 3 * 2 +5] = buffR[pixelIndex * 2 + 1];
                 * buff[pixelIndex * 3 * 2 +2] = buffG[pixelIndex * 2];
                 * buff[pixelIndex * 3 * 2 +3] = buffG[pixelIndex * 2 + 1];
                 */
                // RGB
                buff[pixelIndex * 3 * 2]     = buffR[pixelIndex * 2];
                buff[pixelIndex * 3 * 2 + 1] = buffR[pixelIndex * 2 + 1];
                buff[pixelIndex * 3 * 2 + 2] = buffG[pixelIndex * 2];
                buff[pixelIndex * 3 * 2 + 3] = buffG[pixelIndex * 2 + 1];
                buff[pixelIndex * 3 * 2 + 4] = buffB[pixelIndex * 2];
                buff[pixelIndex * 3 * 2 + 5] = buffB[pixelIndex * 2 + 1];
            }



            string fileName = targetFilename;

            if (targetFormat == TARGETFORMAT.EXR)
            {
                ResourceLimits.Thread = (ulong)maxThreads;
                ResourceLimits.LimitMemory(new Percentage(90));

                MagickReadSettings settings = new MagickReadSettings();
                settings.Width  = width;
                settings.Height = height;
                settings.Format = MagickFormat.Rgb; // Correction, this is actually right, I had flipped RGB to BGR elsewhere in the code before. Fixed now.

                /*ColorManager.ICC.ICCProfileWriter iccWriter = new ColorManager.ICC.ICCProfileWriter();
                 * iccWriter.WriteProfile(new ColorManager.ICC.ICCProfile());
                 */

                if (EXRIntegrityVerification)
                {
                    /*
                     * Info on half float format: https://www.openexr.com/about.html
                     */
                    // What does this mean for precision of converting 16 bit integers to 16 bit floating point?
                    // We need to know the maximum precision achievable to be able to tell rounding errors from actual integrity fails.
                    // More info here: https://en.wikipedia.org/wiki/Half-precision_floating-point_format
                    // Basically, precision at any given value is 11 bits or 2048 values.


                    int  integrityCheckFailCountLocal = 0;
                    bool integrityCheckPassed         = false;
                    bool retriesExhausted             = false;
                    while (!integrityCheckPassed && !retriesExhausted)
                    {
                        using (var image = new MagickImage(buff, settings))
                        {
                            //ExifProfile profile = new ExifProfile();
                            //profile.SetValue(ExifTag.UserComment, Encoding.ASCII.GetBytes(srcRGBTriplet[0] + "," + srcRGBTriplet[1] + "," + srcRGBTriplet[2]));
                            //image.SetProfile(profile);
                            image.Format = MagickFormat.Exr;
                            image.Settings.Compression = CompressionMethod.Piz;

                            //image.Write(fileName);

                            byte[] exrFile = image.ToByteArray();

                            bool integrityCheckFailed = false;
                            using (var reloadedImage = new MagickImage(exrFile))
                            {
                                reloadedImage.Depth      = 16;
                                reloadedImage.ColorSpace = ColorSpace.Undefined;
                                byte[] reloadedImageBytes = reloadedImage.ToByteArray(MagickFormat.Rgb);

                                integrityCheckFailed = integrityCheckFailed | !IntegrityChecker.VerifyIntegrityUInt16InHalfPrecisionFloat(buff, reloadedImageBytes);
                            }
                            if (integrityCheckFailed)
                            {
                                integrityCheckFailCount++;
                                integrityCheckFailCountLocal++;
                                continue;
                            }
                            else
                            {
                                integrityCheckPassed = true;
                                File.WriteAllBytes(fileName, exrFile);
                            }
                            if (integrityCheckFailCountLocal > integrityCheckRetries)
                            {
                                retriesExhausted = true;
                                // At this point just write it into a subfolder and be done with it.
                                string failedFolder = Path.GetDirectoryName(fileName) + Path.DirectorySeparatorChar + "FAILED" + Path.DirectorySeparatorChar;
                                Directory.CreateDirectory(failedFolder);
                                string failedFile = failedFolder + Path.GetFileName(fileName);

                                File.WriteAllBytes(failedFile, exrFile);
                            }
                        }
                    }
                }
                else
                {
                    using (var image = new MagickImage(buff, settings))
                    {
                        //ExifProfile profile = new ExifProfile();
                        //profile.SetValue(ExifTag.UserComment, Encoding.ASCII.GetBytes(srcRGBTriplet[0] + "," + srcRGBTriplet[1] + "," + srcRGBTriplet[2]));
                        //image.SetProfile(profile);
                        image.Format = MagickFormat.Exr;
                        image.Settings.Compression = CompressionMethod.Piz;

                        //image.Write(fileName);
                        byte[] exrFile = image.ToByteArray();
                        File.WriteAllBytes(fileName, exrFile);
                    }
                }
            }
            else if (targetFormat == TARGETFORMAT.TIF)
            {
                using (Tiff output = Tiff.Open(fileName, "w"))
                {
                    output.SetField(TiffTag.SUBFILETYPE, 0);
                    //output.SetField(TiffTag.ORIGINALRAWFILENAME, srcRGBTriplet[0]+","+srcRGBTriplet[1]+","+srcRGBTriplet[2]);
                    output.SetField(TiffTag.IMAGEWIDTH, width);
                    output.SetField(TiffTag.IMAGELENGTH, height);
                    output.SetField(TiffTag.SAMPLESPERPIXEL, 3);
                    output.SetField(TiffTag.BITSPERSAMPLE, 16);
                    output.SetField(TiffTag.ORIENTATION, Orientation.TOPLEFT);
                    output.SetField(TiffTag.PHOTOMETRIC, Photometric.RGB);
                    output.SetField(TiffTag.FILLORDER, FillOrder.MSB2LSB);
                    output.SetField(TiffTag.COMPRESSION, Compression.DEFLATE);

                    output.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);


                    output.WriteEncodedStrip(0, buff, width * height * 2 * 3);
                }
            }
        }
Example #18
0
        /*
         * // Order of colors
         * private byte[] getColorOrder()
         * {
         *  return this.Dispatcher.Invoke(() =>
         *  {
         *      //0=Red, 1=Green,   2=Blue
         *      byte colorAval = 0;
         *      byte colorBval = 1;
         *      byte colorCval = 2;
         *      byte.TryParse(colorA.Text, out colorAval);
         *      byte.TryParse(colorB.Text, out colorBval);
         *      byte.TryParse(colorC.Text, out colorCval);
         *      byte[] colorOrder = { colorAval, colorBval, colorCval };
         *      return colorOrder;
         *  });
         * }
         *
         * // Similar purpose as getColorOrder,
         * // but the returned array's index is the 3 colors (0 red 1 green 2 blue) and the content is the position
         * private byte[] getRGBPositions()
         * {
         *  byte[] colorOrder = getColorOrder();
         *  byte[] RGBPositions = new byte[3];
         *  for(byte i =0;i<3;i++)
         *  {
         *      switch (colorOrder[i])
         *      {
         *          case 0:
         *              RGBPositions[0] = i;
         *              break;
         *          case 1:
         *              RGBPositions[1] = i;
         *              break;
         *          case 2:
         *              RGBPositions[2] = i;
         *              break;
         *          default:
         *              // User entered some garbage!
         *              break;
         *      }
         *  }
         *  return RGBPositions;
         * }*/

        private void ReDrawPreview()
        {
            if (sourceFolder == null || filesInSourceFolder == null)
            {
                return; // Nothing to do here
            }

            int width = 1, height = 1;

            int.TryParse(rawWidth.Text, out width);
            int.TryParse(rawHeight.Text, out height);

            ShotSetting[] shotSettings = getShots();
            int           groupLength  = shotSettings.Length;


            //bool doPreviewDebayer = (bool)previewDebayer.IsChecked;
            bool doPreviewGamma        = (bool)previewGamma.IsChecked;

            float HDRClippingPoint     = getHDRClippingpoint();
            float HDRFeatherMultiplier = getFeatherMultiplier();

            int frameDelay = 0;

            int.TryParse(delay.Text, out frameDelay);
            //byte[] RGBPositions = getRGBPositions();

            int sliderNumber = (int)slide_currentFile.Value;

            double previewExposureMultiplier = Math.Pow(2, previewExposure_slider.Value);

            int baseIndex = (sliderNumber - 1) * groupLength + frameDelay;

            if ((baseIndex + (groupLength - 1)) > (filesInSourceFolder.Length - 1))
            {
                MessageBox.Show("Group incomplete.");
                return;
            }

            int[]    fileIndizi = new int[groupLength]; //{ baseIndex+RGBPositions[0], baseIndex + RGBPositions[1], baseIndex + RGBPositions[2] };
            string[] files      = new string[groupLength];

            string currentFileStringForGUI = "";

            for (int i = 0; i < groupLength; i++)
            {
                fileIndizi[i] = baseIndex + i;
                files[i]      = filesInSourceFolder[baseIndex + i];
            }
            for (int i = 0; i < groupLength; i++)
            {
                currentFileStringForGUI += shotSettings[i].channelColor + "*" + shotSettings[i].exposureMultiplier + ": " + files[shotSettings[i].orderIndex] + "\n";
            }

            //string[] RGBFiles = new string[3] { filesInSourceFolder[RGBIndizi[0]], filesInSourceFolder[RGBIndizi[1]] , filesInSourceFolder[RGBIndizi[2]] };

            filesInfo_txt.Text = currentFileStringForGUI;

            FORMAT inputFormat = getInputFormat();

            foreach (string file in files)
            {
                if (!File.Exists(file))
                {
                    MessageBox.Show("weirdo error, apparently file " + file + " (no longer?) exists");
                    return;
                }
            }
            {
                int subsample = 8;
                int.TryParse(previewSubsample_txt.Text, out subsample);

                int newWidth  = (int)Math.Ceiling((double)width / subsample);
                int newHeight = (int)Math.Ceiling((double)height / subsample);


                byte[] newbytes;

                {
                    byte[][] buffers = new byte[groupLength][];
                    for (int i = 0; i < groupLength; i++)
                    {
                        buffers[i] = File.ReadAllBytes(files[i]);
                        if (inputFormat == FORMAT.MONO12p)
                        {
                            buffers[i] = convert12pto16bit(buffers[i]);
                        }
                    }

                    int byteDepth = 2;            // This is for the source
                    int byteWidth = newWidth * 3; // This is for the preview. 3 means RGB
                    int newStride = Helpers.getStride(byteWidth);


                    byte[][] mergedRGBbuffers = HDRMerge(buffers, shotSettings, HDRClippingPoint, HDRFeatherMultiplier);

                    newbytes = Helpers.DrawPreview(mergedRGBbuffers[0], mergedRGBbuffers[1], mergedRGBbuffers[2], newHeight, newWidth, height, width, newStride, byteDepth, subsample, doPreviewGamma, previewExposureMultiplier);
                }

                // Put preview into WPF image tag
                Bitmap             manipulatedImage = new Bitmap(newWidth, newHeight, Imaging.PixelFormat.Format24bppRgb);
                Imaging.BitmapData pixelData        = manipulatedImage.LockBits(new Rectangle(0, 0, newWidth, newHeight), Imaging.ImageLockMode.WriteOnly, Imaging.PixelFormat.Format24bppRgb);

                System.Runtime.InteropServices.Marshal.Copy(newbytes, 0, pixelData.Scan0, newbytes.Count());

                manipulatedImage.UnlockBits(pixelData);

                System.Runtime.InteropServices.Marshal.Copy(newbytes, 0, pixelData.Scan0, newbytes.Count());
                // Do the displaying
                mainPreview.Source = Helpers.BitmapToImageSource(manipulatedImage);
            }
        }
Example #19
0
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            //_totalFiles = filesInSourceFolder.Length;

            List <string[]> completeGroups = new List <string[]>();

            int frameDelay = 0;

            //byte[] RGBPositions = new byte[1];
            ShotSetting[] shotSettings             = new ShotSetting[3];
            bool          IsTIFF                   = false;
            bool          IsEXR                    = false;
            int           maxThreads               = Environment.ProcessorCount;
            string        customOutputName         = "";
            int           leadingZeros             = 0;
            bool          overwriteExisting        = false;
            float         HDRClippingPoint         = 0.99f;
            float         HDRFeatherMultiplier     = 1;
            bool          EXRIntegrityVerification = true;

            this.Dispatcher.Invoke(() =>
            {
                frameDelay = 0;
                int.TryParse(delay.Text, out frameDelay);
                int.TryParse(outputNameLeadingZeros_txt.Text, out leadingZeros);
                int.TryParse(maxThreads_txt.Text, out maxThreads);
                //RGBPositions = getRGBPositions();
                shotSettings             = getShots();
                IsTIFF                   = (bool)formatTif.IsChecked;
                IsEXR                    = (bool)formatExr.IsChecked;
                customOutputName         = outputNameBase_txt.Text;
                overwriteExisting        = !(bool)overwrite_no.IsChecked && (bool)overwrite_yes.IsChecked;
                HDRClippingPoint         = getHDRClippingpoint();
                HDRFeatherMultiplier     = getFeatherMultiplier();
                EXRIntegrityVerification = (bool)exrIntegrityVerification_check.IsChecked;
            });

            int groupLength = shotSettings.Length;

            _totalFiles = (int)Math.Floor(filesInSourceFolder.Length / (decimal)groupLength);

            if (maxThreads == 0)
            {
                maxThreads = Environment.ProcessorCount;
            }


            FORMAT inputFormat = getInputFormat();

            TARGETFORMAT targetFormat = TARGETFORMAT.EXR;

            if (IsEXR)
            {
                targetFormat = TARGETFORMAT.EXR;
            }
            else
            {
                targetFormat = TARGETFORMAT.TIF;
            }


            for (int baseIndex = frameDelay; baseIndex < filesInSourceFolder.Length; baseIndex += groupLength)
            {
                if ((baseIndex + (groupLength - 1)) > (filesInSourceFolder.Length - 1))
                {
                    MessageBox.Show("Group incomplete. Skipping.");
                    continue;
                }

                int[]    fileIndizi = new int[groupLength];
                string[] files      = new string[groupLength];
                for (var i = 0; i < groupLength; i++)
                {
                    fileIndizi[i] = baseIndex + i;
                    files[i]      = filesInSourceFolder[baseIndex + i];
                }

                //int[] RGBIndizi = new int[groupLength] { baseIndex + RGBPositions[0], baseIndex + RGBPositions[1], baseIndex + RGBPositions[2] };

                //string[] RGBFiles = new string[groupLength] { filesInSourceFolder[RGBIndizi[0]], filesInSourceFolder[RGBIndizi[1]], filesInSourceFolder[RGBIndizi[2]] };

                completeGroups.Add(files);
            }

            int processFrom = 1;
            int processTo   = completeGroups.Count();

            this.Dispatcher.Invoke(() =>
            {
                int.TryParse(processFrom_txt.Text, out processFrom);
                int.TryParse(processTo_txt.Text, out processTo);
            });

            // Index starting at 0, but GUI starts at 1
            processFrom--;
            processTo--;


            var countLock = new object();

            CurrentProgress = 0;

            _counterTotal           = 0;
            _counterSkippedRange    = 0;
            _counterDone            = 0;
            _counterSkippedExisting = 0;

            if (EXRIntegrityVerification)
            {
                IntegrityChecker.BuildIntegrityVerificationAcceptableLossCache();
            }

            integrityCheckFailCount = 0;

            Parallel.ForEach(completeGroups,
                             new ParallelOptions {
                MaxDegreeOfParallelism = maxThreads
            }, (currentGroup, loopState, index) =>
                             // foreach (string srcFileName in filesInSourceFolder)
            {
                _counterTotal++;
                var percentage = (double)_counterTotal / _totalFiles * 100.0;
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    return;
                }

                if (index < processFrom || index > processTo)
                {
                    // Skip this one.
                    _counterSkippedRange++;
                    lock (countLock) { worker?.ReportProgress((int)percentage); }
                    return;
                }

                string fileNameWithoutFolder = customOutputName == "" ? Path.GetFileNameWithoutExtension(currentGroup[0]) : customOutputName + (leadingZeros == 0 ? index.ToString() : index.ToString("D" + leadingZeros.ToString()));

                string fileNameWithoutExtension =
                    targetFolder + "\\" + fileNameWithoutFolder;
                string fileName = fileNameWithoutExtension + (targetFormat == TARGETFORMAT.EXR ? ".exr" : "") + (targetFormat == TARGETFORMAT.TIF ? ".tif" : "");


                if (File.Exists(fileName) && !overwriteExisting)
                {
                    // Error: File already exists. No overwriting. Move on.
                    //continue;
                    _counterSkippedExisting++;
                    lock (countLock) { worker?.ReportProgress((int)percentage); }
                    return;
                }

                ProcessRAW(currentGroup, shotSettings, fileName, targetFormat, inputFormat, maxThreads, HDRClippingPoint, HDRFeatherMultiplier, EXRIntegrityVerification);
                _counterDone++;
                lock (countLock) { worker?.ReportProgress((int)percentage); }
            });
            this.Dispatcher.Invoke(() =>
            {
                txtStatus.Text = "Finished. " + integrityCheckFailCount + " integrity check fails";
            });
        }
        private static void extractDataWorksheet(ExcelWorksheet ews, GemBox.Spreadsheet.CellRange range, FORMAT format)
        {
            // создать структуру таблицы - добавить поля в таблицу, при необходимости создать таблицу
            createDataTableWorksheet(ews.Name, range, format);

            ews.ExtractDataEvent += new ExcelWorksheet.ExtractDataEventHandler((sender, e) => {
                e.DataTableValue = e.ExcelValue == null ? null : e.ExcelValue.ToString();
                e.Action         = ExtractDataEventAction.Continue;
            });

            try {
                ews.ExtractToDataTable(_dictDataTableOfExcelWorksheet[ews.Name]
                                       , range.LastRowIndex + 1
                                       , ExtractDataOptions.SkipEmptyRows | ExtractDataOptions.StopAtFirstEmptyRow
                                       , ews.Rows[range.FirstRowIndex + (format == FORMAT.HEAP ? 0 : format == FORMAT.ORDER ? 1 : 0)]
                                       , ews.Columns[range.FirstColumnIndex]
                                       );

                _dictDataTableOfExcelWorksheet[ews.Name].TableName = ews.Name;
            } catch (Exception e) {
                Logging.ExceptionCaller(MethodBase.GetCurrentMethod(), e, string.Format(@"Лист MS Excel: {0}", ews.Name));
            }

            Logging.DebugCaller(MethodBase.GetCurrentMethod(), string.Format(@"На листе с имененм = {0} полей = {1}", ews.Name, range.LastColumnIndex + 1));

            //// добавить записи в таблицу
            //for (i = range.FirstRowIndex + 1; !(i > range.LastRowIndex); i++) {
            //    dataRow = null;

            //    for (j = range.FirstColumnIndex; !(j > range.LastColumnIndex); j++) {
            //        cellValue = string.Empty;
            //        iValidateCellRes = validateCell(range, i, j);

            //        if (iValidateCellRes == VALIDATE_CELL_RESULT.NEW_ROW) {
            //            dataRow = _dictDataTableOfExcelWorksheet[ews.Name].Rows.Add();

            //            cellValue = range[i - range.FirstRowIndex, j - range.FirstColumnIndex].Value.ToString();
            //            acDoc.Editor.WriteMessage(string.Format(@"{0}Добавлена строка для элемента = {1}", Environment.NewLine, cellValue));
            //        } else
            //            if (iValidateCellRes == VALIDATE_CELL_RESULT.CONTINUE)
            //            continue;
            //        else
            //                if (iValidateCellRes == VALIDATE_CELL_RESULT.BREAK)
            //            break;
            //        else
            //            // значение для параметра (VALIDATE_CELL_RESULT.VALUE)
            //            cellValue = range[i - range.FirstRowIndex, j - range.FirstColumnIndex].Value.ToString();

            //        if (dataRow == null)
            //            break;
            //        else
            //            dataRow[j] = cellValue;
            //    }
            //}
        }
        private static GemBox.Spreadsheet.CellRange getUsedCellRange(ExcelWorksheet ews, FORMAT format)
        {
            GemBox.Spreadsheet.CellRange rangeRes = null;

            int iRow  = -1
            , iColumn = -1;

            // только для 'FORMAT.HEAP'
            iRow    = 0;
            iColumn = 0;
            while (!(ews.Rows[iRow].Cells[0].Value == null))
            {
                while (!(ews.Rows[iRow].Cells[iColumn].Value == null))
                {
                    iColumn++;
                }

                iRow++;
            }

            if ((iRow > 0) &&
                (iColumn > 0))
            {
                rangeRes = ews.Cells.GetSubrangeAbsolute(0, 0, iRow - 1, iColumn - 1);
            }
            else
            {
                ;
            }

            return(rangeRes);
        }
        /// <summary>
        /// Импортировать список объектов
        /// </summary>
        /// <param name="ef">Объект книги MS Excel</param>
        /// <param name="format">Формат книги MS Excel</param>
        /// <returns>Признак результата выполнения метода</returns>
        private static int import(ExcelFile ef, FORMAT format)
        {
            int iRes = 0;

            GemBox.Spreadsheet.CellRange range;
            EntityParser.ProxyEntity?    pEntity;
            string         nameEntity    = string.Empty;
            COMMAND_ENTITY commandEntity = COMMAND_ENTITY.UNKNOWN;

            foreach (ExcelWorksheet ews in ef.Worksheets)
            {
                if (ews.Name.Equals(WSHHEET_NAME_CONFIG) == false)
                {
                    range =
                        ews.GetUsedCellRange()
                        //getUsedCellRange(ews, format)
                    ;

                    Core.Logging.DebugCaller(MethodBase.GetCurrentMethod(), string.Format(@"Обработка листа с имененм = {0}", ews.Name));

                    if ((!(range == null)) &&
                        ((range.LastRowIndex + 1) > 0))
                    {
                        extractDataWorksheet(ews, range, format);

                        switch (ef.Worksheets.Cast <ExcelWorksheet>().ToList().IndexOf(ews))
                        {
                        case 0:     // BLOCK
                            foreach (DataRow rReferenceBlock in _dictDataTableOfExcelWorksheet[ews.Name].Rows)
                            {
                                s_dictBlock.AddReference(rReferenceBlock);
                            }
                            break;

                        default:
                            foreach (DataRow rEntity in _dictDataTableOfExcelWorksheet[ews.Name].Rows)
                            {
                                if (EntityParser.TryParseCommandAndNameEntity(format, rEntity, out nameEntity, out commandEntity) == true)
                                {
                                    pEntity = null;

                                    // соэдать примитив
                                    if (dictDelegateNewProxyEntity.ContainsKey(commandEntity) == true)
                                    {
                                        pEntity = dictDelegateNewProxyEntity[commandEntity](rEntity, format /*, ews.Name*/);
                                    }
                                    else
                                    {
                                        ;
                                    }

                                    if (!(pEntity == null))
                                    {
                                        s_dictBlock.AddEntity(
                                            ews.Name
                                            , commandEntity
                                            , pEntity.GetValueOrDefault()
                                            , nameEntity
                                            );
                                    }
                                    else
                                    {
                                        Logging.DebugCaller(MethodBase.GetCurrentMethod(), string.Format(@"Элемент с именем {0} пропущен..."
                                                                                                         , nameEntity
                                                                                                         ));
                                    }
                                }
                                else
                                {
                                    // ошибка при получении типа и наименования примитива
                                    Core.Logging.DebugCaller(MethodBase.GetCurrentMethod()
                                                             , string.Format(@"Ошибка опрделения имени, типа  сущности лист={0}, строка={1}...", ews.Name, _dictDataTableOfExcelWorksheet[ews.Name].Rows.IndexOf(rEntity)));
                                }
                            }     // цикл по строкам таблицы для листа книги MS Excel

                            Logging.DebugCaller(MethodBase.GetCurrentMethod(), string.Format(@"На листе с имененм = {0} обработано строк = {1}, добавлено элементов {2}"
                                                                                             , ews.Name
                                                                                             , range.LastRowIndex + 1
                                                                                             , _dictDataTableOfExcelWorksheet[ews.Name].Rows.Count
                                                                                             ));
                            break;
                        }
                    }
                    else
                    {
                        // нет строк с данными
                        Logging.DebugCaller(MethodBase.GetCurrentMethod(), string.Format(@"На листе с имененм = {0} нет строк для распознования", ews.Name));
                    }
                }
                else
                {
                    ; // страница(лист) с конфигурацией
                }
            }

            return(iRes);
        }
Example #23
0
        public Convert(string file_path, FORMAT format, config cfg, int lst_select)
        {
            this.file_path     = file_path;
            this.global_config = cfg;
            this.target_format = format;
            try
            {
                this.file_stream = new FileStream(file_path, FileMode.Open, FileAccess.Read);
            }
            catch (Exception exception)
            {
                if (exception.Message.Contains("正由另一进程使用"))
                {
                    MessageBox.Show("您的 " + file_path + " 文件已打开,请先关闭文件再进行转换!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
                return;
            }
            try
            {
                switch (Path.GetExtension(file_path).ToLower())
                {
                case ".pdf":
                    this.pdf_doc = new Aspose.Pdf.Document(this.file_stream, this.global_config.password);
                    this.pages   = this.pdf_doc.Pages.Count;
                    return;

                case ".doc":
                case ".docx":
                    this.word_doc = new Aspose.Words.Document(this.file_stream);
                    this.pages    = this.word_doc.PageCount;
                    break;

                case ".ppt":
                case ".pptx":
                    this.ppt_doc = new Presentation(this.file_stream);
                    this.pages   = this.ppt_doc.Slides.Count;
                    break;

                case ".xls":
                case ".xlsx":
                    this.excel_doc = new Workbook(this.file_stream);
                    this.pages     = this.excel_doc.Worksheets.Count;
                    break;
                }
            }
            catch (Aspose.Pdf.Exceptions.InvalidPasswordException)
            {
                passwordDlg  dlg    = new passwordDlg(Path.GetFileName(this.file_path));
                DialogResult result = dlg.ShowDialog();
                bool         flag   = true;
                while ((result == DialogResult.OK) && flag)
                {
                    try
                    {
                        this.file_stream = new FileStream(file_path, FileMode.Open, FileAccess.Read);
                        this.pdf_doc     = new Aspose.Pdf.Document(this.file_stream, dlg.new_password);
                        this.pages       = this.pdf_doc.Pages.Count;
                        flag             = false;
                    }
                    catch (Aspose.Pdf.Exceptions.InvalidPasswordException)
                    {
                        result = dlg.ShowDialog();
                    }
                }
                if (result == DialogResult.Cancel)
                {
                    this.err_msg       = "";
                    this.file_can_work = false;
                }
            }
            catch (Exception)
            {
                this.file_can_work = false;
                this.err_msg       = "发生未知错误";
            }
        }
        /// <summary>
        /// 読込処理
        /// </summary>
        private void LoadThreadMain(object state)
        {
            DataInfo dataInfo = (DataInfo)state;
            int      version  = -1;
            int      size     = 0;

            byte[] hash    = null;
            byte[] binary  = null;
            bool   encrypt = dataInfo.serializer.encrypt;
            FORMAT format  = dataInfo.serializer.format;

            // 他のリクエスト消化待ち
            while (dataInfo.async && this.IsAccessing())
            {
                Thread.Sleep(30);
            }

            lock (this.sync) {
                this.isAccessing = true;
            }

            // ストレージ読込
            try {
                using (FileStream inFs = File.OpenRead(dataInfo.filePath)) {
                    using (BinaryReader reader = new BinaryReader(inFs)) {
                        // ヘッダ読込
                        string magic = reader.ReadString();
                        // マジックNo.不一致
                        if (magic != dataInfo.serializer.magic)
                        {
                            Debug.LogWarning("CHANGED MAGIC NUMBER\n");
                            this.FinishAccessing(IO_RESULT.LOAD_FAILED, ref dataInfo);
                            return;
                        }
                        version = reader.ReadInt32();
                        size    = reader.ReadInt32();
                        hash    = reader.ReadBytes(HASH_SIZE);
                        binary  = new byte[size];
#if DEMO
                        encrypt = dataInfo.encrypt = reader.ReadBoolean();
                        format  = dataInfo.format = (FORMAT)reader.ReadInt32();
#endif

                        // 復号化して読込
                        if (encrypt)
                        {
                            bool success = this.DecryptFile(inFs, binary, size);
                            // 復号化失敗
                            if (!success)
                            {
                                this.FinishAccessing(IO_RESULT.LOAD_FAILED, ref dataInfo);
                                return;
                            }
                        }
                        // そのまま読込
                        else
                        {
                            inFs.Read(binary, 0, size);
                        }
                    }

                    // ハッシュチェック
                    if (!this.CheckHash(this.md5.ComputeHash(binary), hash))
                    {
                        Debug.LogWarning("HASH MISMATCH\n");
                        this.FinishAccessing(IO_RESULT.LOAD_FAILED, ref dataInfo);
                        return;
                    }

                    // デシリアライズ
                    using (MemoryStream outMs = new MemoryStream(binary)) {
                        switch (format)
                        {
                        case FORMAT.BINARY:
                            dataInfo.serializer = this.bf.Deserialize(outMs) as ISerializer;
                            break;

                        case FORMAT.JSON:
                            using (BinaryReader br = new BinaryReader(outMs)) {
                                string      json = br.ReadString();
                                System.Type type = dataInfo.serializer.type;
                                dataInfo.serializer = JsonUtility.FromJson(json, type) as ISerializer;
                            }
                            break;
                        }
                    }

                    // バージョンチェック
                    int nowVersion = dataInfo.serializer.version;
                    if (nowVersion > version)
                    {
                        Debug.Log("UPDATE VERSION\n" + version + "→" + nowVersion);
                        dataInfo.serializer.UpdateVersion(version);
                    }
                    else if (nowVersion < version)
                    {
                        Debug.LogError("DEGRADE VERSION\n" + version + "→" + nowVersion);
                        this.FinishAccessing(IO_RESULT.LOAD_FAILED, ref dataInfo);
                        return;
                    }
                }
            }
            catch (System.Exception e) {
                Debug.LogError("READ FAILED\n" + e.Message);
                this.FinishAccessing(IO_RESULT.LOAD_FAILED, ref dataInfo);
                return;
            }

            // 完了
            this.FinishAccessing(IO_RESULT.LOAD_SUCCESS, ref dataInfo);

#if DEBUG
            // 読込ファイルサイズ確認
            FileInfo fi = new FileInfo(dataInfo.filePath);
            Debug.Log("..........FILE_SIZE " + fi.Length + "\n..........SAVE_SIZE " + size);
#endif
        }
Example #25
0
 public PImage createImage(int width, int height, FORMAT format)
 {
     return new PImage(width, height, format);
 }
Example #26
0
    public static string GetTotals(string field, IList <string> argvalue, string stype, string sFormat, int nCulture, Dictionary <string, object> smarty, Builder builder, HttpRequest request, Smarty.MODE mode)
    {
        double value = 0.0;

        if (argvalue.Count == 0)
        {
            return(string.Empty);
        }
        if (stype != "COUNT")
        {
            foreach (string listValue in argvalue)
            {
                double testVal;
                if (double.TryParse(listValue, out testVal))
                {
                    value += testVal;
                }
            }
        }
        if (stype == "AVERAGE")
        {
            if (argvalue.Count > 0)
            {
                value = Math.Round(value / argvalue.Count, 2);
            }
            else
            {
                return(string.Empty);
            }
        }

        string sValue = string.Empty;
        FORMAT format = Control.StringToFormat(sFormat);

        if (format == FORMAT.FORMAT_CURRENCY)
        {
            CultureInfo ci = new CultureInfo(nCulture);
            sValue = value.ToString("C3", ci);
        }
        else if (format == FORMAT.FORMAT_PERCENT)
        {
            CultureInfo ci = new CultureInfo(nCulture);
            sValue = value.ToString("P", ci);
        }
        else if (format == FORMAT.FORMAT_NUMBER)
        {
            CultureInfo ci = new CultureInfo(nCulture);
            sValue = value.ToString("N", ci);
        }
        else if (format == FORMAT.FORMAT_CUSTOM && stype != "COUNT")
        {
            Control control = new Control(field, value, false, smarty, request, builder, mode);
            sValue = control.GetData();
        }
        else
        {
            sValue = value.ToString();
        }

        if (stype == "COUNT")
        {
            return(argvalue.Count.ToString());
        }
        if (stype == "TOTAL")
        {
            return(sValue);
        }
        if (stype == "AVERAGE")
        {
            return(sValue);
        }
        return(string.Empty);
    }
Example #27
0
 public override void OnFooterFinish(IRefreshFooter footer, bool success)
 {
     mFooterFinish = String.Format(Locale.China, "%s - " + success, FORMAT.Format(new Date()));
     updateContent();
 }
Example #28
0
 public override void OnLoadmore(IRefreshLayout refreshlayout)
 {
     mLoadmore = String.Format(Locale.China, "%s", FORMAT.Format(new Date()));
     updateContent();
 }