示例#1
0
 public static string getRandomDir()
 {
     string randomDir = tmpdir + "dir" + String.valueOf((int)(Math.random() * 100000));
     File f = new File(randomDir);
     f.mkdirs();
     return randomDir;
 }
        public static File ParseCore(string filePath, CharacterPositionFinder finder, IXmlFlavor flavor, Encoding encoding)
        {
            using (var reader = new XmlTextReader(new StreamReader(SystemFile.OpenRead(filePath), encoding)))
            {
                var file = new File
                {
                    Name       = filePath,
                    FooterSpan = CharacterSpan.None,                // there is no footer
                };

                var fileBegin = new LineInfo(reader.LineNumber + 1, reader.LinePosition);

                try
                {
                    var dummyRoot = new Container();

                    // Parse the XML and display the text content of each of the elements.
                    // as there are XMLs that have the declaration on same line as the root element, we just loop and parse until the end
                    while (!reader.EOF)
                    {
                        Parse(reader, dummyRoot, finder, flavor);
                    }

                    var root    = dummyRoot.Children.OfType <Container>().Last();
                    var rootEnd = FixRoot(root, dummyRoot);

                    var fileEnd = new LineInfo(reader.LineNumber, reader.LinePosition - 1);

                    var positionAfterLastElement = new LineInfo(rootEnd.LineNumber, rootEnd.LinePosition + 1); // we calculate the next one (either a new line character or a regular one)

                    file.LocationSpan = new LocationSpan(fileBegin, fileEnd);

                    if (positionAfterLastElement < fileEnd)
                    {
                        file.FooterSpan = GetCharacterSpan(new LocationSpan(positionAfterLastElement, fileEnd), finder);
                    }

                    file.Children.Add(root);
                }
                catch (XmlException ex)
                {
                    // try to adjust location span to include full file content
                    // but ignore empty files as parsing errors
                    var lines = SystemFile.ReadLines(filePath).Count();
                    if (lines == 0)
                    {
                        file.LocationSpan = new LocationSpan(LineInfo.None, LineInfo.None);
                    }
                    else
                    {
                        file.ParsingErrors.Add(new ParsingError
                        {
                            ErrorMessage = ex.Message,
                            Location     = new LineInfo(ex.LineNumber, ex.LinePosition),
                        });

                        file.LocationSpan = new LocationSpan(new LineInfo(1, 0), new LineInfo(lines + 1, 0));
                    }
                }

                return(file);
            }
        }
示例#3
0
        public static MimeMessage FromStub(EmailMessage msg)
        {
            MimeMessage outMsg = new MimeMessage();

            var from = msg.From.FirstOrDefault();

            outMsg.From.Add(from.ToMailAddress());

            EmailAddress.IterateBack(msg.To).ForEach(addr => outMsg.To.Add(addr));
            if (msg.CC != null && msg.CC.Count != 0)
            {
                if (!string.IsNullOrEmpty(msg.CC[0].Name) && !string.IsNullOrEmpty(msg.CC[0].Address))
                {
                    EmailAddress.IterateBack(msg.CC).ForEach(addr => outMsg.Cc.Add(addr));
                }
            }
            if (msg.Bcc != null && msg.Bcc.Count != 0)
            {
                if (!string.IsNullOrEmpty(msg.Bcc[0].Name) && !string.IsNullOrEmpty(msg.Bcc[0].Address))
                {
                    EmailAddress.IterateBack(msg.Bcc).ForEach(addr => outMsg.Bcc.Add(addr));
                }
            }
            outMsg.Subject = msg.Subject;

            var body = new TextPart();

            if (msg.IsBodyHtml)
            {
                body = new TextPart("html")
                {
                    Text = msg.Body
                };
            }
            else
            {
                body = new TextPart("plain")
                {
                    Text = msg.PlainTextBody
                };
            }

            //create the multipart/mixed container to hold the message text and the attachment
            var multipart = new Multipart("mixed");

            if (msg.Attachments != null || msg.Attachments.Count != 0)
            {
                //get all attachments from email message
                foreach (var msgAttachment in msg.Attachments)
                {
                    var attachment = new MimePart("image", "gif")
                    {
                        Content                 = new MimeContent(IOFile.OpenRead(msgAttachment.ContentStorageAddress), ContentEncoding.Default),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName                = msgAttachment.Name
                    };

                    multipart.Add(attachment);
                }
            }

            multipart.Add(body);

            //set the multipart/mixed as the message body
            outMsg.Body = multipart;

            return(outMsg);
        }
        // This is NOT thread safe but it is only called from within a lock
        private Assembly GetModelsAssembly(bool forceRebuild)
        {
            if (!Directory.Exists(_pureLiveDirectory.Value))
            {
                Directory.CreateDirectory(_pureLiveDirectory.Value);
            }

            IList <TypeModel> typeModels = UmbracoServices.GetAllTypes();
            var currentHash    = TypeModelHasher.Hash(typeModels);
            var modelsHashFile = Path.Combine(_pureLiveDirectory.Value, "models.hash");
            var modelsSrcFile  = Path.Combine(_pureLiveDirectory.Value, "models.generated.cs");
            var projFile       = Path.Combine(_pureLiveDirectory.Value, "all.generated.cs");
            var dllPathFile    = Path.Combine(_pureLiveDirectory.Value, "all.dll.path");

            // caching the generated models speeds up booting
            // currentHash hashes both the types & the user's partials
            if (!forceRebuild)
            {
                _logger.LogDebug("Looking for cached models.");
                if (File.Exists(modelsHashFile) && File.Exists(projFile))
                {
                    var cachedHash = File.ReadAllText(modelsHashFile);
                    if (currentHash != cachedHash)
                    {
                        _logger.LogDebug("Found obsolete cached models.");
                        forceRebuild = true;
                    }

                    // else cachedHash matches currentHash, we can try to load an existing dll
                }
                else
                {
                    _logger.LogDebug("Could not find cached models.");
                    forceRebuild = true;
                }
            }

            Assembly assembly;

            if (!forceRebuild)
            {
                // try to load the dll directly (avoid rebuilding)
                //
                // ensure that the .dll file does not have a corresponding .dll.delete file
                // as that would mean the the .dll file is going to be deleted and should not
                // be re-used - that should not happen in theory, but better be safe
                if (File.Exists(dllPathFile))
                {
                    var dllPath = File.ReadAllText(dllPathFile);

                    _logger.LogDebug($"Cached models dll at {dllPath}.");

                    if (File.Exists(dllPath) && !File.Exists(dllPath + ".delete"))
                    {
                        assembly = ReloadAssembly(dllPath);

                        ModelsBuilderAssemblyAttribute?attr = assembly.GetCustomAttribute <ModelsBuilderAssemblyAttribute>();
                        if (attr != null && attr.IsInMemory && attr.SourceHash == currentHash)
                        {
                            // if we were to resume at that revision, then _ver would keep increasing
                            // and that is probably a bad idea - so, we'll always rebuild starting at
                            // ver 1, but we remember we want to skip that one - so we never end up
                            // with the "same but different" version of the assembly in memory
                            _skipver = assembly.GetName().Version?.Revision;

                            _logger.LogDebug("Loading cached models (dll).");
                            return(assembly);
                        }

                        _logger.LogDebug("Cached models dll cannot be loaded (invalid assembly).");
                    }
                    else if (!File.Exists(dllPath))
                    {
                        _logger.LogDebug("Cached models dll does not exist.");
                    }
                    else if (File.Exists(dllPath + ".delete"))
                    {
                        _logger.LogDebug("Cached models dll is marked for deletion.");
                    }
                    else
                    {
                        _logger.LogDebug("Cached models dll cannot be loaded (why?).");
                    }
                }

                // must reset the version in the file else it would keep growing
                // loading cached modules only happens when the app restarts
                var   text  = File.ReadAllText(projFile);
                Match match = s_assemblyVersionRegex.Match(text);
                if (match.Success)
                {
                    text = text.Replace(match.Value, "AssemblyVersion(\"0.0.0." + _ver + "\")");
                    File.WriteAllText(projFile, text);
                }

                _ver++;
                try
                {
                    var assemblyPath = GetOutputAssemblyPath(currentHash);
                    RoslynCompiler.CompileToFile(projFile, assemblyPath);
                    assembly = ReloadAssembly(assemblyPath);
                    File.WriteAllText(dllPathFile, assembly.Location);
                    File.WriteAllText(modelsHashFile, currentHash);
                    TryDeleteUnusedAssemblies(dllPathFile);
                }
                catch
                {
                    ClearOnFailingToCompile(dllPathFile, modelsHashFile, projFile);
                    throw;
                }

                _logger.LogDebug("Loading cached models (source).");
                return(assembly);
            }

            // need to rebuild
            _logger.LogDebug("Rebuilding models.");

            // generate code, save
            var code = GenerateModelsCode(typeModels);
            // add extra attributes,
            //  IsLive=true helps identifying Assemblies that contain live models
            //  AssemblyVersion is so that we have a different version for each rebuild
            var ver = _ver == _skipver ? ++_ver : _ver;

            _ver++;
            string mbAssemblyDirective = $@"[assembly:ModelsBuilderAssembly(IsInMemory = true, SourceHash = ""{currentHash}"")]
[assembly:System.Reflection.AssemblyVersion(""0.0.0.{ver}"")]";

            code = code.Replace("//ASSATTR", mbAssemblyDirective);
            File.WriteAllText(modelsSrcFile, code);

            // generate proj, save
            var projFiles = new Dictionary <string, string>
            {
                { "models.generated.cs", code }
            };
            var proj = GenerateModelsProj(projFiles);

            File.WriteAllText(projFile, proj);

            // compile and register
            try
            {
                var assemblyPath = GetOutputAssemblyPath(currentHash);
                RoslynCompiler.CompileToFile(projFile, assemblyPath);
                assembly = ReloadAssembly(assemblyPath);
                File.WriteAllText(dllPathFile, assemblyPath);
                File.WriteAllText(modelsHashFile, currentHash);
                TryDeleteUnusedAssemblies(dllPathFile);
            }
            catch
            {
                ClearOnFailingToCompile(dllPathFile, modelsHashFile, projFile);
                throw;
            }

            _logger.LogDebug("Done rebuilding.");
            return(assembly);
        }
示例#5
0
 public static bool Exists(string path)
 {
     return(File.Exists(path));
 }
示例#6
0
        async void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;
            var key    = e.Argument as String;

            try
            {
                var Bot = new Telegram.Bot.TelegramBotClient(key);
                await Bot.SetWebhookAsync("");

                int offset = 0;
                while (true)
                {
                    Update[] updates;
                    decimal  conAttempts       = 1;
                    decimal  allwaitingseconds = 0;
                    while (true)
                    {
                        try
                        {
                            updates = await Bot.GetUpdatesAsync(offset);
                        }
                        catch (Exception ex)
                        {
                            allwaitingseconds += (conAttempts / 10);
                            SendLog("No connection for the last " + allwaitingseconds + " seconds, attempt = " + conAttempts++);
                            Thread.Sleep((int)conAttempts * 100);
                            continue;
                        }
                        conAttempts = 1;
                        break;
                    }
                    foreach (var update in updates)
                    {
                        Person p = null;
                        if (update.Message.From.Username != null)
                        {
                            p = new Person(update.Message.From.Id, update.Message.From.Username, constr);
                        }
                        else
                        {
                            p = new Person(update.Message.From.Id, update.Message.From.FirstName + " " + update.Message.From.LastName, constr);
                        }
                        var keyboardStandart = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup
                        {
                            Keyboard = new[] {
                                new[]
                                {
                                    new Telegram.Bot.Types.KeyboardButton("Задание"),
                                },
                                new[]
                                {
                                    new Telegram.Bot.Types.KeyboardButton("Очки"),
                                    new Telegram.Bot.Types.KeyboardButton("ТОП-10"),
                                    new Telegram.Bot.Types.KeyboardButton("Помощь")
                                },
                            },
                            OneTimeKeyboard = false,
                            ResizeKeyboard  = true
                        };
                        var keyboardStandartFail = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup
                        {
                            Keyboard = new[] {
                                new[]
                                {
                                    new Telegram.Bot.Types.KeyboardButton("Задание")
                                },
                                new[]
                                {
                                    new Telegram.Bot.Types.KeyboardButton("Очки"),
                                    new Telegram.Bot.Types.KeyboardButton("ТОП-10"),
                                    new Telegram.Bot.Types.KeyboardButton("Помощь")
                                },
                                new[]
                                {
                                    new Telegram.Bot.Types.KeyboardButton("Ошибка в последнем вопросе?")
                                },
                            },
                            OneTimeKeyboard = false,
                            ResizeKeyboard  = true
                        };
                        var keyboardSerial = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup
                        {
                            Keyboard = new[] {
                                new[]
                                {
                                    new Telegram.Bot.Types.KeyboardButton(p.VSerial[0]),
                                    new Telegram.Bot.Types.KeyboardButton(p.VSerial[1]),
                                    new Telegram.Bot.Types.KeyboardButton(p.VSerial[2]),
                                    new Telegram.Bot.Types.KeyboardButton(p.VSerial[3])
                                },
                            },
                            OneTimeKeyboard = false,
                            ResizeKeyboard  = true
                        };
                        var keyboardSeason = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup();
                        if (p.C_serial == "SGU")
                        {
                            keyboardSeason = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup
                            {
                                Keyboard = new[] {
                                    new[]
                                    {
                                        new Telegram.Bot.Types.KeyboardButton("1"),
                                        new Telegram.Bot.Types.KeyboardButton("2")
                                    },
                                },
                                OneTimeKeyboard = false,
                                ResizeKeyboard  = true
                            };
                        }
                        else
                        {
                            keyboardSeason = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup
                            {
                                Keyboard = new[] {
                                    new[]
                                    {
                                        new Telegram.Bot.Types.KeyboardButton(p.V_Season[0]),
                                        new Telegram.Bot.Types.KeyboardButton(p.V_Season[1]),
                                        new Telegram.Bot.Types.KeyboardButton(p.V_Season[2]),
                                        new Telegram.Bot.Types.KeyboardButton(p.V_Season[3])
                                    },
                                },
                                OneTimeKeyboard = false,
                                ResizeKeyboard  = true
                            };
                        }
                        var keyboardSeries = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup
                        {
                            Keyboard = new[] {
                                new[]
                                {
                                    new Telegram.Bot.Types.KeyboardButton(p.V_Series[0])
                                },
                                new[]
                                {
                                    new Telegram.Bot.Types.KeyboardButton(p.V_Series[1])
                                },
                                new[]
                                {
                                    new Telegram.Bot.Types.KeyboardButton(p.V_Series[2])
                                },
                                new[]
                                {
                                    new Telegram.Bot.Types.KeyboardButton(p.V_Series[3])
                                },
                            },
                            OneTimeKeyboard = false,
                            ResizeKeyboard  = true
                        };
                        var  message   = update.Message;
                        bool recognise = false;
                        if (message.Type == Telegram.Bot.Types.Enums.MessageType.TextMessage)
                        {
                            #region stand_0
                            if (p.stand == 0)
                            {
                                if (message.Text == "/start")
                                {
                                    p.Ask     = false;
                                    recognise = true;
                                    if (p.task.Contains("http"))
                                    {
                                        await Bot.SendPhotoAsync(message.Chat.Id, new FileToSend(p.task), "Из какого сериала или фильмов эта картинка?", false, 0, keyboardSerial);
                                    }
                                    else
                                    {
                                        await Bot.SendTextMessageAsync(message.Chat.Id, "Из какого сериала или фильмов эта фраза? \n\n" + p.task, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardSerial);
                                    }
                                }
                                if (message.Text == p.VSerial[0] || message.Text == p.VSerial[1] || message.Text == p.VSerial[2] || message.Text == p.VSerial[3])
                                {
                                    p.Ask     = false;
                                    recognise = true;
                                    if (message.Text == p.C_serial)
                                    {
                                        if (p.C_serial == "Movies")
                                        {
                                            p.stand += 2;
                                            p.SaveToSQl();
                                            SendLog(message.Text + " FROM " + p.UserName + " ITIS " + "Correct" + " STAND " + p.stand + " TASK_ID " + p.taskId);
                                            if (p.task.Contains("http"))
                                            {
                                                await Bot.SendPhotoAsync(message.Chat.Id, new FileToSend(p.task), p.C_serial + ", верно! Какой фильм?", false, 0, keyboardSeries);
                                            }
                                            else
                                            {
                                                await Bot.SendTextMessageAsync(message.Chat.Id, p.C_serial + ", верно! Какой фильм? \n\n" + p.task, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardSeries);
                                            }
                                        }
                                        else
                                        {
                                            p.stand++;
                                            p.SaveToSQl();
                                            SendLog(message.Text + " FROM " + p.UserName + " ITIS " + "Correct" + " STAND " + p.stand + " TASK_ID " + p.taskId);
                                            if (p.task.Contains("http"))
                                            {
                                                await Bot.SendPhotoAsync(message.Chat.Id, new FileToSend(p.task), p.C_serial + ", верно! Какой сезон?", false, 0, keyboardSeason);
                                            }
                                            else
                                            {
                                                await Bot.SendTextMessageAsync(message.Chat.Id, p.C_serial + ", верно! Какой сезон? \n\n" + p.task, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardSeason);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        p.stand = 3;
                                        p.TaskWrong();
                                        SendLog(message.Text + " FROM " + p.UserName + " ITIS " + "InCorrect" + " SCORE " + p.Score + " TASK_ID " + p.taskId);
                                        await Bot.SendTextMessageAsync(message.Chat.Id, "Неверно! Запросите новое задание!", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandartFail);
                                    }
                                }
                            }
                            #endregion
                            #region stand_1
                            if (p.stand == 1)
                            {
                                if (message.Text == "/start")
                                {
                                    p.Ask     = false;
                                    recognise = true;
                                    if (p.task.Contains("http"))
                                    {
                                        await Bot.SendPhotoAsync(message.Chat.Id, new FileToSend(p.task), p.C_serial + ", верно! Какой сезон?", false, 0, keyboardSeason);
                                    }
                                    else
                                    {
                                        await Bot.SendTextMessageAsync(message.Chat.Id, p.C_serial + ", верно! Какой сезон?\n\n" + p.task, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardSeason);
                                    }
                                }
                                if (p.C_serial == "SGU")
                                {
                                    if (message.Text == "1" || message.Text == "2")
                                    {
                                        p.Ask     = false;
                                        recognise = true;
                                        if (message.Text == p.C_season)
                                        {
                                            p.stand++;
                                            p.SaveToSQl();
                                            SendLog(message.Text + " FROM " + p.UserName + " ITIS " + "Correct" + " STAND " + p.stand + " TASK_ID " + p.taskId);
                                            if (p.task.Contains("http"))
                                            {
                                                await Bot.SendPhotoAsync(message.Chat.Id, new FileToSend(p.task), p.C_season + ", верно! Какая серия?", false, 0, keyboardSeries);
                                            }
                                            else
                                            {
                                                await Bot.SendTextMessageAsync(message.Chat.Id, p.C_season + ", верно! Какая серия?\n\n" + p.task, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardSeries);
                                            }
                                        }
                                        else
                                        {
                                            p.stand = 3;
                                            p.TaskWrong();
                                            SendLog(message.Text + " FROM " + p.UserName + " ITIS " + "InCorrect" + " SCORE " + p.Score + " TASK_ID " + p.taskId);
                                            await Bot.SendTextMessageAsync(message.Chat.Id, "Неверно! Запросите новое задание!", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandartFail);
                                        }
                                    }
                                }
                                else
                                {
                                    if (message.Text == p.V_Season[0] || message.Text == p.V_Season[1] || message.Text == p.V_Season[2] || message.Text == p.V_Season[3])
                                    {
                                        p.Ask     = false;
                                        recognise = true;
                                        if (message.Text == p.C_season)
                                        {
                                            p.stand++;
                                            p.SaveToSQl();
                                            SendLog(message.Text + " FROM " + p.UserName + " ITIS " + "Correct" + " STAND " + p.stand + " TASK_ID " + p.taskId);
                                            if (p.task.Contains("http"))
                                            {
                                                await Bot.SendPhotoAsync(message.Chat.Id, new FileToSend(p.task), p.C_season + ", верно! Какая серия?", false, 0, keyboardSeries);
                                            }
                                            else
                                            {
                                                await Bot.SendTextMessageAsync(message.Chat.Id, p.C_season + ", верно! Какая серия?\n\n" + p.task, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardSeries);
                                            }
                                        }
                                        else
                                        {
                                            p.stand = 3;
                                            p.TaskWrong();
                                            SendLog(message.Text + " FROM " + p.UserName + " ITIS " + "InCorrect" + " SCORE " + p.Score + " TASK_ID " + p.taskId);
                                            await Bot.SendTextMessageAsync(message.Chat.Id, "Неверно! Запросите новое задание!", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandartFail);
                                        }
                                    }
                                }
                            }
                            #endregion
                            #region stand_2
                            if (p.stand == 2)
                            {
                                if (message.Text == "/start")
                                {
                                    p.Ask     = false;
                                    recognise = true;
                                    if (p.C_serial == "Movies")
                                    {
                                        if (p.task.Contains("http"))
                                        {
                                            await Bot.SendPhotoAsync(message.Chat.Id, new FileToSend(p.task), p.C_serial + ", верно! Какой фильм?", false, 0, keyboardSeries);
                                        }
                                        else
                                        {
                                            await Bot.SendTextMessageAsync(message.Chat.Id, p.C_serial + ", верно! Какой фильм?\n\n" + p.task, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardSeries);
                                        }
                                    }
                                    else
                                    {
                                        if (p.task.Contains("http"))
                                        {
                                            await Bot.SendPhotoAsync(message.Chat.Id, new FileToSend(p.task), p.C_season + ", верно! Какая серия?", false, 0, keyboardSeries);
                                        }
                                        else
                                        {
                                            await Bot.SendTextMessageAsync(message.Chat.Id, p.C_season + ", верно! Какая серия?\n\n" + p.task, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardSeries);
                                        }
                                    }
                                }
                                if (message.Text == p.V_Series[0] || message.Text == p.V_Series[1] || message.Text == p.V_Series[2] || message.Text == p.V_Series[3])
                                {
                                    p.Ask     = false;
                                    recognise = true;
                                    if (message.Text == p.C_series)
                                    {
                                        p.stand++;
                                        p.TaskDone();
                                        SendLog(message.Text + " FROM " + p.UserName + " ITIS " + "Correct" + " SCORE " + p.Score + " TASK_ID " + p.taskId);
                                        await Bot.SendTextMessageAsync(message.Chat.Id, p.C_series + ", верно! Вы молодец! Запрашивайте новое задание :)", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandart);
                                    }
                                    else
                                    {
                                        p.stand = 3;
                                        p.TaskWrong();
                                        SendLog(message.Text + " FROM " + p.UserName + " ITIS " + "InCorrect" + " SCORE " + p.Score + " TASK_ID " + p.taskId);
                                        await Bot.SendTextMessageAsync(message.Chat.Id, "Неверно! Запросите новое задание!", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandartFail);
                                    }
                                }
                            }
                            #endregion
                            #region stand_3
                            if (p.stand == 3)
                            {
                                if (message.Text == "Задание")
                                {
                                    recognise = true;
                                    p.Ask     = false;
                                    p.stand   = 0;
                                    p.GetTask();
                                    SendLog(message.Text + " TO " + p.UserName + " TASK_ID " + p.taskId);
                                    if (p.task.Contains("http"))
                                    {
                                        await Bot.SendPhotoAsync(message.Chat.Id, new FileToSend(p.task), "Из какого сериала или фильмов эта картинка?", false, 0, keyboardSerial);
                                    }
                                    else
                                    {
                                        await Bot.SendTextMessageAsync(message.Chat.Id, "Из какого сериала или фильмов эта фраза?\n\n" + p.task, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardSerial);
                                    }
                                }
                                if (message.Text == "Ошибка в последнем вопросе?" && !p.done)
                                {
                                    recognise = true;
                                    p.Ask     = true;
                                    p.SaveToSQl();
                                    SendLog("SEND_INSTRUCTION_TO_WRONG_MSG_TO " + p.UserName + " TASK_ID " + p.taskId + " ASK_UNIT " + p.Ask.ToString());
                                    await Bot.SendTextMessageAsync(message.Chat.Id, "Отправьте сообщение с описанием проблемы на столько широко как сможете, так же тут можно оставить свой отзыв.", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandart);
                                }
                                if (message.Text == "Помощь")
                                {
                                    p.Ask     = false;
                                    recognise = true;
                                    SendLog(message.Text + " TO " + p.UserName);
                                    await Bot.SendTextMessageAsync(message.Chat.Id, "Просто отвечайте на вопросы и зарабатывайте очки. Верный ответ +1, неверный -1 балл.\nДля управления чатом используй кнопки внизу.", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandart);
                                }
                                if (message.Text == "ТОП-10")
                                {
                                    p.Ask     = false;
                                    recognise = true;
                                    SendLog(message.Text + " TO " + p.UserName);
                                    await Bot.SendTextMessageAsync(message.Chat.Id, getTopList(), Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandart);
                                }
                                if (message.Text == "Очки")
                                {
                                    p.Ask     = false;
                                    recognise = true;
                                    SendLog(message.Text + " TO " + p.UserName + " SCORE " + p.Score);
                                    await Bot.SendTextMessageAsync(message.Chat.Id, "Кол-во очков: " + p.Score, Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandart);
                                }
                                if (message.Text == "/start")
                                {
                                    p.Ask     = false;
                                    recognise = true;
                                    if (!p.amnew)
                                    {
                                        SendLog("NEW_OLD_USER " + p.Id + " NAME " + p.UserName);
                                        await Bot.SendTextMessageAsync(message.Chat.Id, "С Возвращением!\nИспользуйте клавиатуру для работы с чатом", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandart);
                                    }
                                    else
                                    {
                                        SendLog("NEW_USER " + p.Id + " NAME " + p.UserName);
                                        await Bot.SendTextMessageAsync(message.Chat.Id, "Добро пожаловать!\nИспользуйте клавиатуру для работы с чатом", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandart);
                                    }
                                }
                            }
                            #endregion
                            if (message.Text != "" && !recognise && !p.Ask)
                            {
                                SendLog(message.Text + " SOME_TEXT_WRONG " + " FROM " + p.UserName);
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Я не могу ответить на это сообщение, не кликайте на кнопку по нескольку раз, не дождавшись ответа и не пишите с клавиатуры до требования бота!");
                            }
                            else if (message.Text != "" && p.Ask && !recognise)
                            {
                                p.Ask = false;
                                SendLog(message.Text + " RECEIVING_MSG_FROM_USER " + p.UserName);
                                AskToSQL(message.Text, p);
                                p.SaveToSQl();
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Ваше сообщение принято для обработки, со временем изменения вступят в силу", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboardStandart);
                            }
                        }
                        else
                        {
                            SendLog("SOME_NOT_TEXT_WRONG " + " FROM " + p.UserName);
                            await Bot.SendTextMessageAsync(message.Chat.Id, "Я могу отвечать только на текстовые сообщения!");
                        }
                        offset = update.Id + 1;
                    }
                }
            }
            catch (Exception ex)
            {
                File.WriteAllText(DateTime.Now.ToString("dd.MM.yy hh.mm.ss") + " errorlog.txt", DateTime.Now + " -- " + ex.Message + "\n"
                                  + ex.TargetSite.Name + "\n" + ex.StackTrace + "\n" + ex.HelpLink);
                Application.Current.Shutdown();
            }
        }
示例#7
0
        public bool Load()
        {
            bool r = false;

            bool ve = FileIO.Exists(VersionFilePath);

            if (ve)
            {
                String VersionFileContents = FileIO.ReadAllText(VersionFilePath, System.Text.Encoding.Unicode);
                if (VersionFileContents == NetworkConfig.VersionString)
                {
                    r = true;
                }
                else
                {
                    String IncompatPath = String.Concat(DataSavePath, "_", VersionFileContents);
                    if (DirectoryIO.Exists(IncompatPath))
                    {
                        DirectoryIO.Delete(IncompatPath, true);
                    }
                    DirectoryIO.Move(DataSavePath, IncompatPath);
                    System.Windows.Forms.MessageBox.Show(String.Concat(
                                                             "The application tried to load Js ChatterBox files that were incompatible ",
                                                             "with this version. They have been moved to \"", IncompatPath, "\"."));
                }
            }

            if (r)
            {
                try
                {
                    #region ConfigFileLoading
                    {
                        String ConfigText = FileIO.ReadAllText(ConfigFilePath, System.Text.Encoding.Unicode);
                        JsEncoder.TableValue ConfigTable = (JsEncoder.TableValue)JsEncoder.DecoderStream.DecodeValue(ConfigText);

                        UserName    = ((JsEncoder.StringValue)ConfigTable[new JsEncoder.StringValue("UserName")]).Value;
                        WorkingPort = ((JsEncoder.IntValue)ConfigTable[new JsEncoder.StringValue("WorkingPort")]).Value;
                    }
                    #endregion

                    String HostListFileContents        = FileIO.ReadAllText(HostListFilePath, System.Text.Encoding.Unicode);
                    JsEncoder.TableValue HostListTable = (JsEncoder.TableValue)JsEncoder.DecoderStream.DecodeValue(HostListFileContents);
                    HostList = UserHostList.FromTable(HostListTable);
                }
                catch (Exception e)
                {
                    String BaseIncompatPath  = String.Concat(DataSavePath, "_Damaged<N>");
                    String FinalIncompatPath = null;
                    int    i = 0;
                    while (FinalIncompatPath == null)
                    {
                        i++;
                        FinalIncompatPath = BaseIncompatPath.Replace("<N>", i.ToString());
                        if (DirectoryIO.Exists(FinalIncompatPath))
                        {
                            FinalIncompatPath = null;
                        }
                    }
                    DirectoryIO.Move(DataSavePath, FinalIncompatPath);

                    r = false;
                    System.Windows.Forms.MessageBox.Show(String.Concat(
                                                             "An error occured while loading your save files. They have been moved to \"",
                                                             FinalIncompatPath, "\" and you will now get the defaults. ",
                                                             "The error message is \"", e.Message, "\"."));
                }
            }
            if (!r)
            {
                UserName    = "******";
                HostList    = new UserHostList();
                WorkingPort = NetworkConfig.DefaultServerPort;
            }
            _IsLoaded = true;
            return(r);
        }
示例#8
0
        /// <summary>
        /// if use /presence [subject] create list with buttons
        /// or use /presence create text with results
        /// </summary>
        public override async void Execute(Message message, TelegramBotClient client)
        {
            var inlineKeybord = new InlineKeyboardMarkup(new[]
            {
                new[]
                {
                    InlineKeyboardButton.WithCallbackData("Присутній", "Присутній"),
                    InlineKeyboardButton.WithCallbackData("Н/Б", "Н/Б")
                }
            });
            var chatId = message.Chat.Id;

            if (group.Presence != null & group.Presence.Count != 11 & group.Presence.Count < 11)
            {
                group.Presence.Clear();

                try
                {
                    if (Args.Length > 2)
                    {
                        throw new Exception("Args out");
                    }
                    subject = Args[0];
                    await client.SendTextMessageAsync(chatId, $"{Args[0]}\n");

                    foreach (var classmate in group.Group)
                    {
                        await client.SendTextMessageAsync(chatId, $"{classmate}", replyMarkup : inlineKeybord);
                    }
                    string msg = $"{DateTime.Now}: initials - '{message.Chat.FirstName} {message.Chat.LastName} @{message.Chat.Username}', chatId - '{message.Chat.Id}', message - \"{message.Text}\"";
                    File.AppendAllText("Message.log", $"{msg}\n");
                }
                catch (Exception e)
                {
                    string errmsg = $"{DateTime.Now}: initials - '{message.Chat.FirstName} {message.Chat.LastName} @{message.Chat.Username}', chatId - '{message.Chat.Id}', message - \"{message.Text}\", error - '{e.Message}' path - '{e.StackTrace}'";
                    File.AppendAllText("Error.log", $"{errmsg}\n");
                    await client.SendTextMessageAsync(chatId, $"Enter Command properly '{this.Example}'");
                }
            }
            else
            {
                string s = null;
                s += $"{subject} - {DateTime.Now.ToShortDateString()}\n";
                for (int i = 0; i < group.Presence.Count; i++)
                {
                    s += $"{group.Group[i]} - {group.Presence[i]}\n";
                }
                try
                {
                    if (Args.Length > 2)
                    {
                        throw new Exception("Args out");
                    }
                    else if (group.Presence.Count < 11)
                    {
                        new Exception("Fill all column");
                    }
                    string msg = $"{DateTime.Now}: initials - '{message.Chat.FirstName} {message.Chat.LastName} @{message.Chat.Username}', chatId - '{message.Chat.Id}', message - \"{message.Text}\"";
                    File.AppendAllText("Message.log", $"{msg}\n");
                    await client.SendTextMessageAsync(chatId, s);
                }
                catch (Exception e)
                {
                    string errmsg = $"{DateTime.Now}: initials - '{message.Chat.FirstName} {message.Chat.LastName} @{message.Chat.Username}', chatId - '{message.Chat.Id}', message - \"{message.Text}\", error - '{e.Message}' path - '{e.StackTrace}'";
                    File.AppendAllText("Error.log", $"{errmsg}\n");
                    await client.SendTextMessageAsync(chatId, $"Something going wrong");
                }
            }
        }
        protected override void ExecuteCmdlet()
        {
            List <string> exportedTerms;

            if (ParameterSetName == "TermSet")
            {
                if (Delimiter != "|" && Delimiter == ";#")
                {
                    throw new Exception("Restricted delimiter specified");
                }
                if (!string.IsNullOrEmpty(TermStoreName))
                {
                    var taxSession = TaxonomySession.GetTaxonomySession(ClientContext);
                    var termStore  = taxSession.TermStores.GetByName(TermStoreName);
                    exportedTerms = ClientContext.Site.ExportTermSet(TermSetId.Id, IncludeID, termStore, Delimiter, Lcid);
                }
                else
                {
                    exportedTerms = ClientContext.Site.ExportTermSet(TermSetId.Id, IncludeID, Delimiter, Lcid);
                }
            }
            else
            {
                exportedTerms = ClientContext.Site.ExportAllTerms(IncludeID, Delimiter);
            }

            if (Path == null)
            {
                WriteObject(exportedTerms);
            }
            else
            {
                if (!System.IO.Path.IsPathRooted(Path))
                {
                    Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
                }

                System.Text.Encoding textEncoding = System.Text.Encoding.Unicode;
                switch (Encoding)
                {
                case Encoding.ASCII:
                {
                    textEncoding = System.Text.Encoding.ASCII;
                    break;
                }

                case Encoding.BigEndianUnicode:
                {
                    textEncoding = System.Text.Encoding.BigEndianUnicode;
                    break;
                }

                case Encoding.UTF32:
                {
                    textEncoding = System.Text.Encoding.UTF32;
                    break;
                }

                case Encoding.UTF7:
                {
                    textEncoding = System.Text.Encoding.UTF7;
                    break;
                }

                case Encoding.UTF8:
                {
                    textEncoding = System.Text.Encoding.UTF8;
                    break;
                }

                case Encoding.Unicode:
                {
                    textEncoding = System.Text.Encoding.Unicode;
                    break;
                }
                }

                if (File.Exists(Path))
                {
                    if (Force || ShouldContinue(string.Format(Resources.File0ExistsOverwrite, Path), Resources.Confirm))
                    {
                        File.WriteAllLines(Path, exportedTerms, textEncoding);
                    }
                }
                else
                {
                    File.WriteAllLines(Path, exportedTerms, textEncoding);
                }
            }
        }
        /// <summary>
        /// Converts the value received from the editor into the value can be stored in the database.
        /// </summary>
        /// <param name="editorValue">The value received from the editor.</param>
        /// <param name="currentValue">The current value of the property</param>
        /// <returns>The converted value.</returns>
        /// <remarks>
        /// <para>The <paramref name="currentValue"/> is used to re-use the folder, if possible.</para>
        /// <para>editorValue.Value is used to figure out editorFile and, if it has been cleared, remove the old file - but
        /// it is editorValue.AdditionalData["files"] that is used to determine the actual file that has been uploaded.</para>
        /// </remarks>
        public override object ConvertEditorToDb(ContentPropertyData editorValue, object currentValue)
        {
            // get the current path
            var currentPath = string.Empty;

            try
            {
                var svalue      = currentValue as string;
                var currentJson = string.IsNullOrWhiteSpace(svalue) ? null : JObject.Parse(svalue);
                if (currentJson != null && currentJson["src"] != null)
                {
                    currentPath = currentJson["src"].Value <string>();
                }
            }
            catch (Exception ex)
            {
                // for some reason the value is invalid so continue as if there was no value there
                LogHelper.WarnWithException <ImageCropperPropertyValueEditor>("Could not parse current db value to a JObject.", ex);
            }
            if (string.IsNullOrWhiteSpace(currentPath) == false)
            {
                currentPath = _mediaFileSystem.GetRelativePath(currentPath);
            }

            // get the new json and path
            JObject editorJson = null;
            var     editorFile = string.Empty;

            if (editorValue.Value != null)
            {
                editorJson = editorValue.Value as JObject;
                if (editorJson != null && editorJson["src"] != null)
                {
                    editorFile = editorJson["src"].Value <string>();
                }
            }

            // ensure we have the required guids
            if (editorValue.AdditionalData.ContainsKey("cuid") == false || // for the content item
                editorValue.AdditionalData.ContainsKey("puid") == false)    // and the property type
            {
                throw new Exception("Missing cuid/puid additional data.");
            }
            var cuido = editorValue.AdditionalData["cuid"];
            var puido = editorValue.AdditionalData["puid"];

            if ((cuido is Guid) == false || (puido is Guid) == false)
            {
                throw new Exception("Invalid cuid/puid additional data.");
            }
            var cuid = (Guid)cuido;
            var puid = (Guid)puido;

            if (cuid == Guid.Empty || puid == Guid.Empty)
            {
                throw new Exception("Invalid cuid/puid additional data.");
            }

            // editorFile is empty whenever a new file is being uploaded
            // or when the file is cleared (in which case editorJson is null)
            // else editorFile contains the unchanged value

            var uploads = editorValue.AdditionalData.ContainsKey("files") && editorValue.AdditionalData["files"] is IEnumerable <ContentItemFile>;
            var files   = uploads ? ((IEnumerable <ContentItemFile>)editorValue.AdditionalData["files"]).ToArray() : new ContentItemFile[0];
            var file    = uploads ? files.FirstOrDefault() : null;

            if (file == null) // not uploading a file
            {
                // if editorFile is empty then either there was nothing to begin with,
                // or it has been cleared and we need to remove the file - else the
                // value is unchanged.
                if (string.IsNullOrWhiteSpace(editorFile) && string.IsNullOrWhiteSpace(currentPath) == false)
                {
                    _mediaFileSystem.DeleteFile(currentPath, true);
                    return(null); // clear
                }

                return(editorJson == null ? null : editorJson.ToString()); // unchanged
            }

            // process the file
            var filepath = editorJson == null ? null : ProcessFile(editorValue, file, currentPath, cuid, puid);

            // remove all temp files
            foreach (var f in files)
            {
                File.Delete(f.TempFilePath);
            }

            // remove current file if replaced
            if (currentPath != filepath && string.IsNullOrWhiteSpace(currentPath) == false)
            {
                _mediaFileSystem.DeleteFile(currentPath, true);
            }

            // update json and return
            if (editorJson == null)
            {
                return(null);
            }
            editorJson["src"] = filepath == null ? string.Empty : _mediaFileSystem.GetUrl(filepath);
            return(editorJson.ToString());
        }
示例#11
0
        public bool NewerThan(FileRef dst)
        {
            Debug.Assert(IOFile.Exists(this));

            return(!IOFile.Exists(dst) || IOFile.GetLastWriteTime(this) > IOFile.GetLastWriteTime(dst));
        }
示例#12
0
 public string GetContent()
 {
     return(IOFile.ReadAllText(this));
 }