예제 #1
0
        public static SSCTechActivity DeSerialize_SSCTechActivity(FileType fileType, int surveyRowID)
        {
            //Stream stream = File.Open(String.Format("{0}{1}{2}.{3}", FilePathType.SerData.DirPath(), AppNEnvConfig.GetFileSeperator, surveyRowID, fileType.ToString()), FileMode.Open);
            Stream stream = File.Open(String.Format("{0}{1}{2}.{3}", AppNEnvConfig.TechSerData, AppNEnvConfig.GetFileSeperator, surveyRowID, fileType.ToString()), FileMode.Open);

            BinaryFormatter bformatter = new BinaryFormatter();

            var result = (SSCTechActivity)bformatter.Deserialize(stream);
            stream.Close();

            return result;
        }
예제 #2
0
        private string UrlToPdf(string url, FileType returnType)
        {
            var path = string.Format(@"{0}\lib\phantomjs-custom.exe", ApplicationDirectory);

            if (string.IsNullOrEmpty(path) || !File.Exists(path))
            {
                throw new FileNotFoundException("Could not find PhantomJS executable.");
            }

            var dir = Path.GetDirectoryName(path);

            if (string.IsNullOrEmpty(dir) || !Directory.Exists(dir))
            {
                throw new FileNotFoundException("Could not determin PhantomJS base directory.");
            }

            var fileName = Path.GetFileName(path);
            var savePath = string.Format(@"{0}{1}.{2}", Path.GetTempPath(), Guid.NewGuid(), returnType.ToString().ToLower());

            // If is a local file, we need to adapt the path a bit
            if (File.Exists(url))
            {
                url = string.Format("file:///{0}", Uri.EscapeDataString(url).Replace("%3A", ":").Replace("%5C", "/"));
            }

            var arguments = string.Format(@"--config=config.json scripts/run.js {0} {1}", url, savePath);

            using (var process = new Process())
            {
                process.EnableRaisingEvents = true;

                process.ErrorDataReceived += (sender, e) =>
                {
                    throw new Exception("process.ErrorDataReceived");
                };

                process.StartInfo.WindowStyle      = ProcessWindowStyle.Hidden;
                process.StartInfo.CreateNoWindow   = true;
                process.StartInfo.ErrorDialog      = true;

                process.StartInfo.FileName         = fileName;
                process.StartInfo.Arguments        = arguments;
                process.StartInfo.WorkingDirectory = dir;

                process.Start();
                process.WaitForExit(10000);
            }

            return savePath;
        }
예제 #3
0
 public static string GetFileTypeExtension(FileType fileType)
 {
     switch (fileType)
     {
         case FileType.MP4:
             return ".mp4";
         case FileType.WMV:
             return "wmv";
         case FileType.XML:
             return "xml";
         case FileType.Unknown:
             return null;
         default:
             throw new ApplicationException("Unexpected FileType enum value: " + fileType.ToString());
     }
 }
예제 #4
0
        /// <summary>
        /// New Upload File
        /// </summary>
        /// <param name="ID">Upload ID</param>
        /// <param name="FileID">File ID</param>
        /// <param name="Name">File Name</param>
        /// <param name="FileType">File Type</param>
        /// <param name="Client">TcpClient.</param>
        public UploadFile(int ID, int FileID, string Name, FileType FileType, TcpClient Client)
        {
            this.ID = ID;
            this.FileID = FileID;
            this.Name = Name;
            this.Type = FileType.ToString();
            this.Client = Client;

            if (FileType == FileType.CrashLog)
            {
                Stream = new FileStream(Core.Setting.ApplicationDirectory + "\\CrashLogs\\" + Name, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                Stream.Seek(0, SeekOrigin.Begin);
            }
            else if (FileType == FileType.Logger)
            {
                Stream = new FileStream(Core.Setting.ApplicationDirectory + "\\Logger\\" + Name, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                Stream.Seek(0, SeekOrigin.Begin);
            }

            Core.RCONPlayer.SentToPlayer(new Package(Package.PackageTypes.BeginCreateFile, new List<string> { FileID.ToString(), Name, Stream.Length.ToString() }, Client));
        }
예제 #5
0
        public static void Serialize_SSCTechActivity(SSCTechActivity result, FileType fileType)
        {
            //if (!Directory.Exists(FilePathType.SerData.DirPath()))
            //{
            //    Directory.CreateDirectory(FilePathType.SerData.DirPath());
            //}

            //Stream stream = File.Open(String.Format("{0}{1}{2}.{3}", FilePathType.SerData.DirPath(), AppNEnvConfig.GetFileSeperator, result.SurveyRowID, fileType.ToString()), FileMode.Create);
            //BinaryFormatter bformatter = new BinaryFormatter();
            //bformatter.Serialize(stream, result);
            //stream.Close();

            if (!Directory.Exists(AppNEnvConfig.TechSerData))
            {
                Directory.CreateDirectory(AppNEnvConfig.TechSerData);
            }

            Stream stream = File.Open(String.Format("{0}{1}{2}.{3}", AppNEnvConfig.TechSerData, AppNEnvConfig.GetFileSeperator, result.SurveyRowID, fileType.ToString()), FileMode.Create);
            BinaryFormatter bformatter = new BinaryFormatter();
            bformatter.Serialize(stream, result);
            stream.Close();
        }
예제 #6
0
 /// <summary> 初始化类型文件夹 </summary>
 /// <param name="type"></param>
 private void InitDirectory(FileType type)
 {
     var path = Path.Combine(Contains.BaseDirectory, type.ToString().ToLower());
     if (!Directory.Exists(path))
     {
         //初始化类型文件
         path = Path.Combine(path, GenerateFirstDirectory(), Util.GenerateFileName());
         _directoryCache[type] = path;
         _fileCountCache[type] = 0;
         return;
     }
     var parent = new DirectoryInfo(path);
     var dir = parent.GetDirectories().OrderByDescending(t => t.LastWriteTime).FirstOrDefault();
     //判断二级目录
     if (dir == null || dir.GetDirectories().Length >= Contains.MaxFileCount)
     {
         var count = 1;
         if (dir != null)
         {
             var search = string.Format("d{0}*", Convert.ToString(DateTime.Now.Year, 16));
             count = parent.GetDirectories(search).Length + 1;
         }
         _directoryCache[type] = Path.Combine(path, GenerateFirstDirectory(count), Util.GenerateFileName());
         _fileCountCache[type] = 0;
         return;
     }
     path = dir.FullName;
     dir = dir.GetDirectories().OrderByDescending(t => t.LastWriteTime).FirstOrDefault();
     if (dir == null || dir.GetFiles().Length >= Contains.MaxFileCount)
     {
         _directoryCache[type] = Path.Combine(path, Util.GenerateFileName());
         _fileCountCache[type] = 0;
         return;
     }
     _directoryCache[type] = dir.FullName;
     _fileCountCache[type] = dir.GetFiles().Length;
 }
예제 #7
0
 /// <summary>подготовим файлы карт</summary>
 private string PrepareFile(BusinessGraphicsResourceInfo info, FileType fType)
 {
     //достанем временной индентивикатор для карт, по нему будем ориентироваться новый файл или нет
     ResourceFileProperty file = info.ResourceFileList.FirstOrDefault(f => f.Id.Equals(FileType.mapResource.ToString()));
     //если файла карты нет, значит БГ без карты, возьмем тогда сам xml
     if (file == null)
         file = info.ResourceFileList.FirstOrDefault(f => f.Id.Equals(FileType.xmlResource.ToString()));
     long dtFile = file.ModifiedUtc;
     //информация об оригинальном файле
     ResourceFileProperty oldMapFileName = info.ResourceFileList.FirstOrDefault(f => f.Id.Equals(fType.ToString()));
     //информация о файле который приехал с сервера в качестве ресурса
     string resFileName = GetFileByType(info, fType);
     if (string.IsNullOrEmpty(resFileName) || !File.Exists(resFileName)) return string.Empty;
     //имя файла как он должен называться
     string newFileName = Path.Combine(
         Path.GetDirectoryName(resFileName),
         Path.GetFileNameWithoutExtension(oldMapFileName.ResourceFileName) +
             dtFile.ToString() + "." + GetFileExtension(fType));
     if (!File.Exists(newFileName))
     {
         File.Copy(resFileName, newFileName);
     }
     return newFileName;
 }
예제 #8
0
파일: Branch.cs 프로젝트: jiabailie/Qunar
        /// <summary>
        /// Write the bmp images into number format to judge the threshold.
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="savepath"></param>
        /// <param name="filetype"></param>
        public static void write_Bmp_To_Txt_Batch(string filepath, string savepath, FileType filetype)
        {
            try
            {
                if (filetype != FileType.bmp && filetype != FileType.jpg)
                {
                    throw new Exception("The file type is not image.");
                }

                string inpath = "";
                string outpath = "";
                for (int i = 0; i < (1 << 10); i++)
                {
                    inpath = filepath + "0(" + i.ToString() + ")." + filetype.ToString();
                    outpath = savepath + "0(" + i.ToString() + ")." + FileType.txt.ToString();

                    if (!File.Exists(inpath)) { break; }

                    IO.write_Bmp_To_Avg_Number(inpath, outpath);
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
예제 #9
0
파일: Branch.cs 프로젝트: jiabailie/Qunar
        /// <summary>
        /// Using Threshold to process image and write them into certain position.
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="savepath"></param>
        /// <param name="filetype"></param>
        public static void write_Bmp_To_Bmp_Using_Threshold(string filepath, string savepath, FileType filetype)
        {
            int i = 0;
            int w = 0, h = 0;
            string inpath = "";
            string outpath = "";
            Bitmap bitmap = null;

            try
            {
                if (filetype != FileType.bmp && filetype != FileType.jpg)
                {
                    throw new Exception("The file type is not image.");
                }

                for (i = 0; i < (1 << 10); i++)
                {
                    inpath = filepath + "0(" + i.ToString() + ")." + filetype.ToString();
                    outpath = savepath + "0(" + i.ToString() + ")." + FileType.bmp.ToString();

                    if (!File.Exists(inpath)) { break; }

                    bitmap = Operations.Convert_Jpg2Bmp(inpath);

                    w = bitmap.Width;
                    h = bitmap.Height;

                    // Zoom out the image by certain ratio
                    bitmap = Scaling.Image_Zoom_Out(Config.Image_Scaling_Ratio, bitmap);

                    // Zoom in the image to the original size
                    bitmap = Scaling.Image_Zoom_In(w, h, bitmap);

                    // Do uniformization operation
                    Operations.Uniformization_Bmp(bitmap);

                    // Remove black edges
                    Operations.Generate_White_Edges(bitmap);

#if     Remove_Suspending_Points
                    // Remove suspending points
                    Operations.Remove_Suspending_Points(bitmap);
#endif

#if     Remove_Thin_Vertical_Line
                    // Remove thin vertical lines
                    Operations.Remove_Thin_Vertical_Lines(bitmap);
#endif

                    bitmap.Save(outpath, ImageFormat.Bmp);
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
예제 #10
0
 // ============================================
 // PUBLIC Methods
 // ============================================
 public static string[] GetExtension(FileType type)
 {
     int position = (int) Enum.Parse(typeof(FileType), type.ToString());
     return(Extensions[position]);
 }
예제 #11
0
 // ============================================
 // PRIVATE Methods
 // ============================================
 private static string MakePattern(FileType type)
 {
     return(MakePattern(type.ToString()));
 }
예제 #12
0
		private ContentItem CreateZipActionContentItem(string password, FileType fileType, string filePath, string contentId, string parentId)
		{
			PolicySet[] policySets;
			switch (fileType)
			{
			case FileType.Email:
			case FileType.ZIP:
			case FileType.OutlookMessageFile:
				policySets = CreateContainerPolicySets();
				break;
			default:
				policySets = CreateDocumentPolicySets(password);
				break;
			}

			CustomProperty[] properties = CreateProperties(filePath, contentId);

			return new ContentItem
				{
					ContentType = fileType.ToString(),
					Name = filePath,
					DisplayName = Path.GetFileName(filePath),
					Id = contentId,
					ParentId = parentId,
					PolicySets = policySets,
					Properties = properties
				};
		}
예제 #13
0
파일: Main.cs 프로젝트: shuikeyi/gwtool
        private string GetExtension(FileType type)
        {
            switch (type)
            {
                case FileType.GMAD:
                    return ".gma";

                case FileType.LZMA:
                    return ".7z";

                default:
                    return "." + type.ToString().ToLower();
            }
        }
 private FileContentResult GetData(FileType fileType)
 {
     FileContentResult fr = null;
     ReadDataFromRouteData();
     string folderPrefix = string.Empty;
     switch (fileType.ToString())
     {
         case "js":
             folderPrefix = "Scripts";
             break;
         case "css":
             folderPrefix = "Styles";
             break;
         case "image":
             folderPrefix = "Images";
             break;
     }
     try
     {
         string fileFullPath = Path.Combine(_adminManager.DataPath, "knowledgebase", "portalConfiguration", clientId.ToString(), portalId.ToString(), folderPrefix, fileName);
         System.IO.MemoryStream s = _adminManager.ReadFileStream(fileFullPath);
         byte[] bts = new byte[s.Length];
         s.Read(bts, 0, bts.Length);
         string contentType = Mime.FromExtension(Path.GetExtension(fileFullPath));
         fr = new FileContentResult(bts, contentType);
     }
     catch (IOException ex)
     {
         KBCustomException kbCustExp = KBCustomException.ProcessException(ex, KBOp.LoadContent, KBErrorHandler.GetMethodName(), GeneralResources.IOError,
             new KBExceptionData("fileType", fileType.ToString()), new KBExceptionData("clientId", clientId), new KBExceptionData("portalId", portalId),
             new KBExceptionData("folderPrefix", folderPrefix), new KBExceptionData("fileName", fileName));
         throw kbCustExp;
     }
     catch (Exception ex)
     {
         KBCustomException kbCustExp = KBCustomException.ProcessException(ex, KBOp.LoadContent, KBErrorHandler.GetMethodName(), GeneralResources.GeneralError,
             new KBExceptionData("fileType", fileType.ToString()), new KBExceptionData("clientId", clientId), new KBExceptionData("portalId", portalId),
             new KBExceptionData("folderPrefix", folderPrefix), new KBExceptionData("fileName", fileName));
         throw kbCustExp;
     }
     return fr;
 }
예제 #15
0
파일: locbaml.cs 프로젝트: cozzyy2002/WPF
        /// <summary>
        /// return true if the operation succeeded.
        /// otherwise, return false
        /// </summary>
        internal string CheckAndSetDefault()
        {
            // we validate the options here and also set default
            // if we can

            // Rule #1: One and only one action at a time
            // i.e. Can't parse and generate at the same time
            //      Must do one of them
            if ((ToParse && ToGenerate) ||
                (!ToParse && !ToGenerate))
                return StringLoader.Get("MustChooseOneAction");

            // Rule #2: Must have an input
            if (string.IsNullOrEmpty(Input))
            {
                return StringLoader.Get("InputFileRequired");
            }
            else
            {
                if (!File.Exists(Input))
                {
                    return StringLoader.Get("FileNotFound", Input);
                }

                string extension = Path.GetExtension(Input);

                // Get the input file type.
                if (string.Compare(extension, "." + FileType.BAML.ToString(), true, CultureInfo.InvariantCulture) == 0)
                {
                    InputType = FileType.BAML;
                }
                else if (string.Compare(extension, "." + FileType.RESOURCES.ToString(), true, CultureInfo.InvariantCulture) == 0)
                {
                    InputType = FileType.RESOURCES;
                }
                else if (string.Compare(extension, "." + FileType.DLL.ToString(), true, CultureInfo.InvariantCulture) == 0)
                {
                    InputType = FileType.DLL;
                }
                else if (string.Compare(extension, "." + FileType.EXE.ToString(), true, CultureInfo.InvariantCulture) == 0)
                {
                    InputType = FileType.EXE;
                }
                else
                {
                    return StringLoader.Get("FileTypeNotSupported", extension);
                }
            }

            if (ToGenerate)
            {
                // Rule #3: before generation, we must have Culture string
                if (CultureInfo == null &&  InputType != FileType.BAML)
                {
                    // if we are not generating baml,
                    return StringLoader.Get("CultureNameNeeded", InputType.ToString());
                }

                // Rule #4: before generation, we must have translation file
                if (string.IsNullOrEmpty(Translations))
                {

                    return StringLoader.Get("TranslationNeeded");
                }
                else
                {
                    string extension = Path.GetExtension(Translations);

                    if (!File.Exists(Translations))
                    {
                        return StringLoader.Get("TranslationNotFound", Translations);
                    }
                    else
                    {
                        if (string.Compare(extension, "." + FileType.CSV.ToString(), true, CultureInfo.InvariantCulture) == 0)
                        {
                            TranslationFileType = FileType.CSV;
                        }
                        else
                        {
                            TranslationFileType = FileType.TXT;
                        }
                    }
                }
            }

            // Rule #5: If the output file name is empty, we act accordingly
            if (string.IsNullOrEmpty(Output))
            {
                // Rule #5.1: If it is parse, we default to [input file name].csv
                if (ToParse)
                {
                    string fileName = Path.GetFileNameWithoutExtension(Input);
                    Output = fileName + "." + FileType.CSV.ToString();
                    TranslationFileType = FileType.CSV;
                }
                else
                {
                    // Rule #5.2: If it is generating, and the output can't be empty
                    return StringLoader.Get("OutputDirectoryNeeded");
                }

            }else
            {
                // output isn't null, we will determind the Output file type
                // Rule #6: if it is parsing. It will be .csv or .txt.
                if (ToParse)
                {
                    string fileName;
                    string outputDir;

                    if (Directory.Exists(Output))
                    {
                        // the output is actually a directory name
                        fileName = string.Empty;
                        outputDir = Output;
                    }
                    else
                    {
                        // get the extension
                        fileName = Path.GetFileName(Output);
                        outputDir = Path.GetDirectoryName(Output);
                    }

                    // Rule #6.1: if it is just the output directory
                    // we append the input file name as the output + csv as default
                    if (string.IsNullOrEmpty(fileName))
                    {
                        TranslationFileType = FileType.CSV;
                        Output = outputDir
                               + Path.DirectorySeparatorChar
                               + Path.GetFileName(Input)
                               + "."
                               + TranslationFileType.ToString();
                    }
                    else
                    {
                        // Rule #6.2: if we have file name, check the extension.
                        string extension = Path.GetExtension(Output);

                        // ignore case and invariant culture
                        if (string.Compare(extension, "." + FileType.CSV.ToString(), true, CultureInfo.InvariantCulture) == 0)
                        {
                            TranslationFileType = FileType.CSV;
                        }
                        else
                        {
                            // just consider the output as txt format if it doesn't have .csv extension
                            TranslationFileType = FileType.TXT;
                        }
                    }
                }
                else
                {
                    // it is to generate. And Output should point to the directory name.
                    if (!Directory.Exists(Output))
                        return StringLoader.Get("OutputDirectoryError", Output);
                }
            }

            // Rule #7: if the input assembly path is not null
            if (AssemblyPaths != null && AssemblyPaths.Count > 0)
            {
                Assemblies = new Assembly[AssemblyPaths.Count];
                for (int i = 0; i < Assemblies.Length; i++)
                {
                    string errorMsg = null;
                    try
                    {
                        // load the assembly
                        Assemblies[i] = Assembly.LoadFrom((string) AssemblyPaths[i]);
                    }
                    catch (ArgumentException argumentError)
                    {
                        errorMsg = argumentError.Message;
                    }
                    catch (BadImageFormatException formatError)
                    {
                        errorMsg = formatError.Message;
                    }
                    catch (FileNotFoundException fileError)
                    {
                        errorMsg = fileError.Message;
                    }
                    catch (PathTooLongException pathError)
                    {
                        errorMsg = pathError.Message;
                    }
                    catch (SecurityException securityError)
                    {

                        errorMsg = securityError.Message;
                    }

                    if (errorMsg != null)
                    {
                        return errorMsg; // return error message when loading this assembly
                    }
                }
            }

            // if we come to this point, we are all fine, return null error message
            return null;
        }
예제 #16
0
파일: Branch.cs 프로젝트: jiabailie/Qunar
        public static void write_Bmp_To_Txt_Using_Threshold(string filepath, string savepath, FileType filetype)
        {
            int i = 0;
            string inpath = "";
            string outpath = "";
            Bitmap bitmap = null;

            try
            {
                if (filetype != FileType.bmp && filetype != FileType.jpg)
                {
                    throw new Exception("The file type is not image.");
                }

                for (i = 0; i < (1 << 10); i++)
                {
                    inpath = filepath + "0(" + i.ToString() + ")." + filetype.ToString();
                    outpath = savepath + "0(" + i.ToString() + ")." + FileType.txt.ToString();

                    if (!File.Exists(inpath)) { break; }

                    bitmap = Operations.Convert_Jpg2Bmp(inpath);

                    // Do uniformization operation
                    Operations.Uniformization_Bmp(bitmap);

                    // Remove black edges
                    Operations.Generate_White_Edges(bitmap);

#if     Remove_Suspending_Points
                    // Remove suspending points
                    Operations.Remove_Suspending_Points(bitmap);
#endif
                    IO.write_Bmp_To_Avg_Number(bitmap, outpath);
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
예제 #17
0
파일: Fn.cs 프로젝트: hifans/capdata
 public static bool DownloadFile(string fileLink, string filename, FileType ft)
 {
     //string strFileDir = System.Configuration.ConfigurationSettings.AppSettings["fileDir"].Trim('\\')+"\\"+ft.ToString()+"\\";
     string strFileDir = Fn.GetConfValue("fileDir").Trim('\\') + "\\" + ft.ToString() + "\\";
     return DownloadFile(fileLink, filename, strFileDir);
 }
예제 #18
0
		private Image GetImageByFileType(FileType type)
		{
			string tmpName = string.Format("{0}_{1}_32.ico", (int)type, type.ToString());

			return Icons.FileType.GetIcon(tmpName);
		}
예제 #19
0
파일: Branch.cs 프로젝트: jiabailie/Qunar
        public static void write_Long_Black_Lines_Into_Files(string filepath, string savepath, FileType filetype)
        {
            int i = 0;
            string inpath = "";
            string outpath = "";
            Bitmap bitmap = null;

            try
            {
                if (filetype != FileType.bmp && filetype != FileType.jpg)
                {
                    throw new Exception("The file type is not image.");
                }

                for (i = 0; i < (1 << 10); i++)
                {
                    inpath = filepath + "0(" + i.ToString() + ")." + filetype.ToString();
                    outpath = savepath + "0(" + i.ToString() + ")." + FileType.bmp.ToString();

                    if (!File.Exists(inpath)) { break; }

                    bitmap = Operations.Convert_Jpg2Bmp(inpath);

                    // Do uniformization operation
                    Operations.Uniformization_Bmp(bitmap);

                    // Remove black edges
                    Operations.Generate_White_Edges(bitmap);

#if     Remove_Suspending_Points
                    // Remove suspending points
                    Operations.Remove_Suspending_Points(bitmap);
#endif

                    // Find the long black line
                    iLine iline1 = QunarFeatureOperations.Find_Long_Connected_Lines(bitmap.Width - 1, 0, -1, bitmap);
                    iLine iline2 = QunarFeatureOperations.Find_Long_Connected_Lines(0, bitmap.Width - 1, 1, bitmap);

                    bitmap.Save(outpath, ImageFormat.Bmp);
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
예제 #20
0
        private void GetRequest(FileType fileType, int surveyRowID = 0)
        {
            //COUpdate.InstallUpdateSyncWithInfo(this);

            if (!COUpdate.InstallUpdateSyncWithInfo(this))
            {
                using (BackgroundWorker worker = new BackgroundWorker())
                {
                    worker.DoWork += (s, e) =>
                    {
                        RequestInfo = RepOperation.GetNextRequest(fileType, surveyRowID);
                    };

                    worker.RunWorkerCompleted += (s, e) =>
                    {
                        if (e.Error != null)
                        {
                            IsBusy = false;
                            SSCLog.HandleError(e.Error);
                        }
                        else
                        {
                            if (RequestInfo == null)
                            {
                                MsgUtility.ShowMessageBox(string.Format("No {0} Task found.", fileType.ToString()), MessageType.Info);
                            }
                            else
                            {
                                InitializeViewModel(true);
                            }
                            //IsBusy = false;
                            IsBusy = IsSourceGettingDownloaded;
                        }
                    };

                    IsBusy = true;

                    worker.RunWorkerAsync();
                }
            }
            else
            {
                //COUpdate.RestartApp();
                COUpdate.UpdateApp(this);
            }
        }
예제 #21
0
            public string CreateFile(string content, FileType type, string folder = null)
            {
                string fileName;
                switch (type)
                {
                    case FileType.MarkdownToc:
                        fileName = MarkdownTocName;
                        break;
                    case FileType.YamlToc:
                        fileName = YamlTocName;
                        break;
                    case FileType.MarkdownContent:
                        fileName = Path.GetRandomFileName() + ".md";
                        break;
                    default:
                        throw new NotSupportedException(type.ToString());
                }

                fileName = Path.Combine(folder ?? string.Empty, fileName);

                var filePath = Path.Combine(_rootDir, fileName);
                var dir = Path.GetDirectoryName(filePath);
                if (!string.IsNullOrEmpty(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                File.WriteAllText(filePath, content);
                return fileName.Replace('\\', '/');
            }
예제 #22
0
 /// <summary>
 ///     Get the name of the file given the file type.
 /// </summary>
 /// <param name="fileType">The type of the file.</param>
 /// <returns>The name of the cvs file.</returns>
 public String GetFilename (FileType fileType) {
     switch (fileType) {
         case (FileType.Entries):{
             return Entry.FILE_NAME;
         }
         case (FileType.Repository):{
             return Repository.FILE_NAME;
         }
         case (FileType.Root):{
             return Root.FILE_NAME;
         }
         case (FileType.Tag):{
             return Tag.FILE_NAME;
         }
         default:{
             StringBuilder msg = new StringBuilder();
             msg.Append("Unknown file type specified.");
             msg.Append("fileType=[").Append(fileType.ToString()).Append("]");
             throw new UnsupportedFileTypeException (msg.ToString());
         }
     }
 }
예제 #23
0
        public async Task<IList<FileContent>> UploadFile(IEnumerable<HttpPostedFileBase> files, FileType fileType)
        {
            var rootFilePath = ConfigurationManager.AppSettings["RootFilePath"];
            var newSubPath = Path.Combine(fileType.ToString(), DateTime.Now.Year.ToString(),
                DateTime.Now.Month.ToString());
            var directoryPath = Path.Combine(rootFilePath, newSubPath);

            IList<FileContent> savedFiles = new List<FileContent>();
            try
            {
                if (!Directory.Exists(directoryPath))
                    Directory.CreateDirectory(directoryPath);

                string fileName, fileExtension, newFileName;

                foreach (var file in files)
                {
                    if (file != null && file.ContentLength > 0 && !string.IsNullOrEmpty(file.FileName))
                    {
                        fileName = Path.GetFileName(file.FileName);
                        fileExtension = Path.GetExtension(fileName);
                        newFileName = string.Format("{0}-{1}{2}", Path.GetFileNameWithoutExtension(fileName),
                            Guid.NewGuid(), fileExtension);

                        savedFiles.Add(new FileContent
                        {
                            FileNm = fileName,
                            FilePath = Path.Combine(newSubPath, newFileName)
                        });

                        await Task.Run(() => file.SaveAs(Path.Combine(directoryPath, newFileName)));
                    }
                }

                return savedFiles;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #24
0
		/// <summary>
		/// Add files using the multipart content-type
		/// </summary>
		/// <param name="fileName">The file name and extension</param>
		/// <param name="fileType">The file type</param>
		/// <param name="folderId">The id of the folder</param>
		/// <param name="description">The description of the file</param>
		/// <param name="source">The source of the original file</param>
		/// <param name="data">The data contained in the file being uploaded</param>
		/// <returns>Returns the file Id associated with the uploaded file</returns>
		public string AddLibraryFilesMultipart(string fileName, FileType fileType, string folderId, string description, FileSource source, byte[] data)
		{
            if (string.IsNullOrEmpty(fileName))
            {
                throw new IllegalArgumentException(CTCT.Resources.Errors.FileNameNull);
            }

            var extension = Path.GetExtension(fileName).ToLowerInvariant();
            string[] fileTypes = new string[5] { ".jpeg", ".jpg", ".gif", ".png", ".pdf" };

            if (!((IList<string>)fileTypes).Contains(extension))
            {
                throw new IllegalArgumentException(CTCT.Resources.Errors.FileTypeInvalid);
            }

            if (string.IsNullOrEmpty(folderId) || string.IsNullOrEmpty(description))
            {
                throw new IllegalArgumentException(CTCT.Resources.Errors.FieldNull);
            }

            if (data == null)
            {
                throw new IllegalArgumentException(CTCT.Resources.Errors.FileNull);
            }

			string result = null;
			string url = String.Concat(Settings.Endpoints.Default.BaseUrl, Settings.Endpoints.Default.MyLibraryFiles);
			byte[] content = MultipartBuilder.CreateMultipartContent(fileName, data, null, fileType.ToString(), folderId, description, source.ToString());
            RawApiResponse response = RestClient.PostMultipart(url, UserServiceContext.AccessToken, UserServiceContext.ApiKey, content);

            if (response.IsError)
            {
                throw new CtctException(response.GetErrorMessage());
            }

			if(!response.IsError && response.StatusCode == System.Net.HttpStatusCode.Accepted)
			{
				string location = response.Headers["Location"];
				int idStart = location.LastIndexOf("/") + 1;
				result = location.Substring(idStart);
			}

			return result;
		}