Exemple #1
0
        public static void backupSSF()
        {
            //verifica se existe o diretório, caso não exista será criado
            string dirAnteriores = Library.appDir + "\\ssf\\anteriores\\";
            if (!System.IO.Directory.Exists(dirAnteriores))
            {
                System.IO.Directory.CreateDirectory(dirAnteriores);
            }

            //verifica se existe o diretório, caso não exista será criado
            string dirZipados = Library.appDir + "\\ssf\\zipados\\";
            if (!System.IO.Directory.Exists(dirZipados))
            {
                System.IO.Directory.CreateDirectory(dirZipados);
            }

            //backup ssf
            System.IO.DirectoryInfo dirSSF = new System.IO.DirectoryInfo(appDir + "\\ssf");

            string[] filePaths = System.IO.Directory.GetFiles(dirSSF.ToString(), "*.ssf");

            ZipFile zip =
                new ZipFile(dirZipados + DateTime.Now.Day + DateTime.Now.Month + DateTime.Now.Year +
                    DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + ".zip");
            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
            zip.AddFiles(filePaths);
            zip.Save();

            //move todos os arquivos
            foreach (string file in filePaths)
                System.IO.File.Move(file, dirAnteriores + System.IO.Path.GetFileName(file));
        }
Exemple #2
0
        public static EngineType getEngineType(string dir)
        {
            if (dir == null)
            {
                return(EngineType.None);
            }

            while (dir.Length >= 0)
            {
                if (System.IO.Directory.Exists(dir + "\\" + ".git"))
                {
                    return(EngineType.Git);
                }
                if (System.IO.Directory.Exists(dir + "\\" + ".svn"))
                {
                    return(EngineType.Svn);
                }

                System.IO.DirectoryInfo di = System.IO.Directory.GetParent(dir);
                if (di == null)
                {
                    return(EngineType.None);
                }

                string s = di.ToString();
                if (s.Equals(dir))
                {
                    return(EngineType.None);
                }
                dir = s;
            }
            return(EngineType.None);
        }
Exemple #3
0
        static public void CreateBackup(string arg)
        {
            directoryInfo = new System.IO.DirectoryInfo(Program.currentFilePath);
            System.IO.FileInfo[] finfo = directoryInfo.GetFiles();
            //Backup vezeichniss
            System.IO.Directory.CreateDirectory(directoryInfo + "\\bfk.exe Backup " + arg);

            var backupDir = new System.IO.DirectoryInfo(directoryInfo + "\\bfk.exe Backup " + arg);



            foreach (var s in finfo)
            {
                try
                {
                    string destFile = System.IO.Path.Combine(directoryInfo.ToString(), s.FullName);


                    //Exception
                    System.IO.File.Copy(s.Name, destFile, true);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }
Exemple #4
0
        private void vLCDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog Folder = new FolderBrowserDialog();

            Folder.ShowDialog();
            VLC_Dir = new System.IO.DirectoryInfo(Folder.SelectedPath);
            Console.WriteLine(VLC_Dir.ToString());
        }
Exemple #5
0
        internal static string GetScriptContent(string fileName, MigrationScriptType type)
        {
            var rootDir = new System.IO.DirectoryInfo(System.AppContext.BaseDirectory);

            rootDir = new System.IO.DirectoryInfo(rootDir.Parent.Parent.Parent.FullName);


            string spContent = string.Empty;
            string directory = @"\Migrations";

            switch (type)
            {
            case MigrationScriptType.DataUpdate:
                directory += @"\SeedData";
                break;

            case MigrationScriptType.Function:
                directory += @"\Functions";
                break;

            case MigrationScriptType.StoredProcedure:
                directory += @"\StoredProcedures";
                break;

            case MigrationScriptType.Table:
                directory += @"\Tables";
                break;

            case MigrationScriptType.View:
                directory += @"\Views";
                break;
            }

            if (System.IO.File.Exists(rootDir.ToString() + directory + @"\" + fileName) == false)
            {
                directory = directory.Replace(@"\dotNetApi.Migrations\Scripts", "\\");
            }

            spContent = System.IO.File.ReadAllText(rootDir.ToString() + directory + @"/" + fileName);

            return(spContent);
        }
Exemple #6
0
        static StackObject *ToString_16(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.IO.DirectoryInfo instance_of_this_method = (System.IO.DirectoryInfo) typeof(System.IO.DirectoryInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.ToString();

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Exemple #7
0
        public static void Main()
        {
            string[]           args = Environment.GetCommandLineArgs();
            LastUserConnection usr  = new LastUserConnection();

            if (SingleInstance <App> .InitializeAsFirstInstance(Unique))
            {
                if (usr.getNomUtil() == null)
                {
                    System.Windows.Forms.Application.Run(new Login.Form1());
                }
                if (usr.getNomUtil() != null)
                {
                    if (args.Length > 1)
                    {
                        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Environment.CurrentDirectory);
                        Envoie_De_Fichiers      f  = new Envoie_De_Fichiers(di.ToString(), args[1]);
                        f.Show();
                    }
                    var application = new App();
                    application.InitializeComponent();
                    application.Run();
                    // Allow single instance code to perform cleanup operations
                    SingleInstance <App> .Cleanup();
                }
            }
            else
            {
                if (usr.getNomUtil() == null)
                {
                    System.Windows.Forms.Application.Run(new Login.Form1());
                }
                if (usr.getNomUtil() != null)
                {
                    if (args.Length > 1)
                    {
                        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Environment.CurrentDirectory);
                        System.Windows.Forms.Application.Run(new Envoie_De_Fichiers(di.ToString(), args[1]));
                    }
                }
            }
        }
Exemple #8
0
        static void Main()
        {
            LastUserConnection usr = new LastUserConnection();

            if (usr.getNomUtil() == null)
            {
                Application.Run(new Login.Form1());
            }
            if (usr.getNomUtil() != null)
            {
                string[] args = Environment.GetCommandLineArgs();
                if (args.Length > 1)
                {
                    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Environment.CurrentDirectory);
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Envoie_De_Fichiers(di.ToString(), args[1]));
                }
            }
        }
Exemple #9
0
        private JsonClassGenerator Prepare()
        {
            if (edtJson.Text == string.Empty)
            {
                MessageBox.Show(this, "Please insert json data", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                edtJson.Focus();
                return(null);
            }

            if (edtMainClass.Text == string.Empty)
            {
                MessageBox.Show(this, "Please specify a main class name.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(null);
            }

            var gen = new JsonClassGenerator();

            gen.Example                 = edtJson.Text;
            gen.InternalVisibility      = false;
            gen.CodeWriter              = (ICodeWriter)cmbLanguage.SelectedItem;
            gen.ExplicitDeserialization = false;
            gen.Namespace               = "Finda";
            gen.NoHelperClass           = false;
            gen.SecondaryNamespace      = null;
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Application.StartupPath + @"\Data");
            if (!di.Exists)
            {
                di.Create();
            }
            gen.TargetFolder               = di.ToString();
            gen.UseProperties              = true;
            gen.MainClass                  = edtMainClass.Text;
            gen.UsePascalCase              = false;
            gen.UseNestedClasses           = false;
            gen.ApplyObfuscationAttributes = false;
            gen.SingleFile                 = true;
            gen.ExamplesInDocumentation    = true;
            return(gen);
        }
        /// <summary>
        /// Generates an HTML view for a directory.
        /// </summary>
        public virtual Task GenerateContentAsync(HttpContext context, IEnumerable <IFileInfo> contents)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (contents == null)
            {
                throw new ArgumentNullException("contents");
            }
            context.Response.ContentType = "text/html; charset=utf-8";
            if (HttpMethods.IsHead(context.Request.Method))
            {
                return(Task.CompletedTask);
            }
            PathString    pathString    = context.Request.PathBase + context.Request.Path;
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.AppendFormat("<!DOCTYPE html>\r\n<html lang=\"{0}\">", CurrentCulture.TwoLetterISOLanguageName);
            stringBuilder.AppendFormat("\r\n<head>\r\n  <title>{0} {1}</title>", HtmlEncode("Index of"), HtmlEncode(pathString.Value));
            stringBuilder.Append("\r\n  <style>\r\n    body {\r\n        font-family: \"Segoe UI\", \"Segoe WP\", \"Helvetica Neue\", 'RobotoRegular', sans-serif;\r\n        font-size: 14px;}\r\n    header h1 {\r\n        font-family: \"Segoe UI Light\", \"Helvetica Neue\", 'RobotoLight', \"Segoe UI\", \"Segoe WP\", sans-serif;\r\n        font-size: 28px;\r\n        font-weight: 100;\r\n        margin-top: 5px;\r\n        margin-bottom: 0px;}\r\n    #index {\r\n        border-collapse: separate; \r\n        border-spacing: 0; \r\n        margin: 0 0 20px; }\r\n    #index th {\r\n        vertical-align: bottom;\r\n        padding: 10px 5px 5px 5px;\r\n        font-weight: 400;\r\n        color: #a0a0a0;\r\n        text-align: center; }\r\n    #index td { padding: 3px 10px; }\r\n    #index th, #index td {\r\n        border-right: 1px #ddd solid;\r\n        border-bottom: 1px #ddd solid;\r\n        border-left: 1px transparent solid;\r\n        border-top: 1px transparent solid;\r\n        box-sizing: border-box; }\r\n    #index th:last-child, #index td:last-child {\r\n        border-right: 1px transparent solid; }\r\n    #index td.length, td.modified { text-align:right; }\r\n    a { color:#1ba1e2;text-decoration:none; }\r\n    a:hover { color:#13709e;text-decoration:underline; }\r\n  </style>\r\n</head>\r\n<body>\r\n  <section id=\"main\">");
            stringBuilder.AppendFormat("\r\n    <header><h1><a href=\"/\">Home</a>&nbsp;&nbsp;<a href='{0}'>Settings</a>&nbsp;&nbsp;", LoggerSettings.SettingsPath);
            string text = "/";

            string[] array = pathString.Value.Split(new char[1]
            {
                '/'
            }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string text2 in array)
            {
                text = text + text2 + "/";
                if (text == pathString.Value)
                {
                    stringBuilder.AppendFormat("<a href='javascript:;'>{0}</a>", HtmlEncode(text2));
                }
                else
                {
                    stringBuilder.AppendFormat("<a href=\"{0}\">{1}/</a>", HtmlEncode(text), HtmlEncode(text2));
                }
            }
            stringBuilder.AppendFormat(CurrentCulture, "</h1></header>\r\n    <table id=\"index\" summary=\"{0}\">\r\n    <thead>\r\n      <tr><th abbr=\"{1}\">{1}</th><th abbr=\"{2}\">{2}</th><th abbr=\"{3}\">{4}</th></tr>\r\n    </thead>\r\n    <tbody>",
                                       HtmlEncode("The list of files in the given directory.  Column headers are listed in the first row."),
                                       HtmlEncode("Name"),
                                       HtmlEncode("Size"),
                                       HtmlEncode("Modified"),
                                       HtmlEncode("Last Modified"));
            DateTimeOffset lastModified;

            foreach (IFileInfo item in from info in contents
                     where info.IsDirectory
                     select info)
            {
                StringBuilder stringBuilder2 = stringBuilder;
                string        arg            = HtmlEncode(item.Name);
                lastModified = item.LastModified;
                long?len = new System.IO.DirectoryInfo(item.PhysicalPath)
                           .GetFiles()
                           .Where(x => x.Name != LoggerSettings.LogJsonFileName)
                           .Sum(x => x.Length);
                if (len <= 0)
                {
                    len = null;
                }
                stringBuilder2.AppendFormat("<tr class=\"directory\"><td class=\"name\"><a href=\"./{0}/\">{0}/</a></td><td>{1}</td><td class=\"modified\">{2}</td></tr>",
                                            arg, HtmlEncode(len?.ToString("n0", CurrentCulture)), HtmlEncode(lastModified.ToString(CurrentCulture)));
            }
            foreach (IFileInfo item2 in from info in contents
                     where !info.IsDirectory
                     select info)
            {
                if (item2.Name == LoggerSettings.LogJsonFileName)
                {
                    continue;
                }
                StringBuilder stringBuilder3 = stringBuilder;
                string        arg2           = HtmlEncode(item2.Name);
                string        arg3           = HtmlEncode(item2.Length.ToString("n0", CurrentCulture));
                string        arg4           = HtmlEncode(item2.PhysicalPath);
                lastModified = item2.LastModified;
                stringBuilder3.AppendFormat("\r\n      <tr class=\"file\">\r\n        <td class=\"name\"><a href=\"./{0}\" title=\"{2}\">{0}</a></td>\r\n        <td class=\"length\">{1}</td>\r\n        <td class=\"modified\">{3}</td>\r\n      </tr>",
                                            arg2, arg3, arg4, HtmlEncode(lastModified.ToString(CurrentCulture)));
            }
            stringBuilder.Append("\r\n    </tbody>\r\n    </table>\r\n  </section>\r\n</body>\r\n</html>");
            string s = stringBuilder.ToString();

            byte[] bytes = Encoding.UTF8.GetBytes(s);
            context.Response.ContentLength = bytes.Length;
            return(context.Response.Body.WriteAsync(bytes, 0, bytes.Length));
        }
Exemple #11
0
        private void CreateFromBundlerFile(string configFile)
        {
            string text = System.IO.File.ReadAllText(configFile);

            string[] lines = text.Split('\r');


            int numCameras = int.Parse(lines[1].Split(' ')[0]);
            int numPoints  = int.Parse(lines[1].Split(' ')[1]);

            for (int i = 0; i < numCameras; i++)
            {
                //Extract the focal length and the radial distrortion cooefficients
                string[] line1split  = lines[2 + i * 5].Split(' ');
                float    focalLength = float.Parse(line1split[0]);
                float    k1          = float.Parse(line1split[1]);
                float    k2          = float.Parse(line1split[2]);

                //Camera Rotation matrix
                //m1, m2, m3
                //m4, m5, m6
                //m7, m8, m9

                string[] line2split = lines[3 + i * 5].Split(' ');
                float    m1         = float.Parse(line2split[0]);
                float    m2         = float.Parse(line2split[1]);
                float    m3         = float.Parse(line2split[2]);

                string[] line3split = lines[4 + i * 5].Split(' ');
                float    m4         = float.Parse(line3split[0]);
                float    m5         = float.Parse(line3split[1]);
                float    m6         = float.Parse(line3split[2]);

                string[] line4split = lines[5 + i * 5].Split(' ');
                float    m7         = float.Parse(line4split[0]);
                float    m8         = float.Parse(line4split[1]);
                float    m9         = float.Parse(line4split[2]);

                //Camera Translation Matrix
                string[] line5split = lines[6 + i * 5].Split(' ');
                float    t1         = float.Parse(line5split[0]);
                float    t2         = float.Parse(line5split[1]);
                float    t3         = float.Parse(line5split[2]);

                //Create the new camera and store:
                Matrix           RotationMatrix    = new Matrix(m1, m2, m3, 0, m4, m5, m6, 0, m7, m8, m9, 0, 0, 0, 0, 1);
                Vector3          TranslationVector = new Vector3(t1, t2, t3);
                RegisteredCamera thisCamera        = new RegisteredCamera(focalLength, k1, k2, RotationMatrix, TranslationVector, 480, 640);
                //thisCamera.TrackedPoints.Add(new TrackedImagePoint(320, 240));
                //thisCamera.TrackedPoints.Add(new TrackedImagePoint(320, -240));
                //thisCamera.TrackedPoints.Add(new TrackedImagePoint(-320, 240));
                //thisCamera.TrackedPoints.Add(new TrackedImagePoint(-320, -240));
                //thisCamera.TrackedPoints.Add(new TrackedImagePoint(0, 0));

                //Add some matched image points, to check the calibration...
                System.IO.DirectoryInfo thisDIR = System.IO.Directory.GetParent(configFile);
                System.IO.DirectoryInfo upDIR   = System.IO.Directory.GetParent(thisDIR.ToString());

                string sDIR    = upDIR.ToString();
                string keyText = System.IO.File.ReadAllText(sDIR + "\\" + i + ".key");

                string[] keyLines = keyText.Split('\r');

                for (int y = 0; y < 20; y++)
                {
                    string[] matchcoords = keyLines[1 + (y * 8)].Split(' ');
                    float    matchY      = float.Parse(matchcoords[0]);
                    float    matchX      = float.Parse(matchcoords[1]);
                    thisCamera.TrackedPoints.Add(new TrackedImagePoint(matchX, matchY));
                }

                Cameras.Add(thisCamera);
            }

            int           startLine     = 1 + 6 + (numCameras - 1) * 5;
            CameraMatches cameraMatches = new CameraMatches();

            //Get the model points
            for (int i = 0; i < numPoints; i++)
            {
                string[] linesplit = lines[startLine + i * 3].Split(' ');
                float    x         = float.Parse(linesplit[0]);
                float    y         = float.Parse(linesplit[1]);
                float    z         = float.Parse(linesplit[2]);
                Point3D  thisPoint = new Point3D(x, y, z);
                cameraMatches.points.Add(thisPoint);
            }

            modelPoints = cameraMatches;
        }
        /** From T.g return a list of File objects that
         *  name files ANTLR will emit from T.g.
         */
        public virtual IList <string> GetGeneratedFileList()
        {
            List <FileInfo> files = new List <FileInfo>();

            System.IO.DirectoryInfo outputDir = tool.GetOutputDirectory(grammarFileName);
            if (outputDir.Name.Equals("."))
            {
                outputDir = outputDir.Parent;
            }
            else if (outputDir.Name.IndexOf(' ') >= 0)
            { // has spaces?
                string escSpaces = outputDir.ToString().Replace(
                    " ",
                    "\\ ");
                outputDir = new System.IO.DirectoryInfo(escSpaces);
            }
            // add generated recognizer; e.g., TParser.java
            string recognizer =
                generator.GetRecognizerFileName(grammar.name, grammar.type);

            files.Add(new FileInfo(System.IO.Path.Combine(outputDir.FullName, recognizer)));
            // add output vocab file; e.g., T.tokens. This is always generated to
            // the base output directory, which will be just . if there is no -o option
            //
            files.Add(new FileInfo(System.IO.Path.Combine(tool.OutputDirectory, generator.VocabFileName)));
            // are we generating a .h file?
            StringTemplate headerExtST = null;
            StringTemplate extST       = generator.Templates.GetInstanceOf("codeFileExtension");

            if (generator.Templates.IsDefined("headerFile"))
            {
                headerExtST = generator.Templates.GetInstanceOf("headerFileExtension");
                string suffix   = Grammar.grammarTypeToFileNameSuffix[(int)grammar.type];
                string fileName = grammar.name + suffix + headerExtST.Render();
                files.Add(new FileInfo(System.IO.Path.Combine(outputDir.FullName, fileName)));
            }
            if (grammar.type == GrammarType.Combined)
            {
                // add autogenerated lexer; e.g., TLexer.java TLexer.h TLexer.tokens
                // don't add T__.g (just a temp file)
                string suffix = Grammar.grammarTypeToFileNameSuffix[(int)GrammarType.Lexer];
                string lexer  = grammar.name + suffix + extST.Render();
                files.Add(new FileInfo(System.IO.Path.Combine(outputDir.FullName, lexer)));

                // TLexer.h
                if (headerExtST != null)
                {
                    string header = grammar.name + suffix + headerExtST.Render();
                    files.Add(new FileInfo(System.IO.Path.Combine(outputDir.FullName, header)));
                }
                // for combined, don't generate TLexer.tokens
            }

            // handle generated files for imported grammars
            IList <Grammar> imports =
                grammar.composite.GetDelegates(grammar.composite.RootGrammar);

            foreach (Grammar g in imports)
            {
                outputDir = tool.GetOutputDirectory(g.FileName);
                string fname = GroomQualifiedFileName(outputDir.ToString(), g.GetRecognizerName() + extST.Render());
                files.Add(new FileInfo(fname));
            }

            if (files.Count == 0)
            {
                return(null);
            }

            return(files.Select(info => info.FullName).ToArray());
        }
        public JsonResult UploadedFile()
        {
            // Set the methods local variables...
            bool   isFileUploadedSuccessfully = true;
            string petFileNameGUID            = string.Empty;

            // UPLOADING ALL THE INVOICE FILE(S)...
            try
            {
                // Checks each file request...
                foreach (string fileName in Request.Files)
                {
                    // Gets the uploaded file(s)...
                    HttpPostedFileBase requestFiles = Request.Files[fileName];
                    petFileNameGUID = Guid.NewGuid().ToString();
                    if (requestFiles != null && requestFiles.ContentLength > 0)
                    {
                        // Gets the base directory information using the Server.MapPath...
                        var    baseDirectoryInfo = new System.IO.DirectoryInfo(string.Format("{0}Images\\uploaded", Server.MapPath(@"\")));
                        string pathString        = System.IO.Path.Combine(baseDirectoryInfo.ToString(), "imagepath", ApplicationSession.GlobalParameters.SelectedPetName);
                        var    petFileName       = System.IO.Path.GetFileName(requestFiles.FileName);

                        // Checks if the directory path already exists, else create the directory...
                        bool isExists = System.IO.Directory.Exists(pathString);
                        if (!isExists)
                        {
                            System.IO.Directory.CreateDirectory(pathString);
                        }

                        // Save the uploaded file to the location path of the selected petname...
                        var locationPathToSave = string.Format("{0}\\{1}", pathString, petFileNameGUID);
                        requestFiles.SaveAs(locationPathToSave);

                        // Checks if the list of ApplicationSession.GlobalParameters.PetClaimServiceList has value...
                        if (ApplicationSession.GlobalParameters.PetClaimServiceList != null)
                        {
                            // Gets the existing list on the ApplicationSession.GlobalParameters.PetClaimServiceList and save it into the temporary PetClaimServiceList...
                            this.PetClaimServiceList = ApplicationSession.GlobalParameters.PetClaimServiceList;
                        }

                        // Add new list on the temporary PetClaimServiceList...
                        PetClaimServiceList.Add(new PetClaimServiceViewModels
                        {
                            FileNameGUID = ApplicationSession.GlobalParameters.SelectedPetFileNameGUID = petFileNameGUID,
                            FileName     = ApplicationSession.GlobalParameters.SelectedPetFileName = petFileName,
                            FilePath     = ApplicationSession.GlobalParameters.SelectedPetFilePath = locationPathToSave,
                        });

                        // Now save and set the new list of ApplicationSession.GlobalParameters.PetClaimServiceList...
                        ApplicationSession.GlobalParameters.PetClaimServiceList = this.PetClaimServiceList;
                    }
                }
            }
            catch (Exception)
            {
                // Set the flag value to false if any unhandled exception occourred...
                isFileUploadedSuccessfully = false;
            }
            // Return the file uploading message result...
            if (isFileUploadedSuccessfully)
            {
                return(Json(new { Message = petFileNameGUID }));
            }
            else
            {
                return(Json(new { Message = "Error in saving file" }));
            }
        }
Exemple #14
0
        private string GetTrimmedLocalPath(double width)
        {
            try
            {
                string        filename  = System.IO.Path.GetFileName(Path);
                string        directory = System.IO.Path.GetDirectoryName(Path);
                FormattedText formatted;
                bool          widthOK      = false;
                bool          changedWidth = false;
                string        placeholder  = string.Empty;
                if (!directory.EndsWith("\\"))
                {
                    directory += "\\";
                }
                do
                {
                    TextBlock textBlock = this;

                    Typeface typeface = new Typeface(textBlock.FontFamily,
                                                     textBlock.FontStyle,
                                                     textBlock.FontWeight,
                                                     textBlock.FontStretch);

                    // FormattedText is used to measure the whole width of the text held up by TextBlock container.
                    formatted = new FormattedText(
                        "{0}{1}{2}".FormatWith(directory, placeholder, filename),
                        System.Threading.Thread.CurrentThread.CurrentCulture,
                        textBlock.FlowDirection,
                        typeface,
                        textBlock.FontSize,
                        textBlock.Foreground);

                    //formatted = new FormattedText(
                    //    "{0}{1}{2}".FormatWith(directory, placeholder, filename),
                    //    CultureInfo.CurrentCulture,
                    //    FlowDirection.LeftToRight,
                    //    FontFamily.GetTypefaces().First(),
                    //    FontSize,
                    //    Foreground
                    //    );

                    widthOK = formatted.Width < width;

                    if (!widthOK)
                    {
                        changedWidth = true;
                        System.IO.DirectoryInfo directoryInfo = System.IO.Directory.GetParent(directory);
                        if (null == directoryInfo)
                        {
                            if (filename.Length == 0)
                            {
                                return("...");
                            }
                            filename = filename.Substring(1);
                        }
                        else
                        {
                            directory = directoryInfo.ToString();
                        }
                        if (directory.EndsWith("\\"))
                        {
                            placeholder = "...\\";
                        }
                        else
                        {
                            placeholder = "\\...\\";
                        }
                    }
                } while (!widthOK);

                if (!changedWidth)
                {
                    return(Path);
                }
                SetValue(IsTextTrimmedProperty, changedWidth);
                return("{0}{1}{2}".FormatWith(directory, placeholder, filename));
            }
            catch (Exception ex)
            {
                NLogger.LogHelper.UILogger.Debug("Failed", ex);
                return(string.Empty);
            }
        }
Exemple #15
0
        protected internal async void Listen()  // прослушивание входящих подключений
        {
            System.Net.Sockets.TcpListener tcpListener = System.Net.Sockets.TcpListener.Create(Form1.myForm.LocalHost.intPortChat);
            try
            {
                tcpListener.Start();
                while (true)
                {
                    using (var tcpClient = await tcpListener.AcceptTcpClientAsync())
                    {
                        string id = Guid.NewGuid().ToString();   // id connection
                        // Form1.myForm._richTextBoxEchoAdd( DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": " + "Client has connected " + id);

                        using (var networkStream = tcpClient.GetStream())
                        {
                            var buffer    = new byte[4096];
                            var byteCount = await networkStream.ReadAsync(buffer, 0, buffer.Length);

                            var message = encryptDecrypt.DecryptRijndael(Encoding.UTF8.GetString(buffer, 0, byteCount), salt);
                            try { cts.Cancel(); } catch { }
                            try
                            {
                                if (Form1.myForm.RemoteHost.HostName == null)
                                {
                                    try { Form1.myForm.RemoteHost.HostName = System.Net.Dns.GetHostEntry(message.Split('(')[0].Trim()); } catch { }
                                    try { Form1.myForm.RemoteHost.ipAddress = System.Net.IPAddress.Parse((message.Split('(')[1]).Split(')')[0].Trim()); } catch { }
                                    try { Form1.myForm.RemoteHost.intPortGetFile = Convert.ToInt32(message.Split(':')[2].Trim()); } catch { }
                                    Form1.myForm.RemoteHost.SetInfo();
                                }
                                else if (Form1.myForm.RemoteHost.HostName != null)
                                {
                                    string currentIP = (message.Split('(')[1]).Split(')')[0].Trim();
                                    if (currentIP != Form1.myForm.RemoteHost.ipAddress.ToString())
                                    {
                                        try { Form1.myForm.RemoteHost.HostName = System.Net.Dns.GetHostEntry(message.Split('(')[0].Trim()); } catch { }
                                        try { Form1.myForm.RemoteHost.ipAddress = System.Net.IPAddress.Parse((message.Split('(')[1]).Split(')')[0].Trim()); } catch { }
                                        try { Form1.myForm.RemoteHost.intPortGetFile = Convert.ToInt32(message.Split(':')[2].Trim()); } catch { }
                                        Form1.myForm.RemoteHost.SetInfo();
                                    }
                                }

                                // Form1.myForm._richTextBoxEchoAdd(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": " + message);

                                buffer = System.Text.Encoding.UTF8.GetBytes(encryptDecrypt.EncryptRijndael(message, salt));

                                //byte[] msg = System.Text.Encoding.UTF8.GetBytes(encryptDecrypt.EncryptRijndael("Hi!", salt));
                                await networkStream.WriteAsync(buffer, 0, buffer.Length);

                                buffer    = new byte[4096];
                                byteCount = await networkStream.ReadAsync(buffer, 0, buffer.Length);

                                message = encryptDecrypt.DecryptRijndael(Encoding.UTF8.GetString(buffer, 0, byteCount), salt);
                                //Write all info into log
                                //Form1.myForm._richTextBoxEchoAdd(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": " + Form1.myForm.RemoteHost.UserName + ": " + message);

                                doAction         = new DoAction();
                                doAction.message = Form1.myForm.RemoteHost.UserName + " " + message;
                                doAction.CheckGotMessage();
                                if (doAction.ActionSelected == "NAME")
                                {
                                    buffer = System.Text.Encoding.UTF8.GetBytes(encryptDecrypt.EncryptRijndael(doAction.answer, salt));
                                    await networkStream.WriteAsync(buffer, 0, buffer.Length);
                                }
                                else if (doAction.ActionSelected == "TAKE")
                                {
                                    buffer = System.Text.Encoding.UTF8.GetBytes(encryptDecrypt.EncryptRijndael(doAction.answer, salt));
                                    // await networkStream.WriteAsync(buffer, 0, buffer.Length);
                                }
                                else if (doAction.ActionSelected == "UPDATESERVER")
                                {
                                    Random rnd           = new Random();
                                    string sActionFolder = rnd.Next().ToString();
                                    System.IO.DirectoryInfo UpdateFolderFullPath = new System.IO.DirectoryInfo(System.Windows.Forms.Application.StartupPath + "\\" + sActionFolder);

                                    try { UpdateFolderFullPath.Create(); } catch { }
                                    Form1.myForm.strFolderUpdates = UpdateFolderFullPath.ToString();
                                    try
                                    {
                                        using (Microsoft.Win32.RegistryKey EvUserKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(myRegKey))
                                        {
                                            EvUserKey.SetValue("UPDATESERVERFOLDER", encryptDecrypt.EncryptStringToBase64Text(Form1.myForm.strFolderUpdates, btsMess1, btsMess2), Microsoft.Win32.RegistryValueKind.String);
                                        }
                                    }
                                    catch { }

                                    string sPathCmd = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "myCltSvr.cmd");
                                    doAction.UpdateServerMakecmd(sPathCmd, sActionFolder);

                                    buffer = System.Text.Encoding.UTF8.GetBytes(encryptDecrypt.EncryptRijndael(Form1.myForm.LocalHost.UserName + ": Ready to get a file on the port: " + Form1.myForm.LocalHost.intPortGetFile, salt));
                                    await networkStream.WriteAsync(buffer, 0, buffer.Length);

                                    SendGetFile getFile = new SendGetFile();
                                    getFile.GetFile(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, sActionFolder), Form1.myForm.LocalHost.intPortGetFile);

                                    doAction.RunProcess(sPathCmd);
                                }
                                else if (doAction.ActionSelected == "GET") //Prepare to get file by Server
                                {
                                    SendGetFile getFile = new SendGetFile();
                                    buffer = System.Text.Encoding.UTF8.GetBytes(encryptDecrypt.EncryptRijndael(Form1.myForm.LocalHost.UserName + ": Ready to get a file on the port: " + Form1.myForm.LocalHost.intPortGetFile, salt));
                                    await networkStream.WriteAsync(buffer, 0, buffer.Length);  //Добавить cancelationtoken

                                    getFile.GetFile(Form1.myForm.strFolderGet, Form1.myForm.LocalHost.intPortGetFile);
                                }
                                else if (doAction.ActionSelected.Length > 0)
                                {
                                    cts = new System.Threading.CancellationTokenSource();
                                    bool messageIsCommand = false;
                                    foreach (string str in actionWord) //
                                    {
                                        if (doAction.ActionSelected == str)
                                        {
                                            messageIsCommand = true;
                                            break;
                                        }
                                    }
                                    if (messageIsCommand != true && Form1.myForm.controlled != "uncontrolcheck")
                                    {
                                        System.Threading.Tasks.Task.Run(() => MakeDelayForHide(10000), cts.Token); //отмена задачи если будет   cts.Cancel
                                    }

                                    buffer = System.Text.Encoding.UTF8.GetBytes(encryptDecrypt.EncryptRijndael(doAction.message, salt));
                                    await networkStream.WriteAsync(buffer, 0, buffer.Length);
                                }
                                else if (doAction.ActionSelected == "")
                                {
                                    buffer = System.Text.Encoding.UTF8.GetBytes(encryptDecrypt.EncryptRijndael(Form1.myForm.RemoteHost.UserName + ": said  -= " + message.ToUpper(), salt));
                                    await networkStream.WriteAsync(buffer, 0, buffer.Length);
                                }
                                else
                                {
                                    buffer = System.Text.Encoding.UTF8.GetBytes(encryptDecrypt.EncryptRijndael(Form1.myForm.RemoteHost.UserName + ": said nothing", salt));
                                    await networkStream.WriteAsync(buffer, 0, buffer.Length);
                                }
                                await networkStream.WriteAsync(buffer, 0, buffer.Length);
                            }
                            catch// (Exception expt)
                            {
                                //   Form1.myForm._AppendTextToFile(Form1.myForm.FileLog, DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": Listen().tcpClient.GetStream(): " + expt.ToString());
                            }
                        }
                    }
                }
            }
            catch (Exception expt)
            { Form1.myForm._AppendTextToFile(Form1.myForm.FileLog, DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": Listen(): " + expt.Message); }
            finally { tcpListener.Stop(); }
        }
Exemple #16
0
        //this will add new keys, then deactive the others
        private static void option1_create_key()
        {
            MySQL_Interface MySQL = new MySQL_Interface();

            string Errors = "";
            //System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
            System.Console.Write("Creating Keys..." + Environment.NewLine);
            System.Security.Cryptography.RSACryptoServiceProvider provider = new System.Security.Cryptography.RSACryptoServiceProvider(); //make keys in c#
            System.Console.Write("Keys Created." + Environment.NewLine);

            System.Console.WriteLine("Connecting to database and deactivating past keys...");
            if (MySQL.mysql_clear_old_key(my_username,my_password,my_database))
            {
                Console.WriteLine("Old Keys Deactivated");
            }
            else
            {
                Errors += "Error disabling old keys" + "|" + "Run command 'database-maintance'" + "|";
                Console.WriteLine("Error disabling old keys");
                Console.WriteLine("Manually deactivte old keys or empty table, im not a english major spelling is for computers, and awake people");
            }

            System.Console.WriteLine("Inserting new key, and activating...");
            int time = Convert.ToInt32((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds); // get unix time stamp for easy use
            string mod = BitConverter.ToString(provider.ExportParameters(false).Modulus).Replace("-", string.Empty).ToLower(); //public key parts of ssl
            string expon = BitConverter.ToString(provider.ExportParameters(false).Exponent).Replace("-", string.Empty);

            //Public key parts get put in database to be used in web end, the rest of the key is saved to the hard drive so that just a local app can decrypt

            string mysql_command = "INSERT INTO `" + my_database + "`.`" + my_db_table +  "` (`index` ,`modulus` ,`exponent`,`active`,`date_added`) VALUES (NULL , '" + mod + "', '" + expon + "',  '1',  '" + time + "')";
            if (MySQL.mysql_nonquery(my_username, my_password, my_database, mysql_command))
            {
                //Save local key pairs
                string index_of = MySQL.mysql_select_cell(my_username, my_password, my_database, "SELECT * FROM `" + my_database + "`.`" + my_db_table +  "` WHERE `modulus`='" + mod + "' AND `date_added`='" + time + "'", "index");
                System.IO.DirectoryInfo Working_dir = new System.IO.DirectoryInfo(System.Environment.CurrentDirectory);
                string working_dir = Working_dir.ToString();
                local_store_key(working_dir, index_of, provider);
            }
            else
            {
                Console.Write("Error putting key in database" + Environment.NewLine);
            }
        }
Exemple #17
0
        //this will write the keys to the hard drive
        private static string local_store_key(string passed_data_store, string keyID, RSACryptoServiceProvider passed_provider)
        {
            System.IO.DirectoryInfo Working_dir = new System.IO.DirectoryInfo(passed_data_store);
            System.IO.DirectoryInfo Keys_Dir = new System.IO.DirectoryInfo(System.IO.Path.Combine(Working_dir.ToString(), "keys"));
            if (Working_dir.Exists)
            {
                //Directory is good for storage
                if (!Keys_Dir.Exists)
                {
                    try
                    {
                        Keys_Dir.Create();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                        return e.ToString();
                    }
                }
            }
            else
            {
                try
                {
                    Working_dir.Create();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                    return e.ToString();
                }
                //No keys directory
                try
                {
                    Keys_Dir.Create();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                    return e.ToString();
                }
            }
            Working_dir = null;
            //Keys Dir should work now
            System.IO.FileInfo Key_file = new System.IO.FileInfo(Keys_Dir.ToString() + System.IO.Path.DirectorySeparatorChar + keyID + ".key");
            using (System.IO.StreamWriter sw = Key_file.CreateText())
            {
                sw.Write(BitConverter.ToString(passed_provider.ExportCspBlob(true)));
                Console.WriteLine("Key Stored in 'keys'");
                //Console.WriteLine(BitConverter.ToString(passed_provider.ExportCspBlob(true)));
                //Console.WriteLine();
                //Console.WriteLine(BitConverter.ToString(passed_provider.ExportCspBlob(true)).Replace("-", string.Empty));

            }
            return "yes";
        }
Exemple #18
0
        private void btnCnvert_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtSingleFilePath.Text) && string.IsNullOrEmpty(this.txtMultFilePath.Text))
            {
                MessageBox.Show("You need to enter a file path!", "Error: No File Path");
                return;
            }

            string singleFilePath = this.txtSingleFilePath.Text, multFileDir = this.txtMultFilePath.Text;
            string pathsSelected = "Single File Path:\t\t" + singleFilePath + "\nMultiple File Directory:\t" + multFileDir;

            //GhostscriptSharp.GhostscriptSettings gss = new GhostscriptSharp.GhostscriptSettings();
            //gss.Device = GhostscriptSharp.Settings.GhostscriptDevices.jpeg;
            //gss.Page.AllPages = true;
            //gss.Resolution = new Size(500, 500);
            //gss.Size = new GhostscriptSharp.Settings.GhostscriptPageSize() { Native = GhostscriptSharp.Settings.GhostscriptPageSizes.a4, Manual = new Size(500, 500) };

            Ghostscript.NET.GhostscriptVersionInfo gv = Ghostscript.NET.GhostscriptVersionInfo.GetLastInstalledVersion(Ghostscript.NET.GhostscriptLicense.GPL | Ghostscript.NET.GhostscriptLicense.AFPL, Ghostscript.NET.GhostscriptLicense.GPL);

            MessageBox.Show(pathsSelected);

            if (!string.IsNullOrEmpty(singleFilePath))
            {
                if (!System.IO.File.Exists(singleFilePath))
                {
                    MessageBox.Show("The file you entered does not exist. Verify that it does and try again.\nYour entry:\t" + singleFilePath, "Single File does not exist");
                }
                else if (!string.Equals(System.IO.Path.GetExtension(singleFilePath), ".pdf"))
                {
                    MessageBox.Show("The file you entered is not a PDF. Verify that it is and try again.\nYour entry:\t" + singleFilePath, "Single File not PDF");
                }
                else
                {
                    Label lblWaitMsg = new Label();
                    lblWaitMsg.Location = new Point(13, 13);
                    lblWaitMsg.Text     = "Please wait while the Image Conversion loads..";
                    lblWaitMsg.AutoSize = true;

                    System.Windows.Forms.Form frmWait = new Form();
                    frmWait.Text          = "Loading...";
                    frmWait.UseWaitCursor = true;
                    frmWait.Controls.Add(lblWaitMsg);
                    frmWait.AutoSize = true;

                    frmWait.Show();
                    ConvertToJPEG(singleFilePath);
                    frmWait.Close();
                    MessageBox.Show("Single File conversion sucess!");
                }
            }

            if (!string.IsNullOrEmpty(multFileDir))
            {
                if (!System.IO.Directory.Exists(multFileDir))
                {
                    MessageBox.Show("The Directory you entered does not exist. Verify that it does and try again.\nYour entry:\t" + multFileDir, "File Directory does not exist");
                    return;
                }
                else
                {
                    System.IO.DirectoryInfo multiDirInfo = new System.IO.DirectoryInfo(multFileDir);
                    System.IO.FileInfo[]    pdfFiles     = multiDirInfo.GetFiles("*.pdf");

                    if (pdfFiles.Count() <= 0)
                    {
                        MessageBox.Show("The Directory you entered does not have any PDF files. Verify that it does and try again.\nYour entry:\t" + multFileDir, "File Directory conatins no PDFs");
                    }
                    else
                    {
                        Label lblWaitMsg = new Label();
                        lblWaitMsg.Location = new Point(13, 13);
                        lblWaitMsg.Text     = "Please wait while the Image Conversion loads..";
                        lblWaitMsg.AutoSize = true;

                        System.Windows.Forms.Form frmWait = new Form();
                        frmWait.Text          = "Loading...";
                        frmWait.UseWaitCursor = true;
                        frmWait.Controls.Add(lblWaitMsg);
                        frmWait.AutoSize = true;

                        frmWait.Show();

                        string multiFiles = "";

                        for (int counter = 0; counter < pdfFiles.Count(); counter++)
                        {
                            multiFiles = multiFiles + pdfFiles[counter].ToString() + "\n";
                            ConvertToJPEG(multiDirInfo.ToString() + "\\" + pdfFiles[counter].ToString());
                        }

                        frmWait.Close();

                        MessageBox.Show("Multiple File sucess!\n" + multiFiles);
                    }
                }
            }

            return;
        }
Exemple #19
0
        internal static bool CheckWriteAccessAndCreate(this System.IO.DirectoryInfo directory, out string errorMessage)
        {
            System.IO.DirectoryInfo directoryToCheck = directory.Parent;
            if (!directoryToCheck.Exists)
            {
                errorMessage = "Parent folder doesn't exist.";
                return(false);
            }

            errorMessage = "";

            string whoIsTrying = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

            // Gets all access security types for directory
            System.Security.AccessControl.DirectorySecurity security;
            try {
                security = directoryToCheck.GetAccessControl(System.Security.AccessControl.AccessControlSections.All);
            }
            catch (System.Security.AccessControl.PrivilegeNotHeldException e) {
                errorMessage = e.Message;
                Tracer.Log($"\"SeSecurityPrivilege\" error: {whoIsTrying} doesn't have privileges to check folder's security ({directoryToCheck})", e);
                return(false);
            }

            // Collects all access rules for that security types
            System.Security.AccessControl.AuthorizationRuleCollection rules = security.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));

            // Iterate each access rule
            for (var i = 0; i < rules.Count; i++)
            {
                var rule = rules[i];

                // Do we match the identity ?
                if (rule.IdentityReference.Value.Equals(whoIsTrying, System.StringComparison.CurrentCultureIgnoreCase))
                {
                    var fsAccessRule = rule as System.Security.AccessControl.FileSystemAccessRule; // cast to check 4 access rights
                    var hasAccessOrNotBordelDeMerde = (fsAccessRule.FileSystemRights & System.Security.AccessControl.FileSystemRights.WriteData) > 0 &&
                                                      fsAccessRule.AccessControlType != System.Security.AccessControl.AccessControlType.Deny;

                    if (!hasAccessOrNotBordelDeMerde)
                    {
                        errorMessage = $"\"{whoIsTrying}\" does not have write access to {directoryToCheck}";
                        return(false);
                    }

                    try {
                        directory.Create();
                    }
                    catch (System.Exception e) {
                        errorMessage = e.Message;
                        Tracer.Log($@"Exception in Config.CheckCreate for this folder: ""{directory.ToString()}""", e);
                        return(false);
                    }
                }
            }

            return(true);
        }