/// <summary>
        /// Immediately save data.
        /// </summary>
        /// <returns></returns>
        public async Task ForceSave()
        {
            using (await _saveLock.LockAsync())
            {
                var chat = await _botClient.GetChatAsync(_saveResChatId);

                var prevPinnedMessage = chat.PinnedMessage;

                SaveStorageStateToFile();
                Message savedMsg = null;
                using (var readStream = File.OpenRead(_storageFilePath))
                {
                    savedMsg = await _botClient.SendDocumentAsync(
                        _saveResChatId,
                        new InputOnlineFile(readStream, FileResName),
                        caption : FileResName
                        );
                }
                await _botClient.PinChatMessageAsync(_saveResChatId, savedMsg.MessageId);

                if (_deletePreviousMessages)
                {
                    await _botClient.DeleteMessageAsync(_saveResChatId, prevPinnedMessage.MessageId);
                }
            }
        }
示例#2
0
        private static void Main(string[] args)
        {
            bool   removeDirectory;
            string temporaryDirectory = GetTemporaryDirectory(out removeDirectory);

            Console.WriteLine("Working directory: {0}", temporaryDirectory);

            try
            {
                IPackageRepository sourceRepository = PackageRepositoryFactory.Default.CreateRepository("https://www.nuget.org/api/v2/");
                PackageManager     packageManager   = new PackageManager(sourceRepository, temporaryDirectory);
                packageManager.PackageInstalled += HandlePackageInstalled;
                packageManager.InstallPackage("Microsoft.Bcl.Immutable", SemanticVersion.Parse("1.0.34"));
                packageManager.InstallPackage("System.Collections.Immutable", SemanticVersion.Parse("1.1.33-beta"));

                using (PEReader referenceAssembly = new PEReader(File.OpenRead(Path.Combine(temporaryDirectory, "Microsoft.Bcl.Immutable.1.0.34", "lib", "portable-net45+win8+wp8+wpa81", "System.Collections.Immutable.dll"))))
                {
                    using (PEReader newAssembly = new PEReader(File.OpenRead(Path.Combine(temporaryDirectory, "System.Collections.Immutable.1.1.33-beta", "lib", "portable-net45+win8+wp8+wpa81", "System.Collections.Immutable.dll"))))
                    {
                        Analyzer analyzer = new Analyzer(referenceAssembly, newAssembly, null);
                        analyzer.Run();
                    }
                }
            }
            finally
            {
                if (removeDirectory)
                {
                    Directory.Delete(temporaryDirectory, true);
                }
            }
        }
示例#3
0
        public override async Task <JobResult> Execute(DBContext db, SqlService sql, AppSettings settings)
        {
            var file = await db.UploadedFiles.AsQueryable().Where(f => f.Id == FileId).FirstOrDefaultAsync();

            using (var client = new FtpClient("storage.bunnycdn.com"))
            {
                client.Credentials = new NetworkCredential(settings.BunnyCDN_User, settings.BunnyCDN_Password);
                await client.ConnectAsync();

                using (var stream = File.OpenRead(Path.Combine("public", "files", file.MungedName)))
                {
                    await client.UploadAsync(stream, file.MungedName, progress : new Progress(file.MungedName));
                }

                await db.Jobs.InsertOneAsync(new Job
                {
                    Priority = Job.JobPriority.High,
                    Payload  = new IndexJob
                    {
                        Archive = new Archive
                        {
                            Name  = file.MungedName,
                            Size  = file.Size,
                            Hash  = file.Hash,
                            State = new HTTPDownloader.State
                            {
                                Url = file.Uri
                            }
                        }
                    }
                });
            }
            return(JobResult.Success());
        }
        public async Task SendResult(object sender, CaptureResponseEventArgs e)
        {
            if (e == null)
            {
                Logger.Warn("result is null, ignoring");
                return;
            }

            var message = e.Request.RequestContext as Message;

            if (message == null)
            {
                Logger.Error("Returned RequestContext is not a valid Telegram UserRequest object");
                return;
            }

            if (e.Attachments != null)
            {
                foreach (var filePath in e.Attachments)
                {
                    using (var fs = File.OpenRead(filePath))
                    {
                        var trial    = 0;
                        var succeed  = false;
                        var fileName = Path.GetFileName(filePath);
                        while (!succeed && trial < MaxUploadRetries)
                        {
                            try
                            {
                                Logger.Debug($"(retry {trial}/{MaxUploadRetries}) Uploading file \"{fileName}\"");
                                var inputOnlineFile = new InputOnlineFile(fs, fileName);
                                await _bot.SendDocumentAsync(message.Chat, inputOnlineFile,
                                                             replyToMessageId : message.MessageId);

                                succeed = true;
                            }
                            catch (ApiRequestException)
                            {
                                Logger.Warn("Telegram API timeout");
                                trial += 1;
                            }
                        }

                        if (!succeed)
                        {
                            Logger.Error("Unable to upload file \"{fileName}\"");
                            e.StatusText += "Unable to upload file \"{fileName}\".\n";
                        }
                    }
                }
            }

            Logger.Debug("Sending session information");
            await _bot.SendTextMessageAsync(
                message.Chat,
                $"<pre>{e}</pre>",
                replyToMessageId : message.MessageId,
                parseMode : ParseMode.Html
                );
        }
示例#5
0
        public static bool OpenWrapEnabled(string filePath)
        {
            if (!SysFile.Exists(filePath))
            {
                return(false);
            }
            var xmlDoc           = new XmlDocument();
            var namespaceManager = new XmlNamespaceManager(xmlDoc.NameTable);

            namespaceManager.AddNamespace("msbuild", MSBUILD_NS);

            using (var projectFileStream = SysFile.OpenRead(filePath))
                xmlDoc.Load(projectFileStream);
            var isOpenWrap = (from node in xmlDoc.SelectNodes(@"//msbuild:Import", namespaceManager).OfType <XmlElement>()
                              let attr = node.GetAttribute("Project")
                                         where attr != null && Regex.IsMatch(attr, @"OpenWrap\..*\.targets")
                                         select node).Any();

            var isDisabled =
                (
                    from node in xmlDoc.SelectNodes(@"//msbuild:OpenWrap-EnableVisualStudioIntegration", namespaceManager).OfType <XmlElement>()
                    let value = node.Value
                                where value != null && value.EqualsNoCase("false")
                                select node
                ).Any();

            return(isOpenWrap && !isDisabled);
        }
        private string ProcessFile(ContentPropertyData editorValue, ContentItemFile file, string currentPath, Guid cuid, Guid puid)
        {
            // process the file
            // no file, invalid file, reject change
            if (UploadFileTypeValidator.ValidateFileExtension(file.FileName) == false)
            {
                return(null);
            }

            // get the filepath
            // in case we are using the old path scheme, try to re-use numbers (bah...)
            var filepath = _mediaFileSystem.GetMediaPath(file.FileName, currentPath, cuid, puid); // fs-relative path

            using (var filestream = File.OpenRead(file.TempFilePath))
            {
                _mediaFileSystem.AddFile(filepath, filestream, true); // must overwrite!

                var ext = _mediaFileSystem.GetExtension(filepath);
                if (_mediaFileSystem.IsImageFile(ext))
                {
                    var preValues = editorValue.PreValues.FormatAsDictionary();
                    var sizes     = preValues.Any() ? preValues.First().Value.Value : string.Empty;
                    using (var image = Image.FromStream(filestream))
                        _mediaFileSystem.GenerateThumbnails(image, filepath, sizes);
                }

                // all related properties (auto-fill) are managed by ImageCropperPropertyEditor
                // when the content is saved (through event handlers)
            }

            return(filepath);
        }
示例#7
0
        public async Task Should_Set_Webhook_With_SelfSigned_Cert()
        {
            await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldSetWebhookWithCertificate);

            const string url            = "https://www.telegram.org/";
            const int    maxConnections = 5;

            using (var stream = File.OpenRead(Constants.FileNames.Certificate.PublicKey))
            {
                await BotClient.SetWebhookAsync(
                    url : url,
                    certificate : stream,
                    maxConnections : maxConnections,
                    allowedUpdates : new UpdateType[0]
                    );
            }

            WebhookInfo info = await BotClient.GetWebhookInfoAsync();

            Assert.Equal(url, info.Url);
            Assert.True(info.HasCustomCertificate);
            Assert.Equal(maxConnections, info.MaxConnections);
            Assert.Null(info.AllowedUpdates);

            await BotClient.DeleteWebhookAsync();
        }
示例#8
0
        private static async Task UploadToSharePoint(string path, string siteUrl, string requestUrl, string fieldName, string fieldValue)
        {
            using (var handler = new HttpClientHandler {
                UseDefaultCredentials = true
            })
            {
                using (var client = new HttpClient(handler))
                {
                    client.DefaultRequestHeaders.Add("Accept", "application/json; odata=verbose");

                    var contextInfo = await client.PostAsync(siteUrl + "_api/contextinfo", null);

                    var contextResponseContent = await contextInfo.Content.ReadAsStringAsync().ConfigureAwait(true);

                    JToken contextObj  = JsonConvert.DeserializeObject <dynamic>(contextResponseContent);
                    var    digestValue = contextObj["d"]["GetContextWebInformation"]["FormDigestValue"];
                    client.DefaultRequestHeaders.Add("X-RequestDigest", (string)digestValue);


                    var streamContent    = new StreamContent(File.OpenRead(path));
                    var byteArrayContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
                    byteArrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
                    HttpResponseMessage uploadResponse = await client.PostAsync(requestUrl, byteArrayContent).ConfigureAwait(true);

                    var uploadResponseContent = await uploadResponse.Content.ReadAsStringAsync().ConfigureAwait(true);

                    if (uploadResponse.IsSuccessStatusCode)
                    {
                        JToken        spFileObj = JsonConvert.DeserializeObject <dynamic>(uploadResponseContent);
                        ClientContext context   = new ClientContext(Regex.Replace(requestUrl, "/_api.*", "", RegexOptions.IgnoreCase));
                        var           web       = context.Web;
                        var           file      = web.GetFileByServerRelativeUrl((string)spFileObj.SelectToken("d.ServerRelativeUrl"));
                        var           fileItem  = file.ListItemAllFields;
                        context.Load(web);
                        context.Load(file);
                        context.Load(fileItem);
                        context.ExecuteQuery();

                        var wasCheckedOut = file.CheckOutType != CheckOutType.None;
                        if (!wasCheckedOut)
                        {
                            file.CheckOut();
                        }


                        fileItem.ParseAndSetFieldValue(fieldName, fieldValue);

                        fileItem.Update();
                        if (!wasCheckedOut)
                        {
                            file.CheckIn(string.Empty, CheckinType.OverwriteCheckIn);
                        }

                        context.ExecuteQuery();
                    }
                }
            }
        }
示例#9
0
        protected FileStreamResult Pdf(string fileName,
                                       string fileDownloadName)
        {
            var resumeFile = IOFile.OpenRead(fileName);

            return(File(resumeFile,
                        "application/pdf",
                        fileDownloadName));
        }
示例#10
0
        public async Task <IActionResult> GetProfilePicture()
        {
            var userImageDestination = string.Format(
                $"{UserImageDestination}_optimized.jpg",
                this.User.Identity.Name);

            await using var file = FileSystem.OpenRead(userImageDestination);

            return(this.File(file, ImageContentType));
        }
示例#11
0
            public void Run()
            {
                // Gets MediaPickerActivity's private members
                _imageAvailableHandler._mediaPickerActivity.Accept(_imageAvailableHandler);
                _imageAvailableHandler._createMediaFile();

                StoreImage();

                Task.Run(NotifyImageStored);

                #region Local functions

                void StoreImage()                 // Stores captured image to specified location
                {
                    ByteBuffer buffer = _image.GetPlanes()[0].Buffer;

                    byte[] bytes = new byte[buffer.Remaining()];
                    buffer.Get(bytes);
                    using (var fileOutputStream =
                               new FileOutputStream(_imageAvailableHandler._convertUriToPath(_imageAvailableHandler._newMediaFileUri), true))
                    {
                        try
                        {
                            fileOutputStream.Write(bytes);
                        }
                        catch (IOException e)
                        {
                            e.PrintStackTrace();
                        }
                        finally
                        {
                            _image.Close();
                        }
                    }
                }

                async Task NotifyImageStored()
                {
                    MediaPickedEventArgs args = GetMediaFile();

                    await Task.Delay(1).ConfigureAwait(false);

                    _imageAvailableHandler._onMediaPicked(args);
                }

                MediaPickedEventArgs GetMediaFile()
                {
                    string albumPath  = _imageAvailableHandler._newMediaFileUri.ToString(),
                           resultPath = _imageAvailableHandler._convertUriToPath(_imageAvailableHandler._newMediaFileUri);

                    if (resultPath != null && File.Exists(resultPath))
                    {
                        var mediaFile = new MediaFile(resultPath, () => File.OpenRead(resultPath), albumPath);
                        return(new MediaPickedEventArgs(default, false, mediaFile));
示例#12
0
        public override async Task <JobResult> Execute(SqlService sql, AppSettings settings)
        {
            int retries = 0;

TOP:
            var file = await sql.UploadedFileById(FileId);

            if (settings.BunnyCDN_User == "TEST" && settings.BunnyCDN_Password == "TEST")
            {
                return(JobResult.Success());
            }

            using (var client = new FtpClient("storage.bunnycdn.com"))
            {
                client.Credentials = new NetworkCredential(settings.BunnyCDN_User, settings.BunnyCDN_Password);
                await client.ConnectAsync();

                using (var stream = File.OpenRead(Path.Combine("public", "files", file.MungedName)))
                {
                    try
                    {
                        await client.UploadAsync(stream, file.MungedName, progress : new Progress((RelativePath)file.MungedName));
                    }
                    catch (Exception ex)
                    {
                        if (retries > 10)
                        {
                            throw;
                        }
                        Utils.Log(ex.ToString());
                        Utils.Log("Retrying FTP Upload");
                        retries++;
                        goto TOP;
                    }
                }

                await sql.EnqueueJob(new Job
                {
                    Priority = Job.JobPriority.High,
                    Payload  = new IndexJob
                    {
                        Archive = new Archive(new HTTPDownloader.State(file.Uri))
                        {
                            Name = file.MungedName,
                            Size = file.Size,
                            Hash = file.Hash,
                        }
                    }
                });
            }
            return(JobResult.Success());
        }
示例#13
0
        public static ReadOnlyCollection <Message> AnalyzeAssemblies(string referenceAssemblyFile, string newAssemblyFile)
        {
            using (PEReader referenceAssembly = new PEReader(File.OpenRead(referenceAssemblyFile)))
            {
                using (PEReader newAssembly = new PEReader(File.OpenRead(newAssemblyFile)))
                {
                    TestMessageLogger logger   = new TestMessageLogger();
                    Analyzer          analyzer = new Analyzer(referenceAssembly, newAssembly, logger);
                    analyzer.Run();

                    return(logger.RawMessages);
                }
            }
        }
示例#14
0
        private static void Main(string[] args)
        {
            string assemblyPath = args[0];

            using (PEReader peReader = new PEReader(File.OpenRead(assemblyPath), PEStreamOptions.PrefetchMetadata))
            {
                ISet <AssemblyName> exposedDependencies = new HashSet <AssemblyName>(new AssemblyNameEqualityComparer());

                MetadataReader metadataReader = peReader.GetMetadataReader();
                foreach (var type in metadataReader.TypeDefinitions)
                {
                    TypeDefinition typeDefinition = metadataReader.GetTypeDefinition(type);
                    if (!IsExposedType(metadataReader, typeDefinition))
                    {
                        continue;
                    }

                    Console.WriteLine("Exposed type: {0}", GetFullName(metadataReader, typeDefinition));

                    CheckType(metadataReader, typeDefinition, exposedDependencies);

                    foreach (var eventDefinitionHandle in typeDefinition.GetEvents())
                    {
                        CheckEvent(metadataReader, metadataReader.GetEventDefinition(eventDefinitionHandle), exposedDependencies);
                    }

                    foreach (var methodDefinitionHandle in typeDefinition.GetMethods())
                    {
                        CheckMethod(metadataReader, metadataReader.GetMethodDefinition(methodDefinitionHandle), exposedDependencies);
                    }

                    foreach (var propertyDefinitionHandle in typeDefinition.GetProperties())
                    {
                        CheckProperty(metadataReader, metadataReader.GetPropertyDefinition(propertyDefinitionHandle), exposedDependencies);
                    }

                    foreach (var fieldDefinitionHandle in typeDefinition.GetFields())
                    {
                        CheckField(metadataReader, metadataReader.GetFieldDefinition(fieldDefinitionHandle), exposedDependencies);
                    }
                }

                Console.WriteLine();
                Console.WriteLine("Exposed Dependencies ({0}):", Path.GetFileName(args[0]));
                foreach (AssemblyName dependency in exposedDependencies.OrderBy(i => i.FullName, StringComparer.OrdinalIgnoreCase))
                {
                    Console.WriteLine("  {0}", dependency.FullName);
                }
            }
        }
示例#15
0
        /// <summary>
        /// Проверка изображения на допустимость к загрузке
        /// </summary>
        /// <param name="imagePath"></param>
        public void CheckDownloadingImage(string imagePath)
        {
            //Проверка загружаемого изображения
            SysImage image;

            using (var imgStream = File.OpenRead(imagePath))
            {
                image = SysImage.FromStream(imgStream);
            }

            if (image.Height < 700 || image.Width < 1270 || image.Height > image.Width)
            {
                throw new ImageException("Принимаются изображения с размерами не меньше чем 1270 пикселей в ширину и 700 пикселей в высоту.");
            }
        }
示例#16
0
        public void CanSyncDTest()
        {
            this.Execute("/d", () =>
            {
                var hashAlgorithm = new QuickXorHash();

                Assert.True(File.Exists("/d".ToAbsolutePath(_driveHive.LocalDrivePath)), "File does not exist.");
                Assert.True(File.Exists("/d".ToAbsolutePath(_driveHive.RemoteDrivePath)), "File does not exist.");

                using (var stream = File.OpenRead("/d".ToAbsolutePath(_driveHive.LocalDrivePath)))
                {
                    Assert.True(Convert.ToBase64String(hashAlgorithm.ComputeHash(stream)) == Utils.DriveItemPool["/d1"].QuickXorHash());
                }
            });
        }
示例#17
0
        /** Load full path name .st file relative to root by prefix */
        public virtual CompiledTemplate LoadTemplateFile(string prefix, string unqualifiedFileName)
        {
            if (Path.IsPathRooted(unqualifiedFileName))
            {
                throw new ArgumentException();
            }

            if (Verbose)
            {
                Console.WriteLine("loadTemplateFile({0}) in groupdir from {1} prefix={2}", unqualifiedFileName, root, prefix);
            }

            string templateName = Path.ChangeExtension(unqualifiedFileName, null);
            Uri    f;

            try
            {
                f = new Uri(root.LocalPath + prefix + unqualifiedFileName);
            }
            catch (UriFormatException me)
            {
                ErrorManager.RuntimeError(null, ErrorType.INVALID_TEMPLATE_NAME, me, Path.Combine(root.LocalPath, unqualifiedFileName));
                return(null);
            }

            ANTLRReaderStream fs = null;

            try
            {
                fs      = new ANTLRReaderStream(new StreamReader(File.OpenRead(f.LocalPath), Encoding));
                fs.name = unqualifiedFileName;
            }
            catch (IOException)
            {
                if (Verbose)
                {
                    Console.WriteLine("{0}/{1} doesn't exist", root, unqualifiedFileName);
                }

                //errMgr.IOError(null, ErrorType.NO_SUCH_TEMPLATE, ioe, unqualifiedFileName);
                return(null);
            }

            return(LoadTemplateFile(prefix, unqualifiedFileName, fs));
        }
示例#18
0
        protected void loadSources(DirectoryInfo directory, string filter, Encoding encoding, bool recursive, ICollection <ICharStream> result)
        {
            Debug.Assert(directory.Exists);

            FileInfo[] sources = directory.GetFiles(filter);
            foreach (FileInfo file in sources)
            {
                var         stream = new StreamReader(File.OpenRead(file.FullName), encoding);
                ICharStream input  = new AntlrInputStream(stream);
                result.Add(input);
            }

            if (recursive)
            {
                DirectoryInfo[] children = directory.GetDirectories();
                foreach (DirectoryInfo child in children)
                {
                    loadSources(child, filter, encoding, true, result);
                }
            }
        }
        private string ProcessFile(ContentPropertyData editorValue, ContentItemFile file, string currentPath, Guid cuid, Guid puid)
        {
            // process the file
            // no file, invalid file, reject change
            if (UploadFileTypeValidator.ValidateFileExtension(file.FileName) == false)
            {
                return(null);
            }

            // get the filepath
            // in case we are using the old path scheme, try to re-use numbers (bah...)
            var filepath = _mediaFileSystem.GetMediaPath(file.FileName, currentPath, cuid, puid); // fs-relative path

            using (var filestream = File.OpenRead(file.TempFilePath))
            {
                _mediaFileSystem.AddFile(filepath, filestream, true); // must overwrite!

                var ext = _mediaFileSystem.GetExtension(filepath);
                if (_mediaFileSystem.IsImageFile(ext) && ext != ".svg")
                {
                    var preValues = editorValue.PreValues.FormatAsDictionary();
                    var sizes     = preValues.Any() ? preValues.First().Value.Value : string.Empty;
                    try
                    {
                        using (var image = Image.FromStream(filestream))
                            _mediaFileSystem.GenerateThumbnails(image, filepath, sizes);
                    }
                    catch (ArgumentException ex)
                    {
                        // send any argument errors caused by the thumbnail generation to the log instead of failing miserably
                        LogHelper.WarnWithException <ImageCropperPropertyValueEditor>("Could not extract image thumbnails.", ex);
                    }
                }

                // all related properties (auto-fill) are managed by ImageCropperPropertyEditor
                // when the content is saved (through event handlers)
            }

            return(filepath);
        }
示例#20
0
        private string ProcessFile(ContentPropertyData editorValue, ContentPropertyFile file, string currentPath, Guid cuid, Guid puid)
        {
            // process the file
            // no file, invalid file, reject change
            if (UploadFileTypeValidator.ValidateFileExtension(file.FileName) == false)
            {
                return(null);
            }

            // get the filepath
            // in case we are using the old path scheme, try to re-use numbers (bah...)
            var filepath = _mediaFileSystem.GetMediaPath(file.FileName, currentPath, cuid, puid); // fs-relative path

            using (var filestream = File.OpenRead(file.TempFilePath))
            {
                // TODO: Here it would make sense to do the auto-fill properties stuff but the API doesn't allow us to do that right
                // since we'd need to be able to return values for other properties from these methods

                _mediaFileSystem.AddFile(filepath, filestream, true); // must overwrite!
            }

            return(filepath);
        }
示例#21
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);
        }
        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);
            }
        }
示例#23
0
        static async void Bot_OnMessage(object sender, MessageEventArgs e)
        {
            try
            {
                Message         message = new Message();
                ParseMessage    pm      = new ParseMessage();
                PasteDotaThread pdt     = new PasteDotaThread();
                pm.ParseUserMessage(message.ReplyToMessage.Text);
                switch (pm.ExistBotCommands.Find(x => x.Equals(pm.BotCommand)))
                {
                case "/paste":
                    pdt.GetPasteFromNotepad(pm);
                    await botClient.SendTextMessageAsync(chatId : e.Message.Chat,
                                                         text : pdt.MessageText, replyToMessageId : e.Message.MessageId);

                    break;

                case "/d4":
                case "/d8":
                case "/d10":
                case "/d12":
                case "/d20":
                case "/d100":
                    var        cube = DndCaluclation.GetCube(pm.BotCommand);
                    DNDResults dndr = new DNDResults();
                    dndr.SomeResult(pm, cube);
                    await botClient.SendTextMessageAsync(chatId : e.Message.Chat, text : dndr.TextMessage,
                                                         replyToMessageId : e.Message.MessageId, parseMode : ParseMode.Markdown);

                    dndr.FinalResult(pm, cube);
                    await botClient.SendTextMessageAsync(chatId : e.Message.Chat, text : dndr.TextMessage,
                                                         replyToMessageId : e.Message.MessageId, parseMode : ParseMode.Markdown);

                    break;

                case "/otec":
                    pdt.GetPasteFromOtecNotepad(pm);
                    await botClient.SendTextMessageAsync(chatId : e.Message.Chat,
                                                         text : pdt.MessageText, replyToMessageId : e.Message.MessageId);

                    break;

                case "/help":
                    await botClient.SendTextMessageAsync(chatId : e.Message.Chat,
                                                         text : "Напиши вот этому человеку @shadowmorex", replyToMessageId : e.Message.MessageId);

                    break;

                case "/fresco":
                    Quotes quotes = new Quotes(pm);
                    await using (var file = File.OpenRead(quotes.PathToFile))
                    {
                        var iof = new InputOnlineFile(file, "quotes.bpm");
                        await botClient.SendPhotoAsync(e.Message.Chat, iof, "Все факты достоверны и тщательно проверены администрацией",
                                                       replyToMessageId : e.Message.MessageId);
                    }
                    break;

                case "/test":
                    await using (var file =
                                     File.OpenRead(@"D:\projects\Valentin_Core\Valentin_Core\resources\img\fresco.jpg"))
                    {
                        var iofa = new InputOnlineFile(file, "shit.png");
                        await botClient.SendPhotoAsync(e.Message.Chat, iofa, "иди нахуй",
                                                       replyToMessageId : e.Message.MessageId);
                    }

                    break;
                }
            }
            catch (Exception er)
            {
                await botClient.SendPhotoAsync(chatId : e.Message.Chat, photo :
                                               "http://reactionimage.org/img/gallery/3926393515.jpg",
                                               replyToMessageId : e.Message.MessageId,
                                               caption : "Какая-то хуйня, больше так не делай.\n" +
                                               "Если думаешь, что проблема в боте\n" +
                                               "то вызови автора командой */help*",
                                               parseMode : ParseMode.Markdown);
            }
        }