Beispiel #1
0
        /* Runs in the background on load event.
         * Checks if database file exists at users data directory, if so whether they're
         * the same size, and downloads the latest one if either return false */
        public static void UpdateLocalDatabase()
        {
            Program.log.Info("Checking for database updates");

            if (UpdateLocalDatabaseFiles(UrlOpenDirectories, "open-directories.txt"))
            {
                using (var client = new WebClient()) { client.DownloadFile(new Uri(UrlOpenDirectories), $"{LocalExtensions.pathData}open-directories.txt"); }
                Program.log.Info("open-directories.txt updated");
            }
            MainForm.DataOpenDirectories.AddRange(File.ReadAllLines($"{LocalExtensions.pathData}open-directories.txt"));

            if (UpdateLocalDatabaseFiles(UrlOpenFiles, "open-files.json"))
            {
                using (var client = new WebClient()) { client.DownloadFile(new Uri(UrlOpenFiles), $"{LocalExtensions.pathData}open-files.json"); }
                Program.log.Info("open-files.json updated");
            }

            // Retrieve database items, skipping the first line (contains the meta info)
            foreach (var item in File.ReadAllLines($"{LocalExtensions.pathData}open-files.json").Skip(1))
            {
                if (TextExtensions.IsValidJSON(item))
                {
                    MainForm.FilesOpenDatabase.Add(JsonConvert.DeserializeObject <WebFile>(item));
                }
            }

            MainForm.DatabaseInfo = File.ReadLines($"{LocalExtensions.pathData}open-files.json").First(); // Gets first line in database which contains info
        }
Beispiel #2
0
        public static Assembly Compile(CompilerInputData compilerInputData)
        {
            if (string.IsNullOrWhiteSpace(compilerInputData.CSharpCode))
            {
                throw new Exception("CSharpCode parameter can`t be null or empty.");
            }
            string assemblyName;

            if (string.IsNullOrWhiteSpace(compilerInputData.AssemblyName))
            {
                assemblyName = "CompiledAssembly_" + TextExtensions.Generate(10);
            }
            else
            {
                assemblyName = compilerInputData.AssemblyName;
            }
            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(compilerInputData.CSharpCode);
            var        references = GetMetadataReferences(compilerInputData.ReferencedAssemblies);

            OptimizationLevel optLevel = OptimizationLevel.Release;

#if DEBUG
            //optLevel = OptimizationLevel.Debug;
#endif
            CSharpCompilation compilation = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: new[] { syntaxTree },
                references: references,
                options: new CSharpCompilationOptions(
                    OutputKind.DynamicallyLinkedLibrary,
                    optimizationLevel: optLevel
                    )

                );

            using (var ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);

                if (!result.Success)
                {
                    IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                                                                                 diagnostic.IsWarningAsError ||
                                                                                 diagnostic.Severity == DiagnosticSeverity.Error);

                    string compileErrors = "";
                    foreach (Diagnostic diagnostic in failures)
                    {
                        compileErrors += $"\n  *{diagnostic.Id}: {diagnostic.GetMessage()};";
                    }
                    throw new CodeGenException("Exception while trying to compile script." + compileErrors);
                }
                else
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    Assembly assembly = Assembly.Load(ms.ToArray());
                    return(assembly);
                }
            }
        }
        /// <summary>
        /// Создает словарь с названиями команд cli и соответствующими им методы.
        /// </summary>
        Dictionary <string, ResolvedCmdInfo> CreateReflectionDict()
        {
            var cmdNameAndMethod = new Dictionary <string, ResolvedCmdInfo>();

            foreach (MethodInfo item in GetType().GetMethods())
            {
                CmdInfoAttribute attr = item.GetCustomAttribute(typeof(CmdInfoAttribute)) as CmdInfoAttribute;
                if (attr != null)
                {
                    var name       = attr?.CmdName ?? TextExtensions.ToUnderscoreCase(item.Name);
                    var newCmdInfo = new ResolvedCmdInfo()
                    {
                        CmdName            = name,
                        Description        = attr.Description,
                        MethodInfo         = item,
                        OriginalMethodName = item.Name
                    };
                    cmdNameAndMethod.Add(
                        name,
                        newCmdInfo)
                    ;
                }
            }
            return(cmdNameAndMethod);
        }
        public IList <ForeignExchangeRateModel> ToForeignExchangeRateModels(ForeignExchangeRateDto foreignExchangeRateDto, string date)
        {
            if (foreignExchangeRateDto == null || ListExtensions.IsNullOrEmpty(foreignExchangeRateDto.TargetCurrencies))
            {
                return(new List <ForeignExchangeRateModel>());
            }

            var dateAsInt = GetDateAsInt(foreignExchangeRateDto.PublicationDate);

            if (dateAsInt.ToString() != date)
            {
                return(new List <ForeignExchangeRateModel>());
            }

            var rates = new List <ForeignExchangeRateDto> {
                foreignExchangeRateDto
            };

            return(rates.SelectMany(rate => rate.TargetCurrencies, (r, c) => new ForeignExchangeRateModel {
                Id = Guid.NewGuid(),
                Date = dateAsInt,
                BaseCurrency = TextExtensions.ToEnglishUpper(r.BaseCurrency),
                TargetCurrency = TextExtensions.ToEnglishUpper(c.TargetCurrency),
                InverseRate = ConvertExtensions.ToDecimal(c.InverseRate),
                PublicationDate = r.PublicationDate
            }).ToList());
        }
        /// <summary>
        /// Кроме как для удобного просмотра карты всех апи этот метод ни для чего не служит.
        /// </summary>
        public string AsString()
        {
            StringBuilder res = new StringBuilder();

            foreach (var item in _longNameAndInfo)
            {
                string newStr = item.Key;
                if (_longNameAndMethod.ContainsKey(item.Key))
                {
                    newStr += "(";
                    bool isFirst = true;
                    foreach (var parameter in _longNameAndMethod[item.Key].Parameters)
                    {
                        if (!isFirst)
                        {
                            newStr += ", ";
                        }
                        isFirst = false;
                        newStr += parameter.ParamType.Name + "  "
                                  + TextExtensions.ToUnderscoreCase(parameter.ParamName);
                    }
                    newStr += ")";
                }
                newStr += ";";
                if (item.Value.Description != null)
                {
                    newStr += $"  /*{item.Value.Description}*/";
                }
                res.AppendLine(newStr);
            }
            return(res.ToString());
        }
Beispiel #6
0
        public void ShowFiles(List <WebFile> dataFiles)
        {
            EnableSearchControls(false);

            var stopWatch = new Stopwatch();

            Program.log.Info("Searching files started");
            imageSearchFiles.Image = Properties.Resources.loader;
            BackGroundWorker.RunWorkAsync <List <WebFile> >(() => Query.Search(dataFiles, textBoxSearchFiles.Text, SelectedFilesSort), (data) =>
            {
                if (tabSearch.InvokeRequired)
                {
                    var b = new loadFilesCallBack(ShowFiles);
                    Invoke(b, new object[] { dataFiles });
                }
                else
                {
                    dataGridFiles.Rows.Clear();

                    comboBoxFilterFiles.Items.Clear(); comboBoxFilterFiles.Items.Add("Any");

                    stopWatch.Start();

                    foreach (var jsonData in data)
                    {
                        if (SelectedFilesType.Contains(jsonData.Type) && jsonData.Host.Contains(SelectedFilesHost))
                        {
                            dataGridFiles.Rows.Add(jsonData.Type, jsonData.Name, TextExtensions.BytesToString(jsonData.Size), TextExtensions.GetTimeAgo(jsonData.DateUploaded), jsonData.Host, jsonData.URL);
                            if (!(comboBoxFilterFiles.Items.Contains(jsonData.Host)))
                            {
                                comboBoxFilterFiles.Items.Add(jsonData.Host);
                            }
                        }
                    }

                    stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed;
                    labelResultsInfo.Text         = TextExtensions.GetFormattedNumber(dataGridFiles.Rows.Count.ToString()) + " / " + TextExtensions.GetFormattedNumber(dataFiles.Count.ToString()) + " Files (" + String.Format("{0:0.000}", ts.TotalSeconds) + " Seconds)"; stopWatch.Reset();

                    tab.SelectedTab = CurrentTab;

                    comboBoxFilterFiles.DropDownWidth = ControlExtensions.DropDownWidth(comboBoxFilterFiles);

                    imageSearchFiles.Image = Properties.Resources.magnify_orange;

                    if (dataGridFiles.Rows.Count == 0)
                    {
                        labelNoResultsFound.Visible = true;
                    }
                    else
                    {
                        labelNoResultsFound.Visible = false;
                    }

                    EnableSearchControls(true);

                    Program.log.Info("Successfully returned search results");
                }
            });
        }
Beispiel #7
0
 string ToCurrentNotation(string inputStr)
 {
     if (_underscoreNotationEnabled)
     {
         return(TextExtensions.ToUnderscoreCase(inputStr));
     }
     return(inputStr);
 }
Beispiel #8
0
        private void infoDirectory_Click(object sender, EventArgs e)
        {
            // Open file parent directory in default web browser
            Process browser = new Process();

            browser.StartInfo.UseShellExecute = true;
            browser.StartInfo.FileName        = TextExtensions.GetParentUriString(new Uri(currentFile.URL)).Remove(TextExtensions.GetParentUriString(new Uri(currentFile.URL)).Length - 1);;
            browser.Start();
        }
Beispiel #9
0
        private void btnViewDirectory_ClickButtonArea(object Sender, MouseEventArgs e)
        {
            // Open parent directory of file in default web browser
            Process browser = new Process();

            browser.StartInfo.UseShellExecute = true;
            browser.StartInfo.FileName        = TextExtensions.GetParentUriString(new Uri(currentFile.URL)).Remove(TextExtensions.GetParentUriString(new Uri(currentFile.URL)).Length - 1);;
            browser.Start();
        }
Beispiel #10
0
        public void Compare_StringArray()
        {
            const string stringValues = "[a,b,c,d,e,f,g,h,i,j]";

            CompareMultipleRuns(
                "TextExtensions.FromCsvFields", () => TextExtensions.FromCsvFields(stringValues.Split(',')),
                "SCU.Parse<string[]>", () => TypeSerializer.DeserializeFromString <string[]>(stringValues)
                );
        }
Beispiel #11
0
        private void infoDirectory_Click(object sender, EventArgs e)
        {
            Uri     uri        = new Uri(currentFile.URL);
            string  parentName = TextExtensions.GetParentUriString(uri).Remove(TextExtensions.GetParentUriString(uri).Length - 1);
            Process browser    = new Process();

            browser.StartInfo.UseShellExecute = true;
            browser.StartInfo.FileName        = parentName;
            browser.Start();
        }
Beispiel #12
0
        /// <summary>
        /// Show details/info for a WebFile
        /// </summary>
        /// <param name="File">WebFile object</param>
        /// <param name="createNewInstance">Whether to create a new instance</param>
        public void ShowFileDetails(WebFile File, bool createNewInstance = true)
        {
            Program.log.Info("Showing file details dialog : " + File.URL);

            if (createNewInstance)
            {
                FrmFileDetails = new FileDetails();
            }

            FrmFileDetails.currentFile       = File;
            FrmFileDetails.infoFileName.Text = File.Name;
            FrmFileDetails.infoName.Text     = File.Name;
            FrmFileDetails.infoReferrer.Text = File.Host;
            FrmFileDetails.infoType.Text     = File.Type;
            FrmFileDetails.infoFileURL.Text  = Uri.UnescapeDataString(File.URL);

            // Builds parts of the URL into a better presented string, simply replaces '/' with '>' and no filename
            var url         = new Uri(File.URL);
            var directories = new StringBuilder();

            if (!File.URL.StartsWith(LocalExtensions.userDownloadsDirectory))
            {
                directories.Append(File.Host);
            }
            else
            {
                FrmFileDetails.infoReferrer.Text = "Local";
            }                                                                                                                                                        // Appends the Host at the start if not Local, else it will be named 'Local'
            foreach (string path in url.LocalPath.Split('/', '\\'))
            {
                if (!Path.HasExtension(path))
                {
                    directories.Append(path + "> ");
                }
            }
            FrmFileDetails.infoDirectory.Text = directories.ToString();

            FrmFileDetails.infoSize.Text = TextExtensions.BytesToString(File.Size);
            FrmFileDetails.infoAge.Text  = TextExtensions.GetTimeAgo(File.DateUploaded);

            FrmFileDetails.Dock = DockStyle.Fill;
            if (!createNewInstance)
            {
                FrmFileDetails.CheckFileEvents();
            }
            if (createNewInstance)
            {
                tabBlank.Controls.Clear(); tabBlank.Controls.Add(FrmFileDetails);
            }
            tab.SelectedTab = tabBlank;

            Program.log.Info("Successfully loaded file details dialog");
        }
Beispiel #13
0
        /// <summary>
        /// Get database stats
        /// </summary>
        /// <returns></returns>
        public static DateTime GetLastUpdateDate()
        {
            DateTime updateDate = DateTime.MinValue;

            if (TextExtensions.IsValidJSON(MainForm.DatabaseInfo))
            {
                var dataJsonInfo = JsonConvert.DeserializeObject <DatabaseInfo>(MainForm.DatabaseInfo);
                updateDate = dataJsonInfo.LastUpdated;
            }

            return(updateDate);
        }
        /// <summary>
        /// Ищем свойства-категории. Все методы из типа свойства будут добавленны в reflection map с префиксом в виде имени свойства (учитывая погружение).
        /// </summary>
        /// <param name="t">Исследуемый тип, не путать с InspectedType, ведь с погружением в его поля это будет их тип, соответственно.</param>
        /// <param name="funcToGetLocalInstanceFromGlobal">Делегат для получения объекта с типом t из InspectedType.</param>
        void inspectCategoryProps(string prefix, string realNamePrefix, Type t, Func <object, object> funcToGetLocalInstanceFromGlobal)
        {
            foreach (var item in t.GetProperties())
            {
                var attr = item.GetCustomAttribute(typeof(CategoryProp_ReflectionMapAttribute)) as CategoryProp_ReflectionMapAttribute;
                if (attr != null)
                {
                    var newInfo = new Info_ReflectionMap()
                    {
                        DisplayName = prefix + (attr.DisplayName ?? TextExtensions.ToUnderscoreCase(item.Name)),
                        RealName    = realNamePrefix + item.Name,
                        Description = attr.Description
                    };

                    _longNameAndInfo.Add(
                        prefix + newInfo.DisplayName,
                        newInfo
                        );

                    var categoryGetter = item.GetMethod;
                    Func <object, object> new_funcToGetLocalInstanceFromGlobal = (globalInst) =>
                    {
                        var parentInst = funcToGetLocalInstanceFromGlobal(globalInst);
                        var res        = categoryGetter.Invoke(parentInst, new object[0]);
                        return(res);
                    };

                    var newPrefix         = prefix + newInfo.DisplayName + _splitter;
                    var newRealNamePrefix = realNamePrefix + newInfo.RealName + ".";
                    inspectMetods(
                        newPrefix,
                        newRealNamePrefix,
                        item.PropertyType,
                        new_funcToGetLocalInstanceFromGlobal
                        );

                    inspectSimpleProps(
                        newPrefix,
                        newRealNamePrefix,
                        item.PropertyType,
                        new_funcToGetLocalInstanceFromGlobal
                        );

                    inspectCategoryProps(
                        newPrefix,
                        newRealNamePrefix,
                        item.PropertyType,
                        new_funcToGetLocalInstanceFromGlobal
                        );
                }
            }
        }
        private void Spider_FetchCompleted(object Sender, FetchCompleteEventArgs args)
        {
            var senador = new Lib.Senado.Leg.Senador()
            {
                CodigoSenador = ConversionHelper.ToInt(args.Link.Parts[3], 0),
            };

            var hObj = args.GetHObject();

            var dl_dd = hObj["dd"].ToArray();

            senador.NomeCivil     = dl_dd[0].Trim();
            senador.Nascimento    = dl_dd[1].Trim();
            senador.Naturalidade  = TextExtensions.RemoveExcessiveWhitespaces(dl_dd[2]);
            senador.LocalGabinete = dl_dd[3].Trim();

            // funcionários
            var funcionarios = new List <Lib.Senado.Leg.FuncionarioGabinete>();
            var todosTrs     = hObj["tr"];

            foreach (var linha in todosTrs)
            {
                var tds = linha["td"];
                if (tds.IsEmpty()) // é header da tabela
                {
                    continue;
                }

                var id   = ConversionHelper.ToInt(tds[0]["a"].GetHrefValue().Split('=')[1], 0);
                var func = new Lib.Senado.Leg.FuncionarioGabinete()
                {
                    Senador           = senador.CodigoSenador,
                    CodigoFuncionario = id,
                    Nome       = tds[0]["span"].GetValue(),
                    Funcao     = tds[1].GetValue(),
                    NomeFuncao = tds[2].GetValue(),
                };

                if (funcionarios.Any(o => o.CodigoFuncionario == id))
                {
                    continue;
                }

                funcionarios.Add(func);
            }
            senador.Gabinete = funcionarios.ToArray();

            Senadores.Add(senador);
        }
Beispiel #16
0
        string SaveFileToTempDirectory(Stream stream)
        {
            if (!Directory.Exists(TempDirPath))
            {
                Directory.CreateDirectory(TempDirPath);
            }
            var resName  = TextExtensions.Generate(10);
            var filePath = Path.Combine(TempDirPath, resName);

            using (var fileStream = File.Create(filePath))
            {
                stream.Seek(0, SeekOrigin.Begin);
                stream.CopyTo(fileStream);
            }
            return(filePath);
        }
Beispiel #17
0
        /*************************************************************************/
        /* Home Tab                                                              */
        /*************************************************************************/

        /// <summary>
        /// Get database info located on the first line of the file
        /// </summary>
        public void GetDatabaseInfo()
        {
            Program.log.Info("Getting latest database information");

            long totalSize = 0;

            try
            {
                // Total size of all files in database

                Program.log.Info("Getting absolute total size of all files");

                foreach (var jsonData in FilesOpenDatabase)
                {
                    totalSize += jsonData.Size;
                }

                labelDatabaseStats.Text = String.Format(labelDatabaseStats.Text, TextExtensions.GetFormattedNumber(FilesOpenDatabase.Count.ToString()), TextExtensions.BytesToString(totalSize), TextExtensions.GetFormattedNumber(DataOpenDirectories.Count.ToString()));

                Program.log.Info("Total size of all files successful");
            }
            catch (Exception ex)
            {
                labelDatabaseStats.Text = String.Format(labelDatabaseStats.Text, TextExtensions.GetFormattedNumber(FilesOpenDatabase.Count.ToString()), TextExtensions.BytesToString(totalSize), TextExtensions.GetFormattedNumber(DataOpenDirectories.Count.ToString()));
                Program.log.Error("Unable to get absolute total size of all files", ex);
            }

            try
            {
                // Get database stats

                if (TextExtensions.IsValidJSON(DatabaseInfo))
                {
                    Program.log.Info("Getting latest database update date");
                    var dataJsonInfo = JsonConvert.DeserializeObject <DatabaseInfo>(DatabaseInfo);
                    labelDatabaseUpdatedDate.Text = String.Format(labelDatabaseUpdatedDate.Text, dataJsonInfo.LastUpdated.ToShortDateString());
                    Program.log.Info("Latest database update date successful");
                }
            }
            catch (Exception ex)
            {
                labelDatabaseUpdatedDate.Text = String.Format(labelDatabaseUpdatedDate.Text, "n/a");
                Program.log.Error("Error getting latest database update date", ex);
            }
        }
Beispiel #18
0
        /// <summary>
        /// Show file details for a WebFile
        /// </summary>
        /// <param name="file">WebFile object</param>
        /// <param name="createNewInstance">Whether to create a new instance</param>
        public void ShowFileDetails(WebFile file, bool createNewInstance = true)
        {
            Program.log.Info("Showing file details dialog : " + file.URL);

            if (createNewInstance)
            {
                FrmFileDetails = new FileDetails();
            }

            FrmFileDetails.currentFile       = file;
            FrmFileDetails.infoFileName.Text = file.Name;
            FrmFileDetails.infoName.Text     = file.Name;
            FrmFileDetails.infoReferrer.Text = file.Host;
            FrmFileDetails.infoType.Text     = file.Type;
            FrmFileDetails.infoFileURL.Text  = Uri.UnescapeDataString(file.URL);

            // Build all parts of the URL into a better presented string
            var url         = new Uri(file.URL);
            var directories = new StringBuilder(file.Host);

            foreach (string path in url.LocalPath.Split('/'))
            {
                if (!Path.HasExtension(path))
                {
                    directories.Append(path + "> ");
                }
            }
            FrmFileDetails.infoDirectory.Text = directories.ToString();

            FrmFileDetails.infoSize.Text = TextExtensions.BytesToString(file.Size);
            FrmFileDetails.infoAge.Text  = TextExtensions.GetTimeAgo(file.DateUploaded);

            FrmFileDetails.Dock = DockStyle.Fill;
            if (!createNewInstance)
            {
                FrmFileDetails.CheckFileEvents();
            }
            if (createNewInstance)
            {
                tabBlank.Controls.Clear(); tabBlank.Controls.Add(FrmFileDetails);
            }
            tab.SelectedTab = tabBlank;

            Program.log.Info("Successfully loaded file details dialog");
        }
Beispiel #19
0
        /// <summary>
        /// Создает словарь с названиями команд cli и соответствующими им методы.
        /// </summary>
        Dictionary <string, MethodInfo> CreateReflectionDict()
        {
            Dictionary <string, MethodInfo> cmdNameAndMethod = new Dictionary <string, MethodInfo>();

            foreach (MethodInfo item in this.GetType().GetMethods())
            {
                CmdInfoAttribute attr = item.GetCustomAttribute(typeof(CmdInfoAttribute)) as CmdInfoAttribute;
                if (attr != null)
                {
                    //TODO: Remove attribute crunch.
                    attr.CmdName = attr?.CmdName ?? TextExtensions.ToUnderscoreCase(item.Name);
                    cmdNameAndMethod.Add(
                        attr.CmdName,
                        item)
                    ;
                }
            }
            return(cmdNameAndMethod);
        }
        /// <summary>
        /// Ищем методы.
        /// </summary>
        /// <param name="t">Исследуемый тип, не путать с InspectedType, ведь с погружением в его поля это будет их тип, соответственно.</param>
        /// <param name="funcToGetLocalInstanceFromGlobal">Делегат для получения объекта с типом t из InspectedType.</param>
        void inspectMetods(string prefix, string realNamePrefix, Type t, Func <object, object> funcToGetLocalInstanceFromGlobal)
        {
            var methodInfoList = getAllMethods(t);

            foreach (var item in methodInfoList)
            {
                var attr = item.GetCustomAttribute(typeof(Method_ReflectionMapAttribute)) as Method_ReflectionMapAttribute;
                if (attr != null)
                {
                    var newInfo = new Info_ReflectionMap()
                    {
                        DisplayName = prefix + (attr.DisplayName ?? TextExtensions.ToUnderscoreCase(item.Name)),
                        RealName    = realNamePrefix + item.Name,
                        Description = attr.Description,
                    };

                    var newMethod = new Method_ReflectionMap()
                    {
                        Parameters = parameterInfoArrayToParamsArray(item.GetParameters()),
                        ReturnType = item.ReturnType
                    };
                    newMethod.InvokeAction = (globalInst, parameters) =>
                    {
                        var locInst = funcToGetLocalInstanceFromGlobal(globalInst);
                        return(item.Invoke(locInst, parameters));
                    };
                    checkIfTaskAndDoDirtWork(item, newMethod);


                    _longNameAndInfo.Add(
                        newInfo.DisplayName,
                        newInfo
                        );

                    _longNameAndMethod.Add(
                        newInfo.DisplayName,
                        newMethod
                        );
                }
            }
        }
Beispiel #21
0
        public override void Load(Call call, TabModel model)
        {
            var items = new ItemCollection <ListItem>();

            string extension = System.IO.Path.GetExtension(Tab.Path);

            if (extension == ".json")
            {
                items.Add(new ListItem("Contents", LazyJsonNode.LoadPath(Tab.Path)));
                //items.Add(new ListItem("Contents", JsonValue.Parse(File.ReadAllText(path))));
            }
            else
            {
                bool isText = TextExtensions.Contains(extension);
                if (!isText)
                {
                    try
                    {
                        // doesn't work
                        using StreamReader streamReader = File.OpenText(Tab.Path);

                        var buffer = new char[100];
                        streamReader.Read(buffer, 0, buffer.Length);
                        isText = true;
                    }
                    catch (Exception)
                    {
                    }
                }

                if (isText)
                {
                    items.Add(new ListItem("Contents", new FilePath(Tab.Path)));
                }
                else
                {
                    items.Add(new ListItem("Contents", null));
                }
            }
            model.Items = items;
        }
Beispiel #22
0
        /// <summary>
        /// Gets recently added files in the database by checking if file was uploaded in the last two weeks
        /// </summary>
        public void LoadRecentlyAddedFiles()
        {
            try
            {
                int itemCount  = 1;
                var addedHosts = new List <string>();
                Program.log.Info("Getting recently added files");
                var copiedItems = new List <WebFile>(FilesOpenDatabase);
                copiedItems.Shuffle();
                foreach (var jsonData in copiedItems)
                {
                    if (DateTime.Today < jsonData.DateUploaded.Date.AddDays(14) && jsonData.Size > 0 && !addedHosts.Contains(jsonData.Host) && itemCount <= 6)
                    {
                        itemCount++;
                        addedHosts.Add(jsonData.Host);
                        dataGridRecentlyAdded.Rows.Add(jsonData.Type, jsonData.Name, TextExtensions.BytesToString(jsonData.Size), TextExtensions.GetTimeAgo(jsonData.DateUploaded), jsonData.Host, jsonData.URL);
                    }
                }

                Program.log.Info("Recently added files successful");
            }
            catch (Exception ex) { labelRecentlyAdded.Visible = false; splitterHeaderRecentlyAdded.Visible = false; dataGridRecentlyAdded.Visible = false; Program.log.Error("Error getting recently added files", ex); } /* Error occurred, so hide controls/skip... */
        }
Beispiel #23
0
        public static List <WebFile> Search(List <WebFile> dataFiles, string SearchQuery, SortBy SortBy)
        {
            lock (loadSearchListLock)
            {
                SortFiles(dataFiles, SortBy);

                return(dataFiles.Select(item =>
                                        new
                {
                    i = item,
                    Props = item.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
                })
                       .Where(item => item.Props.Any(p =>
                {
                    var val = p.GetValue(item.i, null);
                    return val != null &&
                    (p.Name.ToLower() == "URL".ToLower() || string.IsNullOrEmpty("URL")) &&
                    (TextExtensions.ContainsAll(Uri.UnescapeDataString(val.ToString().ToLower()), TextExtensions.GetWords(SearchQuery.ToLower())) || string.IsNullOrEmpty(SearchQuery));
                }))
                       .Select(item => item.i)
                       .ToList());
            }
        }
Beispiel #24
0
        public void HelpCmd()
        {
            StringBuilder res = new StringBuilder("\tВы можете передавать параметры в метод, разделяя из через '/'.\n" +
                                                  "\tИспользуйте параметр /auto для автоматического выполнения команд.\n\n");

            foreach (MethodInfo item in this.GetType().GetMethods())
            {
                CmdInfoAttribute attr = item.GetCustomAttribute(typeof(CmdInfoAttribute)) as CmdInfoAttribute;
                if (attr != null && attr.CmdName != "help")
                {
                    //TODO: Remove attribute crunch.
                    attr.CmdName = attr?.CmdName ?? TextExtensions.ToUnderscoreCase(item.Name);

                    string newStr  = "\t" + attr.CmdName + " - " + item.Name + "(";
                    bool   isFirst = true;

                    foreach (var parameter in item.GetParameters())
                    {
                        if (!isFirst)
                        {
                            newStr += ", ";
                        }
                        isFirst = false;
                        newStr += parameter.ParameterType.Name + "  " + parameter.Name;
                    }
                    newStr += ");";

                    if (attr.Description != null)
                    {
                        newStr += $"  /*{attr.Description}*/";
                    }
                    res.AppendLine(newStr);
                }
            }
            Cmd.Write(res.ToString());
        }
Beispiel #25
0
        protected virtual string GenerateModelSourceCode(ModelsGeneratorInput modelsGeneratorInput)
        {
            var    modelName   = modelsGeneratorInput.ClassName;
            string newClassStr = "public class " +
                                 modelName +
                                 GenerateBaseClass(modelsGeneratorInput) +
                                 "\n{\n";

            foreach (var param in modelsGeneratorInput.Params)
            {
                var paramName = param.ParamName;
                paramName = paramName[0].ToString().ToUpper() + paramName.Substring(1);
                var attrs        = GenerateAttributes(param.ParamInfo);
                var newClassProp = attrs
                                   + "public "
                                   + GetTypeName(param.ParamInfo.ParameterType)
                                   + " "
                                   + paramName
                                   + " { get; set; }";
                newClassStr += "\n" + TextExtensions.AddTabs(newClassProp, 1) + "\n";
            }
            newClassStr += "\n}";
            return(newClassStr);
        }
Beispiel #26
0
        public async Task <FileStatistics> ProcessFile(string path, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            var  info  = new FileInfo(path);
            long lines = 0;

            if (TextExtensions.Contains(Path.GetExtension(path)))
            {
                using var r = info.OpenText();
                while (true)
                {
                    if ((lines & 127) == 0)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                    }
                    var line = await r.ReadLineAsync().ConfigureAwait(false);

                    if (line == null)
                    {
                        break;
                    }
                    lines++;
                }
            }

            var statistics = new FileStatistics()
            {
                Count = 1,
                Size  = info.Length,
                Lines = lines
            };

            AddFileStatistics(path, false, statistics);

            return(statistics);
        }
Beispiel #27
0
 public static bool IsTextExtension(string extension)
 {
     return(TextExtensions.Contains(extension));
 }
Beispiel #28
0
    public static bool IsTextFile(string file)
    {
        var extension = Path.GetExtension(file).Substring(1);

        return(TextExtensions.Contains(extension));
    }
Beispiel #29
0
        private ScrollView GetTable()
        {
            ScrollView scrollView = new ScrollView()
            {
                Padding = 0, Margin = 0
            };
            StackLayout tablestack = new StackLayout()
            {
                Padding = 0, Margin = 0, Spacing = -2
            };

            foreach (var item in _wordList)
            {
                DynamicGrid dynamicGrid = new DynamicGrid(Xamarin.CustomViews.Enums.DynamicGridEnum.Custom, 20, 34, 40, 6)
                {
                    Padding = 0, Margin = 0, RowSpacing = 0, ColumnSpacing = 0
                };
                dynamicGrid.AddView(new Label()
                {
                    VerticalOptions = LayoutOptions.Center, FontAttributes = FontAttributes.Bold, TextColor = TextExtensions.GetTextColor(item.Type), Text = item.Type.ToString(), Margin = 0
                });
                dynamicGrid.AddView(new Label()
                {
                    VerticalOptions = LayoutOptions.Center, Text = item.Key, TextColor = UserSettings.TextColor, Margin = new Thickness(5, 0, 0, 0)
                });
                dynamicGrid.AddView(new Label()
                {
                    HorizontalTextAlignment = TextAlignment.Center, VerticalTextAlignment = TextAlignment.Center, TextColor = UserSettings.TextColor, Text = item.Description, Margin = 0
                });

                dynamicGrid.AddView(new CircleImage()
                {
                    Source = "delete.png", GestureRecognizers = { new TapGestureRecognizer()
                                                                  {
                                                                      Command = new Command(DeleteButtonPressed), CommandParameter = item
                                                                  } }
                });
                tablestack.Children.Add(dynamicGrid);
                tablestack.Children.Add(new Line(LineEnum.Horizontal, UserSettings.MainColor)
                {
                    Margin = 0
                });
            }
            scrollView.Content = tablestack;
            return(scrollView);
        }
Beispiel #30
0
 private void btnRequestFileSize_ClickButtonArea(object Sender, MouseEventArgs e)
 {
     // Request file size from URL
     buttonRequestFileSize.Visible = false;
     BackGroundWorker.RunWorkAsync <string>(() => TextExtensions.BytesToString(WebFileExtensions.GetFileSize(currentFile.URL)), (data) => { infoSize.Text = data; });
 }