public static void UsingTextBuilderAndFragment()
        {
            // ExStart:UsingTextBuilderAndFragment
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();

            // Create Document instance
            Document pdfDocument = new Document();
            // Add page to pages collection of Document
            Page page = pdfDocument.Pages.Add();
            // Create TextBuilder instance
            TextBuilder builder = new TextBuilder(pdfDocument.Pages[1]);
            // Create text fragment instance with sample contents
            TextFragment wideFragment = new TextFragment("Text with increased character spacing");
            wideFragment.TextState.ApplyChangesFrom(new TextState("Arial", 12));
            // Specify character spacing for TextFragment
            wideFragment.TextState.CharacterSpacing = 2.0f;
            // Specify the position of TextFragment
            wideFragment.Position = new Position(100, 650);
            // Append TextFragment to TextBuilder instance
            builder.AppendText(wideFragment);
            dataDir = dataDir + "CharacterSpacingUsingTextBuilderAndFragment_out.pdf";
            // Save resulting PDF document.
            pdfDocument.Save(dataDir);
            // ExEnd:UsingTextBuilderAndFragment
            Console.WriteLine("\nCharacter spacing specified successfully using Text builder and fragment.\nFile saved at " + dataDir); 
        }
Ejemplo n.º 2
0
        public static void AddUnderlineText()
        {
            // ExStart:AddUnderlineText
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();

            // Create documentation object
            Document pdfDocument = new Document();
            // Add age page to PDF document
            pdfDocument.Pages.Add();
            // Create TextBuilder for first page
            TextBuilder tb = new TextBuilder(pdfDocument.Pages[1]);
            // TextFragment with sample text
            TextFragment fragment = new TextFragment("Test message");
            // Set the font for TextFragment
            fragment.TextState.Font = FontRepository.FindFont("Arial");
            fragment.TextState.FontSize = 10;
            // Set the formatting of text as Underline
            fragment.TextState.Underline = true;
            // Specify the position where TextFragment needs to be placed
            fragment.Position = new Position(10, 800);
            // Append TextFragment to PDF file
            tb.AppendText(fragment);

            dataDir = dataDir + "AddUnderlineText_out.pdf";

            // Save resulting PDF document.
            pdfDocument.Save(dataDir);
            // ExEnd:AddUnderlineText
            Console.WriteLine("\nUnderline text added successfully.\nFile saved at " + dataDir); 
        }
Ejemplo n.º 3
0
        public static void Run()
        {
            try
            {
                // ExStart:TextToPDF
                // The path to the documents directory.
                string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();
                // Read the source text file
                TextReader tr = new StreamReader(dataDir + "log.txt");

                // Instantiate a Document object by calling its empty constructor
                Document doc = new Document();

                // Add a new page in Pages collection of Document
                Page page = doc.Pages.Add();

                // Create an instance of TextFragmet and pass the text from reader object to its constructor as argument
                TextFragment text = new TextFragment(tr.ReadToEnd());
                // Text.TextState.Font = FontRepository.FindFont("Arial Unicode MS");

                // Add a new text paragraph in paragraphs collection and pass the TextFragment object
                page.Paragraphs.Add(text);

                // Save resultant PDF file
                doc.Save(dataDir + "TexttoPDF_out.pdf"); 
                // ExEnd:TextToPDF
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 4
0
            public void it_should_return_same_fragment_when_pass_non_element_fragment_with_table_name()
            {
                var fragment = new TextFragment {Name = "table"};

                var result = XFormHelper.CleanupXFormHtmlMarkup(fragment);

                result.Should().BeSameAs(fragment);
                result.Name.Should().Be(fragment.Name);
            }
Ejemplo n.º 5
0
        public static void Run()
        {
            // ExStart:AddTOC
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();

            // Load an existing PDF files
            Document doc = new Document(dataDir + "AddTOC.pdf");

            // Get access to first page of PDF file
            Page tocPage = doc.Pages.Insert(1);

            // Create object to represent TOC information
            TocInfo tocInfo = new TocInfo();
            TextFragment title = new TextFragment("Table Of Contents");
            title.TextState.FontSize = 20;
            title.TextState.FontStyle = FontStyles.Bold;

            // Set the title for TOC
            tocInfo.Title = title;
            tocPage.TocInfo = tocInfo;

            // Create string objects which will be used as TOC elements
            string[] titles = new string[4];
            titles[0] = "First page";
            titles[1] = "Second page";
            titles[2] = "Third page";
            titles[3] = "Fourth page";
            for (int i = 0; i < 2; i++)
            {
                // Create Heading object
                Aspose.Pdf.Heading heading2 = new Aspose.Pdf.Heading(1);
                TextSegment segment2 = new TextSegment();
                heading2.TocPage = tocPage;
                heading2.Segments.Add(segment2);

                // Specify the destination page for heading object
                heading2.DestinationPage = doc.Pages[i + 2];

                // Destination page
                heading2.Top = doc.Pages[i + 2].Rect.Height;

                // Destination coordinate
                segment2.Text = titles[i];

                // Add heading to page containing TOC
                tocPage.Paragraphs.Add(heading2);
            }
            dataDir = dataDir + "TOC_out.pdf";
            // Save the updated document
            doc.Save(dataDir);
            // ExEnd:AddTOC
            Console.WriteLine("\nTOC added successfully to an existing PDF.\nFile saved at " + dataDir);
        }
Ejemplo n.º 6
0
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Tables();

            // Create directory if it is not already present.
            bool IsExists = System.IO.Directory.Exists(dataDir);
            if (!IsExists)
                System.IO.Directory.CreateDirectory(dataDir);


            //Instntiate the Document object by calling its empty constructor
            Document doc = new Document();
            Page page = doc.Pages.Add();
            //Instantiate a table object
            Aspose.Pdf.Table tab1 = new Aspose.Pdf.Table();
            //Add the table in paragraphs collection of the desired section
            page.Paragraphs.Add(tab1);
            //Set with column widths of the table
            tab1.ColumnWidths = "50 50 50";
            //Set default cell border using BorderInfo object
            tab1.DefaultCellBorder = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, 0.1F);
            //Set table border using another customized BorderInfo object
            tab1.Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, 1F);
            //Create MarginInfo object and set its left, bottom, right and top margins
            Aspose.Pdf.MarginInfo margin = new Aspose.Pdf.MarginInfo();
            margin.Top = 5f;
            margin.Left = 5f;
            margin.Right = 5f;
            margin.Bottom = 5f;
            //Set the default cell padding to the MarginInfo object
            tab1.DefaultCellPadding = margin;
            //Create rows in the table and then cells in the rows
            Aspose.Pdf.Row row1 = tab1.Rows.Add();
            row1.Cells.Add("col1");
            row1.Cells.Add("col2");
            row1.Cells.Add();
            TextFragment mytext = new TextFragment("col3 with large text string");
            //row1.Cells.Add("col3 with large text string to be placed inside cell");
            row1.Cells[2].Paragraphs.Add(mytext);
            row1.Cells[2].IsWordWrapped = false;
            //row1.Cells[2].Paragraphs[0].FixedWidth= 80;
            Aspose.Pdf.Row row2 = tab1.Rows.Add();
            row2.Cells.Add("item1");
            row2.Cells.Add("item2");
            row2.Cells.Add("item3");
            //Save the Pdf
            doc.Save(dataDir+ "MarginsOrPadding_out.pdf");
            
            
        }
Ejemplo n.º 7
0
        public static void Main(string[] args)
        {
            // The path to the documents directory.
            string dataDir = Path.GetFullPath("../../../Data/");

            // Load an existing PDF files
            Document doc = new Document(dataDir + "input.pdf");

            // Get access to first page of PDF file
            Page tocPage = doc.Pages.Insert(1);

            // Create object to represent TOC information
            TocInfo tocInfo = new TocInfo();
            TextFragment title = new TextFragment("Table Of Contents");
            title.TextState.FontSize = 20;
            title.TextState.FontStyle = FontStyles.Bold;

            // Set the title for TOC
            tocInfo.Title = title;
            tocPage.TocInfo = tocInfo;

            // Create string objects which will be used as TOC elements
            string[] titles = new string[4];
            titles[0] = "First page";
            titles[1] = "Second page";
            titles[2] = "Third page";
            titles[3] = "Fourth page";
            for (int i = 0; i < 2; i++)
            {
                // Create Heading object
                Aspose.Pdf.Heading heading2 = new Aspose.Pdf.Heading(1);
                TextSegment segment2 = new TextSegment();
                heading2.TocPage = tocPage;
                heading2.Segments.Add(segment2);

                // Specify the destination page for heading object
                heading2.DestinationPage = doc.Pages[i + 2];

                // Destination page
                heading2.Top = doc.Pages[i + 2].Rect.Height;

                // Destination coordinate
                segment2.Text = titles[i];

                // Add heading to page containing TOC
                tocPage.Paragraphs.Add(heading2);
            }
            // Save the updated document
            doc.Save(dataDir + "TOC_Output.pdf");
        }
Ejemplo n.º 8
0
        public static void Run()
        {
            // ExStart:AddText
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();

            // Open document
            Document pdfDocument = new Document(dataDir + "input.pdf");

            // Get particular page
            Page pdfPage = (Page)pdfDocument.Pages[1];

            // Create text fragment
            TextFragment textFragment = new TextFragment("main text");
            textFragment.Position = new Position(100, 600);

            // Set text properties
            textFragment.TextState.FontSize = 12;
            textFragment.TextState.Font = FontRepository.FindFont("TimesNewRoman");
            textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray);
            textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Red);

            // Create TextBuilder object
            TextBuilder textBuilder = new TextBuilder(pdfPage);

            // Append the text fragment to the PDF page
            textBuilder.AppendText(textFragment);
            
            dataDir = dataDir + "AddText_out.pdf";

            // Save resulting PDF document.
            pdfDocument.Save(dataDir);
            // ExEnd:AddText
            Console.WriteLine("\nText added successfully.\nFile saved at " + dataDir);

            AddUnderlineText();
            AddingBorderAroundAddedText();
            AddTextUsingTextParagraph();
            AddHyperlinkToTextSegment();
            OTFFont();
            AddStrikeOutText();
        }
        public static void CustomLineStyleForFootNote()
        {
            // ExStart:CustomLineStyleForFootNote
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();

            // Create Document instance
            Document doc = new Document();
            // Add page to pages collection of PDF
            Page page = doc.Pages.Add();
            // Create GraphInfo object
            Aspose.Pdf.GraphInfo graph = new Aspose.Pdf.GraphInfo();
            // Set line width as 2
            graph.LineWidth = 2;
            // Set the color for graph object
            graph.Color = Aspose.Pdf.Color.Red;
            // Set dash array value as 3
            graph.DashArray = new int[] { 3 };
            // Set dash phase value as 1
            graph.DashPhase = 1;
            // Set footnote line style for page as graph
            page.NoteLineStyle = graph;
            // Create TextFragment instance
            TextFragment text = new TextFragment("Hello World");
            // Set FootNote value for TextFragment
            text.FootNote = new Note("foot note for test text 1");
            // Add TextFragment to paragraphs collection of first page of document
            page.Paragraphs.Add(text);
            // Create second TextFragment
            text = new TextFragment("Aspose.Pdf for .NET");
            // Set FootNote for second text fragment
            text.FootNote = new Note("foot note for test text 2");
            // Add second text fragment to paragraphs collection of PDF file
            page.Paragraphs.Add(text);

            dataDir = dataDir + "CustomLineStyleForFootNote_out.pdf";

            // Save resulting PDF document.
            doc.Save(dataDir);
            // ExEnd:CustomLineStyleForFootNote
            Console.WriteLine("\nCustom line style defined successfully.\nFile saved at " + dataDir);
        }
        public static void Run()
        {
            // ExStart:CustomTabStops
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();

            Document _pdfdocument = new Document();
            Page page = _pdfdocument.Pages.Add();

            Aspose.Pdf.Text.TabStops ts = new Aspose.Pdf.Text.TabStops();
            Aspose.Pdf.Text.TabStop ts1 = ts.Add(100);
            ts1.AlignmentType = TabAlignmentType.Right;
            ts1.LeaderType = TabLeaderType.Solid;
            Aspose.Pdf.Text.TabStop ts2 = ts.Add(200);
            ts2.AlignmentType = TabAlignmentType.Center;
            ts2.LeaderType = TabLeaderType.Dash;
            Aspose.Pdf.Text.TabStop ts3 = ts.Add(300);
            ts3.AlignmentType = TabAlignmentType.Left;
            ts3.LeaderType = TabLeaderType.Dot;

            TextFragment header = new TextFragment("This is a example of forming table with TAB stops", ts);
            TextFragment text0 = new TextFragment("#$TABHead1 #$TABHead2 #$TABHead3", ts);
            
            TextFragment text1 = new TextFragment("#$TABdata11 #$TABdata12 #$TABdata13", ts);
            TextFragment text2 = new TextFragment("#$TABdata21 ", ts);
            text2.Segments.Add(new TextSegment("#$TAB"));
            text2.Segments.Add(new TextSegment("data22 "));
            text2.Segments.Add(new TextSegment("#$TAB"));
            text2.Segments.Add(new TextSegment("data23"));

            page.Paragraphs.Add(header);
            page.Paragraphs.Add(text0);
            page.Paragraphs.Add(text1);
            page.Paragraphs.Add(text2);

            dataDir = dataDir + "CustomTabStops_out.pdf";
            _pdfdocument.Save(dataDir);
            // ExEnd:CustomTabStops            
            Console.WriteLine("\nCustom tab stops setup successfully.\nFile saved at " + dataDir);
        }
        public static void Run()
        {
            // ExStart:CreateLocalHyperlink
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_LinksActions();
            
            // Create Document instance
            Document doc = new Document();
            // Add page to pages collection of PDF file
            Page page = doc.Pages.Add();
            // Create Text Fragment instance
            Aspose.Pdf.Text.TextFragment text = new Aspose.Pdf.Text.TextFragment("link page number test to page 7");
            // Create local hyperlink instance
            Aspose.Pdf.LocalHyperlink link = new Aspose.Pdf.LocalHyperlink();
            // Set target page for link instance
            link.TargetPageNumber = 7;
            // Set TextFragment hyperlink
            text.Hyperlink = link;
            // Add text to paragraphs collection of Page
            page.Paragraphs.Add(text);
            // Create new TextFragment instance
            text = new TextFragment("link page number test to page 1");
            // TextFragment should be added over new page
            text.IsInNewPage = true;
            // Create another local hyperlink instance
            link = new LocalHyperlink();
            // Set Target page for second hyperlink
            link.TargetPageNumber = 1;
            // Set link for second TextFragment
            text.Hyperlink = link;
            // Add text to paragraphs collection of page object
            page.Paragraphs.Add(text);    

            dataDir = dataDir + "CreateLocalHyperlink_out.pdf";
            // Save updated document
            doc.Save(dataDir);
            // ExEnd:CreateLocalHyperlink
            Console.WriteLine("\nLocal hyperlink created successfully.\nFile saved at " + dataDir);            
        }
        public static void Run()
        {
            // ExStart:TextAndImageAsParagraph
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
            // Instantiate Document instance
            Document doc = new Document();
            // Add page to pages collection of Document instance
            Page page = doc.Pages.Add();
            // Create TextFragmnet
            TextFragment text = new TextFragment("Hello World.. ");
            // Add text fragment to paragraphs collection of Page object
            page.Paragraphs.Add(text);
            // Create an image instance
            Aspose.Pdf.Image image = new Aspose.Pdf.Image();
            // Set image as inline paragraph so that it appears right after 
            // The previous paragraph object (TextFragment)
            image.IsInLineParagraph = true;
            // Specify image file path 
            image.File = dataDir + "aspose-logo.jpg";
            // Set image Height (optional)
            image.FixHeight = 30;
            // Set Image Width (optional)
            image.FixWidth = 100;
            // Add image to paragraphs collection of page object
            page.Paragraphs.Add(image);
            // Re-initialize TextFragment object with different contents
            text = new TextFragment(" Hello Again..");
            // Set TextFragment as inline paragraph
            text.IsInLineParagraph = true;
            // Add newly created TextFragment to paragraphs collection of page
            page.Paragraphs.Add(text);

            dataDir = dataDir + "TextAndImageAsParagraph_out.pdf";
            doc.Save(dataDir);
            // ExEnd:TextAndImageAsParagraph
            Console.WriteLine("\nText and image added successfully as an inline paragraphs.\nFile saved at " + dataDir);
        }
        public static void Run()
        {
            // ExStart:AddTransparentText
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();

            // Create Document instance
            Document doc = new Document();
            // Create page to pages collection of PDF file
            Aspose.Pdf.Page page = doc.Pages.Add();

            // Create Graph object 
            Aspose.Pdf.Drawing.Graph canvas = new Aspose.Pdf.Drawing.Graph(100, 400);
            // Create rectangle instance with certain dimensions
            Aspose.Pdf.Drawing.Rectangle rect = new Aspose.Pdf.Drawing.Rectangle(100, 100, 400, 400);
            // Create color object from Alpha color channel
            rect.GraphInfo.FillColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.FromArgb(128, System.Drawing.Color.FromArgb(12957183)));
            // Add rectanlge to shapes collection of Graph object
            canvas.Shapes.Add(rect);
            // Add graph object to paragraphs collection of page object
            page.Paragraphs.Add(canvas);
            // Set value to not change position for graph object
            canvas.IsChangePosition = false;

            // Create TextFragment instance with sample value
            TextFragment text = new TextFragment("transparent text transparent text transparent text transparent text transparent text transparent text transparent text transparent text transparent text transparent text transparent text transparent text transparent text transparent text transparent text transparent text ");
            // Create color object from Alpha channel
            Aspose.Pdf.Color color = Aspose.Pdf.Color.FromArgb(30, 0, 255, 0);
            // Set color information for text instance
            text.TextState.ForegroundColor = color;
            // Add text to paragraphs collection of page instance
            page.Paragraphs.Add(text);

            dataDir = dataDir + "AddTransparentText_out.pdf";
            doc.Save(dataDir);
            // ExEnd:AddTransparentText            
            Console.WriteLine("\nTransparent text added successfully.\nFile saved at " + dataDir);
        }
Ejemplo n.º 14
0
 protected void AddHeading(Aspose.Pdf.Page page, string strValue, float fontSize, bool IsUnderline)
 {
     try
     {
         //add a empty line in the page...
         page.Paragraphs.Add(new TextFragment(" "));
         //create a new text fragment...
         TextFragment txtHeading1 = new TextFragment(strValue);
         txtHeading1.TextState.FontSize = fontSize;
         txtHeading1.TextState.FontStyle = FontStyles.Bold;
         if (IsUnderline)
         {
             txtHeading1.TextState.Underline = true;
         }
         //add text fragment in the paragraph of the page...
         page.Paragraphs.Add(txtHeading1);
         //add empty line in the page...
         page.Paragraphs.Add(new TextFragment(" "));
     }
     catch (Exception exp)
     {
         msg.Text = "<div class='alert alert-danger'><button data-dismiss='alert' class='close' type='button'>×</button>Exception Occured:" + exp.Message + "</div>";
     }
 }
Ejemplo n.º 15
0
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task Add(ClientWhitelist data)
        {
            await DBTransactionHelper.SqlTransactionWorkAsync(DBTypes.SqlServer, false, false, _dbConnectionFactory.CreateAllForWhitelistPolicy(), async (conn, transaction) =>
            {
                SqlTransaction sqlTran = null;
                if (transaction != null)
                {
                    sqlTran = (SqlTransaction)transaction;
                }
                using (SqlCommand command = new SqlCommand()
                {
                    Connection = (SqlConnection)conn,
                    CommandType = CommandType.Text,
                    Transaction = sqlTran,
                })
                {
                    SqlParameter parameter;
                    if (data.ID == Guid.Empty)
                    {
                        command.CommandText = @"INSERT INTO [dbo].[ClientWhiteList] 
                                                    ([id] ,[systemname] ,[systemsecret] ,[signatureexpire] ,[createtime] ,[modifytime]) 
                                                VALUES 
                                                    (default ,@systemname ,@systemsecret ,@signatureexpire , GETUTCDATE() , GETUTCDATE());
                                                select @newid =[id] from [dbo].[ClientWhiteList] where [sequence] = SCOPE_IDENTITY()";
                        parameter           = new SqlParameter("@newid", SqlDbType.UniqueIdentifier)
                        {
                            Direction = ParameterDirection.Output
                        };
                        command.Parameters.Add(parameter);
                    }
                    else
                    {
                        command.CommandText = @"INSERT INTO [dbo].[ClientWhiteList] 
                                                    ([id] ,[systemname] ,[systemsecret] ,[signatureexpire] ,[createtime] ,[modifytime]) 
                                                VALUES 
                                                    (@id ,@systemname ,@systemsecret ,@signatureexpire , GETUTCDATE() , GETUTCDATE())";
                        parameter           = new SqlParameter("@id", SqlDbType.UniqueIdentifier)
                        {
                            Value = data.ID
                        };
                        command.Parameters.Add(parameter);
                    }
                    parameter = new SqlParameter("@systemname", SqlDbType.NVarChar, 500)
                    {
                        Value = data.SystemName
                    };
                    command.Parameters.Add(parameter);
                    parameter = new SqlParameter("@systemsecret", SqlDbType.NVarChar, 500)
                    {
                        Value = data.SystemSecret
                    };
                    command.Parameters.Add(parameter);
                    parameter = new SqlParameter("@signatureexpire", SqlDbType.Int)
                    {
                        Value = data.SignatureExpire
                    };
                    command.Parameters.Add(parameter);

                    command.Prepare();

                    try
                    {
                        await command.ExecuteNonQueryAsync();
                    }
                    catch (SqlException ex)
                    {
                        if (ex.Number == 2601)
                        {
                            var fragment = new TextFragment()
                            {
                                Code = TextCodes.ExistClientWhitelistBySystemName,
                                DefaultFormatting = "客户端白名单中存在相同的系统名称\"{0}\"数据",
                                ReplaceParameters = new List <object>()
                                {
                                    data.SystemName
                                }
                            };

                            throw new UtilityException((int)Errors.ExistClientWhitelistBySystemName, fragment);
                        }
                        else
                        {
                            throw;
                        }
                    }

                    //如果用户未赋值ID则创建成功后返回ID
                    if (data.ID == Guid.Empty)
                    {
                        data.ID = (Guid)command.Parameters["@newid"].Value;
                    }
                    ;
                }
            });
        }
Ejemplo n.º 16
0
        private static async Task Lock(SqlConnection conn, SqlTransaction transaction, string lockName, int timeout)
        {
            string strTimeout;

            if (timeout == -1)
            {
                strTimeout = "null";
            }
            else
            {
                strTimeout = timeout.ToString();
            }
            string strSql = string.Format(@"declare @result int,@resource nvarchar(300),@timeout int,@message nvarchar(300)
                                      set @result = 0;
		                              set @resource='{0}';
                                      set @timeout={1}
                                      begin
			                            if @@TRANCOUNT>0
		                                    begin
			                                    if @timeout is null
				                                    EXEC @result = sp_getapplock @Resource = @resource, 
					                                @LockMode = 'Exclusive'
			                                    else
					                                EXEC @result = sp_getapplock @Resource = @resource, 
					                                @LockMode = 'Exclusive',@LockTimeout=@timeout			
		                                    end
                                        else
		                                    begin
			                                    if @timeout is null
				                                    EXEC @result = sp_getapplock @Resource = @resource, 
					                                @LockMode = 'Exclusive',@LockOwner='Session'
			                                    else
					                                EXEC @result = sp_getapplock @Resource = @resource, 
					                                @LockMode = 'Exclusive',@LockOwner='Session',@LockTimeout=@timeout			
		                                    end	

                                        if @result<0
		                                    begin
			                                    set @message=N'applock加锁失败,失败码:'+convert(nvarchar(20),@result)+',详细信息:'+ERROR_MESSAGE();
			                                    throw 50001,@message,1
		                                    end
                                       end
                            
                        ", lockName, strTimeout);

            SqlTransaction sqlTran = null;

            if (transaction != null)
            {
                sqlTran = transaction;
            }

            using (SqlCommand command = new SqlCommand())
            {
                command.CommandTimeout = 300;
                command.Connection     = conn;
                command.CommandType    = CommandType.Text;
                command.CommandText    = strSql;
                command.Transaction    = sqlTran;
                command.Prepare();
                try
                {
                    await command.ExecuteNonQueryAsync();
                }
                catch (SqlException ex)
                {
                    if (ex.Number == 50001)
                    {
                        var fragment = new TextFragment()
                        {
                            Code = TextCodes.ExistLicationLock,
                            DefaultFormatting = "当前请求{0}已被锁定",
                            ReplaceParameters = new List <object>()
                            {
                                lockName
                            }
                        };

                        throw new UtilityException((int)Errors.ExistLicationLock, fragment);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task Update(ClientWhitelist data)
        {
            await DBTransactionHelper.SqlTransactionWorkAsync(DBTypes.SqlServer, false, false, _dbConnectionFactory.CreateAllForWhitelistPolicy(), async (conn, transaction) =>
            {
                SqlTransaction sqlTran = null;
                if (transaction != null)
                {
                    sqlTran = (SqlTransaction)transaction;
                }
                using (SqlCommand command = new SqlCommand()
                {
                    Connection = (SqlConnection)conn,
                    CommandType = CommandType.Text,
                    Transaction = sqlTran,
                    CommandText = @"UPDATE [dbo].[ClientWhiteList]
                                       SET [systemname] = @systemname ,[systemsecret] = @systemsecret ,[signatureexpire] = @signatureexpire ,[modifytime]=GETUTCDATE()
                                        WHERE id=@id"
                })
                {
                    var parameter = new SqlParameter("@id", SqlDbType.UniqueIdentifier)
                    {
                        Value = data.ID
                    };
                    command.Parameters.Add(parameter);
                    parameter = new SqlParameter("@systemname", SqlDbType.NVarChar, 500)
                    {
                        Value = data.SystemName
                    };
                    command.Parameters.Add(parameter);
                    parameter = new SqlParameter("@systemsecret", SqlDbType.NVarChar, 500)
                    {
                        Value = data.SystemSecret
                    };
                    command.Parameters.Add(parameter);
                    parameter = new SqlParameter("@signatureexpire", SqlDbType.Int)
                    {
                        Value = data.SignatureExpire
                    };
                    command.Parameters.Add(parameter);
                    command.Prepare();


                    try
                    {
                        await command.ExecuteNonQueryAsync();
                    }
                    catch (SqlException ex)
                    {
                        if (ex.Number == 2601)
                        {
                            var fragment = new TextFragment()
                            {
                                Code = TextCodes.ExistClientWhitelistBySystemName,
                                DefaultFormatting = "客户端白名单中存在相同的系统名称\"{0}\"数据",
                                ReplaceParameters = new List <object>()
                                {
                                    data.SystemName
                                }
                            };

                            throw new UtilityException((int)Errors.ExistClientWhitelistBySystemName, fragment);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            });
        }
Ejemplo n.º 18
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {

                //Creating new document
                Document doc = new Document();
                //add a new page in the document...
                Aspose.Pdf.Page page = doc.Pages.Add();

                //add header and footer in the document
                AddHeaderFooter(doc, "Online Application Form - Dated: " + DateTime.Now.Date.ToString("MM-dd-yyyy"), "");

                //crearing new table
                Aspose.Pdf.Table table = new Aspose.Pdf.Table();
                page.Paragraphs.Add(table);
                table.Alignment = Aspose.Pdf.HorizontalAlignment.Center;
                table.DefaultColumnWidth = "500";
                //create a new row in the table...
                Aspose.Pdf.Row row = new Aspose.Pdf.Row();
                table.Rows.Add(row);
                //create a new cell in the row...
                Aspose.Pdf.Cell cell = new Aspose.Pdf.Cell();
                row.Cells.Add(cell);

                cell.Alignment = Aspose.Pdf.HorizontalAlignment.Center;

                //create main heading of the page
                TextFragment txtFragmanet = new TextFragment("Online Application Form");

                txtFragmanet.TextState.FontSize = 15;
                txtFragmanet.TextState.FontStyle = FontStyles.Bold;
                cell.Paragraphs.Add(txtFragmanet);

                //============================ Section of personal information Starts======================
                // Add a new heading ...
                AddHeading(page, "Applied for Position: " + txtPosition.Text, 8, false);

                // Add a new heading ...
                AddHeading(page, "Personal Information:", 10, true);

                // create table for personal information
                Aspose.Pdf.Table tblPersonalInfo = new Aspose.Pdf.Table();
                page.Paragraphs.Add(tblPersonalInfo);
                tblPersonalInfo.DefaultCellTextState.FontSize = 6;
                //set columns width...
                tblPersonalInfo.ColumnWidths = "100 400";

                //adding personal details ...
                AddRow(tblPersonalInfo, "Name:", txtName.Text);
                AddRow(tblPersonalInfo, "Date of Birth:", txtDOB.Text);
                AddRow(tblPersonalInfo, "Email:", txtEmail.Text);
                AddRow(tblPersonalInfo, "Phone:", txtPhone.Text);
                AddRow(tblPersonalInfo, "Address:", txtAddress.Text);
                foreach (Aspose.Pdf.Row rw in tblPersonalInfo.Rows)
                {
                    rw.MinRowHeight = 20;
                }
                //=========================== End of Personal Information Section ================================================
                //=========================== Skills Starts ===============================================================
                //add new heading...
                AddHeading(page, "Skills:", 10, true);
                // add text fragment...
                TextFragment txtFragSkills = new TextFragment();
                txtFragSkills.TextState.Font = FontRepository.FindFont("Calibri");
                txtFragSkills.TextState.FontSize = 8;
                txtFragSkills.Text = txtSkills.Text;
                txtFragSkills.TextState.LineSpacing = 5;
                //add text fragment in pagae paragraph...
                page.Paragraphs.Add(txtFragSkills);

                //=========================== End of Objective Statement Section ====================================================
                //============================ Section of Educational information Starts======================
                // Add a new heading ...
                AddHeading(page, "Educational Details:", 10, true);

                //create datatable...
                DataTable dtEducationalDetails = new DataTable();
                dtEducationalDetails.Columns.Add("Degree", typeof(string));
                dtEducationalDetails.Columns.Add("Total Marks/GPA", typeof(string));
                dtEducationalDetails.Columns.Add("Obtained Marks/CGPA", typeof(string));
                dtEducationalDetails.Columns.Add("Institute", typeof(string));

                //get data from the gridview and store in datatable...
                foreach (GridViewRow grow in gvEducationalDetails.Rows)
                {

                    TextBox txtDegree = grow.FindControl("txtDegree") as TextBox;
                    TextBox txtTotalMarks = grow.FindControl("txtTotalMarks") as TextBox;
                    TextBox txtObtainedMarks = grow.FindControl("txtObtainedMarks") as TextBox;
                    TextBox txtInstitute = grow.FindControl("txtInstitute") as TextBox;
                    if (txtDegree.Text.Trim() != "" && txtTotalMarks.Text.Trim() != "" && txtObtainedMarks.Text.Trim() != "" && txtInstitute.Text.Trim() != "")
                    {
                        DataRow drow = dtEducationalDetails.NewRow();
                        drow[0] = txtDegree.Text;
                        drow[1] = txtTotalMarks.Text;
                        drow[2] = txtObtainedMarks.Text;
                        drow[3] = txtInstitute.Text;
                        dtEducationalDetails.Rows.Add(drow);
                    }
                }

                //create table for personal information
                Aspose.Pdf.Table tblEducationalInfo = new Aspose.Pdf.Table();

                tblEducationalInfo.ColumnWidths = "100 100 100 100";
                //add table to the dataset
                DataSet ds = new DataSet();
                ds.Tables.Add(dtEducationalDetails);

                tblEducationalInfo.DefaultCellTextState.FontSize = 8;
                tblEducationalInfo.DefaultCellTextState.Font = FontRepository.FindFont("Calibri");

                //Set the border style of the table...
                tblEducationalInfo.Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Black));
                // Set default cell border...
                tblEducationalInfo.DefaultCellBorder = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Black));
                // Set data source of the table...
                tblEducationalInfo.ImportDataTable(ds.Tables[0], true, 0, 0, ds.Tables[0].Rows.Count, 4);
                //Add table in paragraph...
                page.Paragraphs.Add(tblEducationalInfo);
                // Set the style of head row of the table...
                tblEducationalInfo.Rows[0].DefaultCellTextState.FontStyle = FontStyles.Bold;
                tblEducationalInfo.Rows[0].BackgroundColor = Aspose.Pdf.Color.LightGray;
                //set the min height of the rows...
                foreach (Aspose.Pdf.Row rw in tblEducationalInfo.Rows)
                {
                    rw.Cells[3].IsWordWrapped = false;
                    rw.MinRowHeight = 15;
                }
                //=========================== End of Educational Information Section ================================================

                //============================ Section of Professional Experience Starts======================
                // Add a new heading ...
                AddHeading(page, "Employment History:", 10, true);

                //create a new datatbale to store the data...
                DataTable dtExperience = new DataTable();
                dtExperience.Columns.Add("Designation", typeof(string));
                dtExperience.Columns.Add("Duration", typeof(string));
                dtExperience.Columns.Add("Organization", typeof(string));

                // get the data from the grid view into datatable...
                foreach (GridViewRow grow in gvExperience.Rows)
                {

                    TextBox txtDesignation = grow.FindControl("txtDesignation") as TextBox;
                    TextBox txtDuration = grow.FindControl("txtDuration") as TextBox;
                    TextBox txtOrganization = grow.FindControl("txtOrganization") as TextBox;
                    if (txtDesignation.Text.Trim() != "" && txtDuration.Text.Trim() != "" && txtOrganization.Text.Trim() != "")
                    {
                        DataRow drow = dtExperience.NewRow();
                        drow[0] = txtDesignation.Text;
                        drow[1] = txtDuration.Text;
                        drow[2] = txtOrganization.Text;

                        dtExperience.Rows.Add(drow);
                    }
                }

                //create table for personal information
                Aspose.Pdf.Table tblExperience = new Aspose.Pdf.Table();

               //set width of the columns...
                tblExperience.ColumnWidths = "100 100 200";
                //add table to the dataset
                ds = new DataSet();
                ds.Tables.Add(dtExperience);

                //set the font properties...
                tblExperience.DefaultCellTextState.FontSize = 8;
                tblExperience.DefaultCellTextState.Font = FontRepository.FindFont("Calibri");
                //Set the border style of the table...
                tblExperience.Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Black));
                // Set default cell border...
                tblExperience.DefaultCellBorder = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Black));
                // Set data source of the table...
                tblExperience.ImportDataTable(ds.Tables[0], true, 0, 0, ds.Tables[0].Rows.Count, 3);
                //Add table in paragraph...
                page.Paragraphs.Add(tblExperience);
                // Set the style of head row of the table...
                tblExperience.Rows[0].DefaultCellTextState.FontStyle = FontStyles.Bold;
                tblExperience.Rows[0].BackgroundColor = Aspose.Pdf.Color.LightGray;
                foreach (Aspose.Pdf.Row rw in tblExperience.Rows)
                {
                    rw.Cells[2].IsWordWrapped = false;
                    rw.MinRowHeight = 15;
                }
                //=========================== End of Professional Experience Section ================================================

                //=========================== Cover Letter Starts ===============================================================
                AddHeading(page, "Cover Letter:", 10, true);
                TextFragment txtFragCoverLetter = new TextFragment();
                txtFragCoverLetter.TextState.Font = FontRepository.FindFont("Calibri");
                txtFragCoverLetter.TextState.FontSize = 8;
                txtFragCoverLetter.Text = txtCoverLetter.Text;
                txtFragCoverLetter.TextState.LineSpacing = 5;
                page.Paragraphs.Add(txtFragCoverLetter);

                //=========================== End of Cover Letter Section ====================================================

                //Add watermark in the document...
                foreach (Aspose.Pdf.Page pg in doc.Pages)
                {
                    AddWaterMark(pg);
                }

                string path = Server.MapPath("~/Uploads/Application_" + DateTime.Now.ToString("dd_MM_yy HH_mm_ss") + ".pdf");
                doc.Save(path);
                msg.Text = "<div class='alert alert-success'><button data-dismiss='alert' class='close' type='button'>×</button>Your application has been submitted successfully.</div>";
                //show message "Your application has been submitted successfully."

            }
            catch(Exception exp)
            {
                msg.Text = "<div class='alert alert-danger'><button data-dismiss='alert' class='close' type='button'>×</button>Exception Occured:" + exp.Message + "</div>";
            }
        }
Ejemplo n.º 19
0
 public void StartFragment(TextFragment newFragment)
 {
 }
Ejemplo n.º 20
0
        public ActionResult TenantsToPDF()
        {
            var tenants = GenerateListOfTenants();

            // Create new a PDF document
            var document = new Document
            {
                PageInfo = new PageInfo {
                    Margin = new MarginInfo(28, 28, 28, 42)
                }
            };

            var pdfPage = document.Pages.Add();

            // Initializes a new instance of the TextFragment for report's title
            var textFragment = new TextFragment(reportTitle1);

            // Set text properties
            textFragment.TextState.FontSize  = 12;
            textFragment.TextState.Font      = FontRepository.FindFont("TimesNewRoman");
            textFragment.TextState.FontStyle = FontStyles.Bold;

            // Initializes a new instance of the Table
            Table table = new Table
            {
                // Set column auto widths of the table
                ColumnWidths     = "10 10 10 10 10 10",
                ColumnAdjustment = ColumnAdjustment.AutoFitToContent,
                // Set cell padding
                DefaultCellPadding = new MarginInfo(5, 5, 5, 5),
                // Set the table border color as Black
                Border = new BorderInfo(BorderSide.All, .5f, Color.Black),
                // Set the border for table cells as Black
                DefaultCellBorder = new BorderInfo(BorderSide.All, .2f, Color.Black),
            };

            table.DefaultCellTextState = new TextState("TimesNewRoman", 10);
            var paymentFormat = new TextState("TimesNewRoman", 10)
            {
                HorizontalAlignment = HorizontalAlignment.Right
            };

            table.SetColumnTextState(5, paymentFormat);
            table.ImportEntityList(tenants);

            //Repeat Header
            table.RepeatingRowsCount = 1;

            // Add text fragment object to first page of input document
            pdfPage.Paragraphs.Add(textFragment);
            // Add table object to first page of input document
            pdfPage.Paragraphs.Add(table);

            using (var streamOut = new MemoryStream())
            {
                document.Save(streamOut);
                return(new FileContentResult(streamOut.ToArray(), "application/pdf")
                {
                    FileDownloadName = "tenants.pdf"
                });
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public async Task Update(ScheduleAction action)
        {
            await DBTransactionHelper.SqlTransactionWorkAsync(DBTypes.SqlServer, false, false, _dbConnectionFactory.CreateAllForSchedule(), async (conn, transaction) =>
            {
                SqlTransaction sqlTran = null;
                if (transaction != null)
                {
                    sqlTran = (SqlTransaction)transaction;
                }
                using (SqlCommand command = new SqlCommand()
                {
                    Connection = (SqlConnection)conn,
                    CommandType = CommandType.Text,
                    Transaction = sqlTran,
                    CommandText = @"UPDATE [dbo].[ScheduleAction]
                                   SET 
                                      [name] = @name,
                                      [triggercondition] = @triggercondition,
                                      [configuration]=@configuration,
                                      [mode] = @mode,
                                      [scheduleactionservicefactorytype] = @scheduleactionservicefactorytype,
                                      [scheduleactionservicefactorytypeusedi] = @scheduleactionservicefactorytypeusedi,
                                      [scheduleactionserviceweburl] = @scheduleactionserviceweburl,
                                      [websignature] = @websignature,
                                      [status] = @status,
                                      [modifytime] = GETUTCDATE()
                                 WHERE id=@id;"
                })
                {
                    var parameter = new SqlParameter("@id", SqlDbType.UniqueIdentifier)
                    {
                        Value = action.ID
                    };
                    command.Parameters.Add(parameter);
                    parameter = new SqlParameter("@name", SqlDbType.VarChar, 150)
                    {
                        Value = action.Name
                    };
                    command.Parameters.Add(parameter);

                    parameter = new SqlParameter("@triggercondition", SqlDbType.VarChar, 200)
                    {
                        Value = action.TriggerCondition
                    };
                    command.Parameters.Add(parameter);


                    parameter = new SqlParameter("@configuration", SqlDbType.NVarChar, action.Configuration.Length)
                    {
                        Value = action.Configuration
                    };
                    command.Parameters.Add(parameter);


                    parameter = new SqlParameter("@mode", SqlDbType.Int)
                    {
                        Value = action.Mode
                    };
                    command.Parameters.Add(parameter);
                    if (action.ScheduleActionServiceFactoryType != null)
                    {
                        parameter = new SqlParameter("@scheduleactionservicefactorytype", SqlDbType.VarChar, 200)
                        {
                            Value = action.ScheduleActionServiceFactoryType
                        };
                        command.Parameters.Add(parameter);
                    }
                    else
                    {
                        parameter = new SqlParameter("@scheduleactionservicefactorytype", SqlDbType.VarChar, 200)
                        {
                            Value = DBNull.Value
                        };
                        command.Parameters.Add(parameter);
                    }
                    if (action.ScheduleActionServiceFactoryTypeUseDI != null)
                    {
                        parameter = new SqlParameter("@scheduleactionservicefactorytypeusedi", SqlDbType.Bit)
                        {
                            Value = action.ScheduleActionServiceFactoryTypeUseDI
                        };
                        command.Parameters.Add(parameter);
                    }
                    else
                    {
                        parameter = new SqlParameter("@scheduleactionservicefactorytypeusedi", SqlDbType.Bit)
                        {
                            Value = DBNull.Value
                        };
                        command.Parameters.Add(parameter);
                    }
                    if (action.ScheduleActionServiceWebUrl != null)
                    {
                        parameter = new SqlParameter("@scheduleactionserviceweburl", SqlDbType.VarChar, 200)
                        {
                            Value = action.ScheduleActionServiceWebUrl
                        };
                        command.Parameters.Add(parameter);
                    }
                    else
                    {
                        parameter = new SqlParameter("@scheduleactionserviceweburl", SqlDbType.VarChar, 200)
                        {
                            Value = DBNull.Value
                        };
                        command.Parameters.Add(parameter);
                    }
                    if (action.WebSignature != null)
                    {
                        parameter = new SqlParameter("@websignature", SqlDbType.VarChar, 200)
                        {
                            Value = action.WebSignature
                        };
                        command.Parameters.Add(parameter);
                    }
                    else
                    {
                        parameter = new SqlParameter("@websignature", SqlDbType.VarChar, 200)
                        {
                            Value = DBNull.Value
                        };
                        command.Parameters.Add(parameter);
                    }
                    parameter = new SqlParameter("@status", SqlDbType.Int)
                    {
                        Value = action.Status
                    };
                    command.Parameters.Add(parameter);

                    command.Prepare();


                    try
                    {
                        await command.ExecuteNonQueryAsync();
                    }
                    catch (SqlException ex)
                    {
                        if (ex == null)
                        {
                            throw;
                        }
                        if (ex.Number == 2601)
                        {
                            var fragment = new TextFragment()
                            {
                                Code = TextCodes.ExistScheduleActionByName,
                                DefaultFormatting = "调度动作中存在相同名称\"{0}\"数据",
                                ReplaceParameters = new List <object>()
                                {
                                    action.Name
                                }
                            };

                            throw new UtilityException((int)Errors.ExistScheduleActionByName, fragment);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            });
        }
Ejemplo n.º 22
0
        public IEnumerable <NewFolding> CreateNewFoldings(ITextSource document)
        {
            List <NewFolding> newFoldings = new List <NewFolding>();

            _procList = new List <ProcListItem>();

            int startPos = 0;
            int len      = document.TextLength;

            int currentStart = 0;

            bool   MethodIsOpen = false;
            string MethodName   = "";
            string EndToken     = null;

            int PreCommentStart = -1;

            //var Reader = document.CreateReader();

            string FullText    = document.Text;
            int    DocLine     = 0;
            int    MethodStart = 0;

            const string kProcStart = "ПРОЦЕДУРА";
            const string kProcEnd   = "КОНЕЦПРОЦЕДУРЫ";
            const string kFuncStart = "ФУНКЦИЯ";
            const string kFuncEnd   = "КОНЕЦФУНКЦИИ";

            char[] trimArr = new char[] { ' ', '\t' };

            do
            {
                int    prev_start = startPos;
                string lineText   = ReadLine(FullText, ref startPos);

                DocLine++;

                if (lineText == null)
                {
                    break;
                }

                TextFragment tf = new TextFragment();
                tf.offset = prev_start;
                tf.len    = lineText.Length;

                //startPos += lineText.Length + 2;

                if (!MethodIsOpen)
                {
                    bool CommentBreak = false;

                    if (lineText.StartsWith("//"))
                    {
                        if (PreCommentStart < 0)
                        {
                            PreCommentStart = tf.offset + tf.len;
                        }
                    }
                    else
                    {
                        CommentBreak = true;
                    }

                    if (LineIsKeyword(lineText.TrimStart(trimArr), kProcStart))
                    {
                        MethodIsOpen = true;
                        MethodName   = ScanForParamList(FullText, prev_start + kProcStart.Length);
                        EndToken     = kProcEnd;
                        MethodStart  = DocLine;
                    }
                    else if (LineIsKeyword(lineText.TrimStart(trimArr), kFuncStart))
                    {
                        MethodIsOpen = true;
                        MethodName   = ScanForParamList(FullText, prev_start + kFuncStart.Length);
                        EndToken     = kFuncEnd;
                        MethodStart  = DocLine;
                    }

                    if (MethodIsOpen)
                    {
                        currentStart = tf.offset + tf.len;

                        if (PreCommentStart >= 0)
                        {
                            var Folding = new NewFolding(PreCommentStart, tf.offset - 2);
                            newFoldings.Add(Folding);
                            PreCommentStart = -1;
                        }
                    }
                    else if (CommentBreak)
                    {
                        PreCommentStart = -1;
                    }
                }
                else if (LineIsKeyword(lineText.TrimStart(trimArr), EndToken))
                {
                    var Folding = new NewFolding(currentStart, tf.offset + tf.len);
                    newFoldings.Add(Folding);

                    if (MethodName != "")
                    {
                        ProcListItem pli = new ProcListItem();
                        pli.Name      = MethodName;
                        pli.StartLine = MethodStart;
                        pli.EndLine   = DocLine;
                        pli.ListIndex = _procList.Count;

                        _procList.Add(pli);

                        MethodName = "";
                    }

                    MethodIsOpen = false;
                }
            }while (true);

            return(newFoldings);
        }
        public async Task <CrmRequestMessageHandleResult> ExecuteRequest(CrmRequestMessage request)
        {
            if (!(request is CrmRetrieveEntityO2NRelationMetadataMultipleRequestMessage))
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.CrmRequestMessageTypeNotMatch,
                    DefaultFormatting = "消息请求类型不匹配,期待的类型为{0},实际类型为{1},位置为{2}",
                    ReplaceParameters = new List <object>()
                    {
                        typeof(CrmRetrieveEntityO2NRelationMetadataMultipleRequestMessage).FullName, request.GetType().FullName, $"{ this.GetType().FullName }.ExecuteRequest"
                    }
                };

                throw new UtilityException((int)Errors.CrmRequestMessageTypeNotMatch, fragment);
            }

            var realRequest = request as CrmRetrieveEntityO2NRelationMetadataMultipleRequestMessage;

            var url = $"{realRequest.OrganizationURI}/api/data/v{realRequest.ApiVersion}/EntityDefinitions";

            if (realRequest.EntityMetadataId != Guid.Empty)
            {
                url = $"{url}({realRequest.EntityMetadataId.ToString()})";
            }
            else
            {
                url = $"{url}(LogicalName='{realRequest.EntityName}')";
            }

            url = $"{url}/OneToManyRelationships";

            if (!string.IsNullOrEmpty(realRequest.QueryExpression))
            {
                url = $"{url}?{realRequest.QueryExpression}";
            }

            var headers = new Dictionary <string, IEnumerable <string> >();

            headers["OData-MaxVersion"] = new List <string> {
                "4.0"
            };
            headers["OData-Version"] = new List <string> {
                "4.0"
            };
            headers["Content-Type"] = new List <string> {
                "application/json"
            };
            headers["Content-Type-ChartSet"] = new List <string> {
                "utf-8"
            };
            headers["Accept"] = new List <string> {
                "application/json"
            };

            foreach (var itemHeader in realRequest.Headers)
            {
                headers[itemHeader.Key] = itemHeader.Value;
            }


            CrmRequestMessageHandleResult result = new CrmRequestMessageHandleResult();

            result.Url       = url;
            result.Method    = HttpMethod.Get;
            result.Headers   = headers;
            result.Extension = realRequest;

            return(await Task.FromResult(result));
        }
Ejemplo n.º 24
0
        public async Task <CrmRequestMessageHandleResult> ExecuteRequest(CrmRequestMessage request)
        {
            if (!(request is CrmBatchRequestMessage))
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.CrmRequestMessageTypeNotMatch,
                    DefaultFormatting = "消息请求类型不匹配,期待的类型为{0},实际类型为{1},位置为{2}",
                    ReplaceParameters = new List <object>()
                    {
                        typeof(CrmBatchRequestMessage).FullName, request.GetType().FullName, $"{ this.GetType().FullName }.ExecuteRequest"
                    }
                };

                throw new UtilityException((int)Errors.CrmRequestMessageTypeNotMatch, fragment);
            }

            var batchBoundary     = $"batch_{Guid.NewGuid().ToString()}";
            var changeSetBoundary = $"changeset_{Guid.NewGuid().ToString()}";
            var realRequest       = request as CrmBatchRequestMessage;

            RequestHandleMap handleMap = new RequestHandleMap();

            string strBody = string.Empty;

            if (realRequest.ChangeSetMessages != null && realRequest.ChangeSetMessages.Count > 0)
            {
                strBody = $"--{batchBoundary}\n";
                strBody = $"{strBody}Content-Type: multipart/mixed;boundary={changeSetBoundary}\n\n";

                var changeSetIndex = 0;
                foreach (var batchItem in realRequest.ChangeSetMessages)
                {
                    batchItem.ApiVersion      = realRequest.ApiVersion;
                    batchItem.OrganizationURI = realRequest.OrganizationURI;
                    changeSetIndex++;
                    strBody = $"{strBody}--{changeSetBoundary}\n";
                    strBody = $"{strBody}Content-Type: application/http\n";
                    strBody = $"{strBody}Content-Transfer-Encoding:binary\n";
                    strBody = $"{strBody}Content-ID:{changeSetIndex.ToString()}\n\n";


                    var messageHandle = _crmMessageHandleSelector.Choose(batchItem.GetType().FullName);
                    var handleResult  = await messageHandle.ExecuteRequest(batchItem);

                    strBody = $"{strBody}{handleResult.Method.Method} {handleResult.Url} HTTP/1.1\n";
                    foreach (var headerItem in handleResult.Headers)
                    {
                        strBody = $"{strBody}{headerItem.Key}:{string.Join(";", headerItem.Value)}\n";
                    }

                    strBody = $"{strBody}\n";
                    if (handleResult.ReplaceHttpContent != null)
                    {
                        strBody = $"{strBody}{await handleResult.ReplaceHttpContent.ReadAsStringAsync()}\n";
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(handleResult.Body))
                        {
                            strBody = $"{strBody}{handleResult.Body}\n";
                        }
                    }



                    handleMap.ChangeSetHandles.Add(new RequestHandleMapItem()
                    {
                        Request = batchItem, HandleResult = handleResult
                    });
                }

                strBody = $"{strBody}\n--{changeSetBoundary}--\n\n";
            }

            if (realRequest.BatchMessages != null && realRequest.BatchMessages.Count > 0)
            {
                foreach (var batchItem in realRequest.BatchMessages)
                {
                    batchItem.ApiVersion      = realRequest.ApiVersion;
                    batchItem.OrganizationURI = realRequest.OrganizationURI;

                    strBody = $"{strBody}--{batchBoundary}--\n";
                    strBody = $"{strBody}Content-Type: application/http\n";
                    strBody = $"{strBody}Content-Transfer-Encoding:binary\n\n";

                    var messageHandle = _crmMessageHandleSelector.Choose(batchItem.GetType().FullName);
                    var handleResult  = await messageHandle.ExecuteRequest(batchItem);

                    strBody = $"{strBody}{handleResult.Method.Method} {handleResult.Url} HTTP/1.1\n";
                    foreach (var headerItem in handleResult.Headers)
                    {
                        strBody = $"{strBody}{headerItem.Key}:{string.Join(";", headerItem.Value)}\n";
                    }
                    strBody = $"{strBody}\n";

                    handleMap.ChangeSetHandles.Add(new RequestHandleMapItem()
                    {
                        Request = batchItem, HandleResult = handleResult
                    });
                }
            }

            if ((realRequest.BatchMessages != null && realRequest.BatchMessages.Count > 0) || (realRequest.ChangeSetMessages != null && realRequest.ChangeSetMessages.Count > 0))
            {
                strBody = $"{strBody}--{batchBoundary}--";
            }


            var url     = $"{realRequest.OrganizationURI}/api/data/v{realRequest.ApiVersion}/$batch";
            var headers = new Dictionary <string, IEnumerable <string> >();

            headers["OData-MaxVersion"] = new List <string> {
                "4.0"
            };
            headers["OData-Version"] = new List <string> {
                "4.0"
            };
            headers["Content-Type"] = new List <string> {
                "multipart/mixed"
            };
            headers["Content-Type-boundary"] = new List <string> {
                batchBoundary
            };

            headers["Accept"] = new List <string> {
                "application/json"
            };

            foreach (var itemHeader in realRequest.Headers)
            {
                headers[itemHeader.Key] = itemHeader.Value;
            }

            handleMap.BatchRequest = realRequest;
            CrmRequestMessageHandleResult result = new CrmRequestMessageHandleResult();

            result.Url       = url;
            result.Method    = HttpMethod.Post;
            result.Headers   = headers;
            result.Body      = strBody;
            result.Extension = handleMap;

            return(await Task.FromResult(result));
        }
Ejemplo n.º 25
0
        private MessageItemResponseInfo GetResponseInfo(string body)
        {
            Dictionary <string, IEnumerable <string> > headers = new Dictionary <string, IEnumerable <string> >();
            MessageItemResponseInfo result = new MessageItemResponseInfo();

            result.Headers = headers;
            result.Body    = string.Empty;

            var httpLabelIndex = body.ToLower().IndexOf("http/1.1");

            if (httpLabelIndex == -1)
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.CrmBatchResponseItemFormatError,
                    DefaultFormatting = "Crm的Batch操作响应项格式错误,响应项内容:{0},错误提示:{1}",
                    ReplaceParameters = new List <object>()
                    {
                        body, "miss http/1.1 label"
                    }
                };

                throw new UtilityException((int)Errors.CrmBatchResponseItemFormatError, fragment);
            }



            var startIndex = body.IndexOf("\r\n", httpLabelIndex);

            if (startIndex == -1)
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.CrmBatchResponseItemFormatError,
                    DefaultFormatting = "Crm的Batch操作响应项格式错误,响应项内容:{0},错误提示:{1}",
                    ReplaceParameters = new List <object>()
                    {
                        body, "miss header item"
                    }
                };

                throw new UtilityException((int)Errors.CrmBatchResponseItemFormatError, fragment);
            }


            if (startIndex - httpLabelIndex <= 0)
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.CrmBatchResponseItemFormatError,
                    DefaultFormatting = "Crm的Batch操作响应项格式错误,响应项内容:{0},错误提示:{1}",
                    ReplaceParameters = new List <object>()
                    {
                        body, "miss http info"
                    }
                };

                throw new UtilityException((int)Errors.CrmBatchResponseItemFormatError, fragment);
            }

            var strHttpInfo = body.Substring(httpLabelIndex, startIndex - httpLabelIndex);

            Regex regHttpInfo   = new Regex("http/1.1 +([0-9\\.]+) +", RegexOptions.IgnoreCase);
            var   httpInfoMatch = regHttpInfo.Match(strHttpInfo);

            if (httpInfoMatch == null)
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.CrmBatchResponseItemFormatError,
                    DefaultFormatting = "Crm的Batch操作响应项格式错误,响应项内容:{0},错误提示:{1}",
                    ReplaceParameters = new List <object>()
                    {
                        body, "miss http status code"
                    }
                };

                throw new UtilityException((int)Errors.CrmBatchResponseItemFormatError, fragment);
            }

            var strStatusCode = httpInfoMatch.Groups[1].Value.Trim();

            if (strStatusCode.Contains("."))
            {
                result.StatusCode = (int)float.Parse(httpInfoMatch.Groups[1].Value.Trim());
            }
            else
            {
                result.StatusCode = int.Parse(httpInfoMatch.Groups[1].Value.Trim());
            }


            var endIndex = body.IndexOf("\r\n\r\n", startIndex + 2);

            if (endIndex == -1)
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.CrmBatchResponseItemFormatError,
                    DefaultFormatting = "Crm的Batch操作响应项格式错误,响应项内容:{0},错误提示:{1}",
                    ReplaceParameters = new List <object>()
                    {
                        body, "miss header item"
                    }
                };

                throw new UtilityException((int)Errors.CrmBatchResponseItemFormatError, fragment);
            }

            if (endIndex - startIndex - 2 <= 0)
            {
                return(result);
            }


            var strHeaders = body.Substring(startIndex + 2, endIndex - startIndex - 2);

            var arrayHeaders = strHeaders.Split(new string[] { "\r\n" }, StringSplitOptions.None);

            foreach (var headerItem in arrayHeaders)
            {
                if (string.IsNullOrWhiteSpace(headerItem))
                {
                    continue;
                }

                var splitIndex = headerItem.IndexOf(":");
                if (splitIndex <= 0)
                {
                    var fragment = new TextFragment()
                    {
                        Code = TextCodes.CrmBatchResponseItemFormatError,
                        DefaultFormatting = "Crm的Batch操作响应项格式错误,响应项内容:{0},错误提示:{1}",
                        ReplaceParameters = new List <object>()
                        {
                            body, "Not correct header format"
                        }
                    };

                    throw new UtilityException((int)Errors.CrmBatchResponseItemFormatError, fragment);
                }
                if (headerItem.Length - splitIndex - 1 < 0)
                {
                    var fragment = new TextFragment()
                    {
                        Code = TextCodes.CrmBatchResponseItemFormatError,
                        DefaultFormatting = "Crm的Batch操作响应项格式错误,响应项内容:{0},错误提示:{1}",
                        ReplaceParameters = new List <object>()
                        {
                            body, "Not correct header format"
                        }
                    };

                    throw new UtilityException((int)Errors.CrmBatchResponseItemFormatError, fragment);
                }

                var headerName  = headerItem.Substring(0, splitIndex).Trim();
                var headerValue = headerItem.Substring(splitIndex + 1, headerItem.Length - splitIndex - 1).Trim();

                List <string> headerValueList  = new List <string>();
                var           arrayHeaderValue = headerValue.Split(';');
                foreach (var valueItem in arrayHeaderValue)
                {
                    headerValueList.Add(valueItem.Trim());
                }

                headers.Add(headerName, headerValueList);
            }

            if (endIndex + 4 >= body.Length - 1)
            {
                return(result);
            }

            var strBody = body.Substring(endIndex + 4, body.Length - endIndex - 4);

            result.Body = strBody.Trim();
            return(result);
        }
Ejemplo n.º 26
0
        private BatchTypeInfo GetBatchType(string body)
        {
            BatchTypeInfo result = new BatchTypeInfo();

            var contentArray = body.Split(new string[] { "\r\n" }, StringSplitOptions.None);
            var splitIndex   = contentArray[0].IndexOf(":");

            if (splitIndex <= 0)
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.CrmBatchResponseItemFormatError,
                    DefaultFormatting = "Crm的Batch操作响应项格式错误,响应项内容:{0},错误提示:{1}",
                    ReplaceParameters = new List <object>()
                    {
                        body, "Not correct header format"
                    }
                };

                throw new UtilityException((int)Errors.CrmBatchResponseItemFormatError, fragment);
            }

            if (contentArray[0].Length - splitIndex - 1 < 0)
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.CrmBatchResponseItemFormatError,
                    DefaultFormatting = "Crm的Batch操作响应项格式错误,响应项内容:{0},错误提示:{1}",
                    ReplaceParameters = new List <object>()
                    {
                        body, "Not correct header format"
                    }
                };

                throw new UtilityException((int)Errors.CrmBatchResponseItemFormatError, fragment);
            }

            var headerName  = contentArray[0].Substring(0, splitIndex).Trim();
            var headerValue = contentArray[0].Substring(splitIndex + 1, contentArray[0].Length - splitIndex - 1).Trim();

            if (headerName.ToLower() != "content-type")
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.CrmBatchResponseItemFormatError,
                    DefaultFormatting = "Crm的Batch操作响应项格式错误,响应项内容:{0},错误提示:{1}",
                    ReplaceParameters = new List <object>()
                    {
                        body, "First line need content-type"
                    }
                };

                throw new UtilityException((int)Errors.CrmBatchResponseItemFormatError, fragment);
            }

            var arrayValue = headerValue.Split(';');

            if (arrayValue[0].Trim().ToLower() != "multipart/mixed")
            {
                result.Type = 0;
            }
            else
            {
                result.Type = 1;
                if (arrayValue.Length < 2)
                {
                    var fragment = new TextFragment()
                    {
                        Code = TextCodes.CrmBatchResponseItemFormatError,
                        DefaultFormatting = "Crm的Batch操作响应项格式错误,响应项内容:{0},错误提示:{1}",
                        ReplaceParameters = new List <object>()
                        {
                            body, "First line need content-type"
                        }
                    };

                    throw new UtilityException((int)Errors.CrmBatchResponseItemFormatError, fragment);
                }

                var arrayBoundary = arrayValue[1].Split('=');
                if (arrayBoundary.Length != 2)
                {
                    var fragment = new TextFragment()
                    {
                        Code = TextCodes.CrmBatchResponseItemFormatError,
                        DefaultFormatting = "Crm的Batch操作响应项格式错误,响应项内容:{0},错误提示:{1}",
                        ReplaceParameters = new List <object>()
                        {
                            body, "Miss changeset boundary"
                        }
                    };

                    throw new UtilityException((int)Errors.CrmBatchResponseItemFormatError, fragment);
                }

                result.Exension = arrayBoundary[1].Trim();
            }

            return(result);
        }
Ejemplo n.º 27
0
        public async Task <CrmResponseMessage> ExecuteResponse(object extension, string requestUrl, string requestBody, int responseCode, Dictionary <string, IEnumerable <string> > responseHeaders, string responseBody, HttpResponseMessage responseMessage)
        {
            CrmBatchResponseMessage response = new CrmBatchResponseMessage()
            {
                BatchResponses     = new List <CrmResponseMessage>(),
                ChangeSetResponses = new List <CrmResponseMessage>()
            };
            var handleMap = (RequestHandleMap)extension;

            if (string.IsNullOrEmpty(responseBody))
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.CrmBatchResponseIsEmpty,
                    DefaultFormatting = "Crm的Batch操作响应为空",
                    ReplaceParameters = new List <object>()
                    {
                    }
                };

                throw new UtilityException((int)Errors.CrmBatchResponseIsEmpty, fragment);
            }
            //取第一行
            var arrayBody = responseBody.Split(new string[] { "\r\n" }, StringSplitOptions.None);

            Regex regBatchSplit  = new Regex("--batchresponse_([A-Za-z0-9-]+)", RegexOptions.IgnoreCase);
            var   batchSplitMath = regBatchSplit.Match(arrayBody[0]);

            if (batchSplitMath == null)
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.NotFoundBatchCodeInCrmBatchResponse,
                    DefaultFormatting = "在Crm的Batch操作响应中找不到BatchCode,响应内容首行为{0}",
                    ReplaceParameters = new List <object>()
                    {
                        arrayBody[0]
                    }
                };

                throw new UtilityException((int)Errors.NotFoundBatchCodeInCrmBatchResponse, fragment);
            }


            var batchCode = batchSplitMath.Groups[1].Value;

            string strBody = string.Empty;
            int    index   = 0;

            for (index = 0; index <= arrayBody.Length - 2; index++)
            {
                strBody = $"{ strBody}\r\n{arrayBody[index]}";
            }

            regBatchSplit = new Regex($"--batchresponse_{batchCode} *\r\n", RegexOptions.IgnoreCase);

            arrayBody = regBatchSplit.Split(strBody);

            index = 0;

            foreach (var responseItem in arrayBody)
            {
                if (string.IsNullOrWhiteSpace(responseItem))
                {
                    continue;
                }

                var batchType = GetBatchType(responseItem);

                if (batchType.Type == 0)
                {
                    var batchResponse = await ExecuteBatch(responseItem, index, handleMap.BatchHandles, responseMessage);

                    index++;
                    response.BatchResponses.Add(batchResponse);
                }
                else
                {
                    var changeSetResponses = await ExecuteChangeSet(responseItem, (string)batchType.Exension, handleMap.ChangeSetHandles, responseMessage);

                    response.ChangeSetResponses.AddRange(changeSetResponses);
                }
            }

            return(response);
        }
Ejemplo n.º 28
0
        public async Task <string> GetData(string configuration, string name)
        {
            var configurationObj = JsonSerializerHelper.Deserialize <Configuration>(configuration);

            var credentialOption = new TokenCredentialOptions();

            credentialOption.AuthorityHost = new Uri(configurationObj.AzureLoginUri);

            TokenCredential credential;

            switch (configurationObj.Type)
            {
            case 1:
                //ClientSecret
                credential = new ClientSecretCredential(configurationObj.TenantId, configurationObj.ClientId, configurationObj.ClientSecret, credentialOption);
                break;

            case 2:
                //UsernamePassword
                credential = new UsernamePasswordCredential(configurationObj.UserName, configurationObj.Password, configurationObj.TenantId, configurationObj.ClientId, credentialOption);
                break;

            case 3:
                //ManagedIdentity
                string clientID = null;
                if (!string.IsNullOrEmpty(configurationObj.ClientId))
                {
                    clientID = configurationObj.ClientId;
                }
                credential = new ManagedIdentityCredential(clientID);
                break;

            default:
                var fragment = new TextFragment()
                {
                    Code = TextCodes.NotSupportAzureVaultAuthType,
                    DefaultFormatting = "不支持方式为{0}的AzureVault验证方式,发生位置为{1}",
                    ReplaceParameters = new List <object>()
                    {
                        configurationObj.Type.ToString(), $"{this.GetType().FullName}.GetData"
                    }
                };
                throw new UtilityException((int)Errors.NotSupportAzureVaultAuthType, fragment);
            }

            SecretClientOptions options = new SecretClientOptions()
            {
                Retry =
                {
                    Delay      = TimeSpan.FromSeconds(2),
                    MaxDelay   = TimeSpan.FromSeconds(16),
                    MaxRetries =                        5,
                    Mode       = RetryMode.Exponential
                }
            };

            var client = new SecretClient(new Uri($"https://{configurationObj.VaultName}{configurationObj.VaultUriSuffix}"), credential, options);

            var result = await client.GetSecretAsync(name);

            return(result.Value.Value);
        }
Ejemplo n.º 29
0
        public static void AddHyperlinkToTextSegment()
        {
            // ExStart:AddHyperlinkToTextSegment
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
            // Create document instance
            Document doc = new Document();
            // Add page to pages collection of PDF file
            Page page1 = doc.Pages.Add();
            // Create TextFragment instance
            TextFragment tf = new TextFragment("Sample Text Fragment");
            // Set horizontal alignment for TextFragment
            tf.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Right;
            // Create a textsegment with sample text
            TextSegment segment = new TextSegment(" ... Text Segment 1...");
            // Add segment to segments collection of TextFragment
            tf.Segments.Add(segment);
            // Create a new TextSegment 
            segment = new TextSegment("Link to Google");
            // Add segment to segments collection of TextFragment
            tf.Segments.Add(segment);
            // Set hyperlink for TextSegment
            segment.Hyperlink = new Aspose.Pdf.WebHyperlink("www.google.com");
            // Set forground color for text segment
            segment.TextState.ForegroundColor = Aspose.Pdf.Color.Blue;
            // Set text formatting as italic
            segment.TextState.FontStyle = FontStyles.Italic;
            // Create another TextSegment object
            segment = new TextSegment("TextSegment without hyperlink");
            // Add segment to segments collection of TextFragment
            tf.Segments.Add(segment);
            // Add TextFragment to paragraphs collection of page object
            page1.Paragraphs.Add(tf);

            dataDir = dataDir + "AddHyperlinkToTextSegment_out.pdf";

            // Save resulting PDF document.
            doc.Save(dataDir);

            // ExEnd:AddHyperlinkToTextSegment
            Console.WriteLine("\nHyperlink to text segment added successfully.\nFile saved at " + dataDir);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// 执行所有关联的队列
        /// </summary>
        /// <param name="group"></param>
        /// <returns></returns>
        public async Task <ISQueueProcessGroupExecuteResult> Execute(SQueueProcessGroup group)
        {
            bool errorLogRecord = false;
            //声明一个轮询配置列表,队列的执行通过轮询处理帮助器管理,保证只有一个主控线程被占用
            List <PollingConfiguration> pollingConfigurations = new List <PollingConfiguration>();

            await GetAllQueue(group, async (queue) =>
            {
                pollingConfigurations.Add(new PollingConfiguration()
                {
                    Action = async() =>
                    {
                        try
                        {
                            if (AdministratorClaimGeneratorName != null && AdministratorClaimContextGeneratorName != null)
                            {
                                //生成上下文
                                var administratorClaimGenerator = await _environmentClaimGeneratorRepository.QueryByName(AdministratorClaimGeneratorName);
                                if (administratorClaimGenerator == null)
                                {
                                    var fragment = new TextFragment()
                                    {
                                        Code = TextCodes.NotFoundEnvironmentClaimGeneratorByName,
                                        DefaultFormatting = "没有找到名称为{0}的环境声明生成器",
                                        ReplaceParameters = new List <object>()
                                        {
                                            AdministratorClaimGeneratorName
                                        }
                                    };

                                    throw new UtilityException((int)Errors.NotFoundEnvironmentClaimGeneratorByName, fragment);
                                }

                                var claims = await administratorClaimGenerator.Generate();

                                var administratorClaimContextGenerator = await _claimContextGeneratorRepository.QueryByName(AdministratorClaimContextGeneratorName);
                                if (administratorClaimContextGenerator == null)
                                {
                                    var fragment = new TextFragment()
                                    {
                                        Code = TextCodes.NotFoundClaimContextGeneratorByName,
                                        DefaultFormatting = "没有找到名称为{0}的上下文生成器",
                                        ReplaceParameters = new List <object>()
                                        {
                                            AdministratorClaimContextGeneratorName
                                        }
                                    };

                                    throw new UtilityException((int)Errors.NotFoundClaimContextGeneratorByName, fragment);
                                }

                                administratorClaimContextGenerator.ContextInit(claims.Claims);
                            }

                            ConcurrentDictionary <Guid, Guid> errorMessageList = new ConcurrentDictionary <Guid, Guid>();

                            //获取队列中的消息
                            await _smessageRepository.QueryAllByQueue(queue, 500, async(messages) =>
                            {
                                bool needRestart = false;


                                foreach (var message in messages)
                                {
                                    StatusResult executeResult = new StatusResult()
                                    {
                                        Status = 2
                                    };

                                    try
                                    {
                                        using (var diContainer = DIContainerContainer.CreateContainer())
                                        {
                                            var orginialDI = ContextContainer.GetValue <IDIContainer>("DI");
                                            try
                                            {
                                                ContextContainer.SetValue <IDIContainer>("DI", diContainer);
                                                //对每个消息执行处理
                                                executeResult = await message.Execute();
                                            }
                                            finally
                                            {
                                                ContextContainer.SetValue <IDIContainer>("DI", orginialDI);
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        while (ex.InnerException != null)
                                        {
                                            ex = ex.InnerException;
                                        }
                                        //if (errorMessageList.Count<=100000)
                                        //{
                                        //if (!errorMessageList.ContainsKey(message.ID))
                                        //{
                                        //   errorMessageList.TryAdd(message.ID, message.ID);
                                        LoggerHelper.LogError(ErrorLoggerCategoryName,
                                                              $"SQueueProcessGroup {group.Name} Execute Error,message Type {message.Type},message id {message.ID.ToString()},ErrorMessage:{await ex.GetCurrentLcidMessage()},StackTrace:{ex.StackTrace}");
                                        //}
                                        //}
                                    }

                                    if (executeResult.Status == 0)
                                    {
                                        //执行成功
                                        needRestart = true;
                                        await message.Delete();

                                        //errorMessageList.TryRemove(message.ID, out Guid deleteId);
                                    }
                                    else
                                    {
                                        if (executeResult.Status == 3)
                                        {
                                            needRestart = true;
                                            //执行失败
                                            //LoggerHelper.LogError(ErrorLoggerCategoryName, $"SQueueProcessGroup Message Execute Error,Type:{message.Type},Key:{message.Key},Data:{message.Data},ErrorMessage:{executeResult.Description}");
                                        }
                                    }
                                }

                                if (needRestart)
                                {
                                    return(await Task.FromResult(false));
                                }
                                else
                                {
                                    return(await Task.FromResult(true));
                                }
                            });

                            //System.Threading.Thread.Sleep(1000);
                        }
                        catch (Exception ex)
                        {
                            //if (!errorLogRecord)
                            //{
                            while (ex.InnerException != null)
                            {
                                ex = ex.InnerException;
                            }
                            LoggerHelper.LogError(ErrorLoggerCategoryName,
                                                  $"SQueueProcessGroup {group.Name} Execute Error,ErrorMessage:{await ex.GetCurrentLcidMessage()},StackTrace:{ex.StackTrace}");
                            //    errorLogRecord = true;
                            //}

                            await Task.Delay(1000 * 60 * 2);
                        }
                    },
                    Interval = queue.Interval
                }
                                          );

                await Task.FromResult(0);
            });

            var pollingResult = PollingHelper.Polling(pollingConfigurations,
                                                      async(ex) =>
            {
                LoggerHelper.LogError(ErrorLoggerCategoryName,
                                      $"PollingHelper Execute Error,ErrorMessage:{ex.Message},StackTrace:{ex.StackTrace}");
            }
                                                      );

            return(new SQueueProcessGroupExecuteResultDefalut(pollingResult));
        }
Ejemplo n.º 31
0
        private static void UnLockSync(SqlConnection conn, SqlTransaction transaction, string lockName)
        {
            string strSql = string.Format(@"declare @result int,@resource nvarchar(300),@message nvarchar(300)
                                      set @result = 0;
		                              set @resource='{0}';
                                      begin

		                                begin try
			                                EXEC @result = sp_releaseapplock @Resource = @resource
		                                end try
		                                begin catch
		                                end catch

                                        if @result<0
		                                    begin
			                                    set @message=N'applock解锁失败,失败码:'+convert(nvarchar(20),@result)+N',详细信息:'+ERROR_MESSAGE();
			                                    throw 50001,@message,1
		                                    end
                                       end
                            
                        ", lockName);

            SqlTransaction sqlTran = null;

            if (transaction != null)
            {
                sqlTran = transaction;
            }

            using (SqlCommand command = new SqlCommand())
            {
                command.CommandTimeout = 300;
                command.Connection     = conn;
                command.CommandType    = CommandType.Text;
                command.CommandText    = strSql;
                command.Transaction    = sqlTran;
                command.Prepare();
                try
                {
                    command.ExecuteNonQuery();
                }
                catch (SqlException ex)
                {
                    if (ex.Number == 50001)
                    {
                        var fragment = new TextFragment()
                        {
                            Code = TextCodes.ExistLicationLock,
                            DefaultFormatting = "当前请求{0}已被锁定",
                            ReplaceParameters = new List <object>()
                            {
                                lockName
                            }
                        };

                        throw new UtilityException((int)Errors.ExistLicationLock, fragment);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
Ejemplo n.º 32
0
        protected void btnMergeAllFiles_Click(object sender, EventArgs e)
        {
            try
            {
                //delete file if already exists...
                if (File.Exists(Server.MapPath("~/Uploads/Catalog.pdf")))
                {
                    File.Delete(Server.MapPath("~/Uploads/Catalog.pdf"));
                }
                // create new document to save the catalog...
                Document doc = new Document();

                //get all the applications in the directory
                string[] pdfFiles = Directory.GetFiles(Server.MapPath("~/Uploads"), "*.pdf")
                       .Select(path => Path.GetFileName(path))
                       .ToArray();
                if (pdfFiles.Count() == 0)
                {
                    msg.Text = "<div class='alert alert-danger'><button data-dismiss='alert' class='close' type='button'>×</button>There is currently no application available.</div>";
                    return;
                }
                else
                {
                    foreach (string val in pdfFiles)
                    {
                        //get the pdf document..
                        Document application = new Document(Server.MapPath("~/Uploads/" + val));
                        //merge the pages in catalog document...
                        doc.Pages.Add(application.Pages);
                    }
                    //====================================== Adding Table of Content Starts =========================================
                    //add TOC page...
                    Aspose.Pdf.Page tocPage = doc.Pages.Insert(1);
                    //add watermark on table of content
                    AddWaterMark(tocPage);
                    // Create object to represent TOC information
                    TocInfo tocInfo = new TocInfo();
                    TextFragment title = new TextFragment("Table Of Contents");
                    title.TextState.FontSize = 20;
                    title.TextState.FontStyle = FontStyles.Bold;

                    // Set the title for TOC
                    tocInfo.Title = title;
                    tocPage.TocInfo = tocInfo;

                    for (int i = 0; i < pdfFiles.Count(); i++)
                    {
                        // Create Heading object
                        Aspose.Pdf.Heading heading2 = new Aspose.Pdf.Heading(1);
                        TextSegment segment2 = new TextSegment();
                        heading2.TocPage = tocPage;
                        heading2.Segments.Add(segment2);

                        // Specify the destination page for heading object
                        heading2.DestinationPage = doc.Pages[i + 2];

                        // Destination page
                        heading2.Top = doc.Pages[i + 2].Rect.Height;

                        // Destination coordinate
                        segment2.Text = "Application Form No. " + (i + 1).ToString();

                        // Add heading to page containing TOC
                        tocPage.Paragraphs.Add(heading2);
                    }
                    //===================================== TOC Ends ==========================================

                    //save the final catalog file...
                    string catalogpath = Server.MapPath("~/Catalogs/Catalog.pdf");
                    doc.Save(catalogpath);
                    msg.Text = "<div class='alert alert-success'><button data-dismiss='alert' class='close' type='button'>×</button>Applications have been saved in catalog.</div>";
                    //show success message
                }
            }
            catch (Exception exp)
            {
                msg.Text = "<div class='alert alert-danger'><button data-dismiss='alert' class='close' type='button'>×</button>Exception Occured:" + exp.Message + "</div>";
            }
        }
Ejemplo n.º 33
0
 /// <summary>
 /// Starts the fragment.
 /// </summary>
 /// <param name="newFragment">The new fragment.</param>
 public void StartFragment(TextFragment newFragment)
 {
     foundTerms = new HashSet <string>();
     totalScore = 0;
 }
        public static void Run()
        {
            // ExStart:ReplaceableSymbolsInHeaderFooter
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();

            Document doc  = new Document();
            Page     page = doc.Pages.Add();

            MarginInfo marginInfo = new MarginInfo();

            marginInfo.Top    = 90;
            marginInfo.Bottom = 50;
            marginInfo.Left   = 50;
            marginInfo.Right  = 50;
            // Assign the marginInfo instance to Margin property of sec1.PageInfo
            page.PageInfo.Margin = marginInfo;

            HeaderFooter hfFirst = new HeaderFooter();

            page.Header          = hfFirst;
            hfFirst.Margin.Left  = 50;
            hfFirst.Margin.Right = 50;

            // Instantiate a Text paragraph that will store the content to show as header
            TextFragment t1 = new TextFragment("report title");

            t1.TextState.Font                = FontRepository.FindFont("Arial");
            t1.TextState.FontSize            = 16;
            t1.TextState.ForegroundColor     = Aspose.Pdf.Color.Black;
            t1.TextState.FontStyle           = FontStyles.Bold;
            t1.TextState.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Center;
            t1.TextState.LineSpacing         = 5f;
            hfFirst.Paragraphs.Add(t1);

            TextFragment t2 = new TextFragment("Report_Name");

            t2.TextState.Font                = FontRepository.FindFont("Arial");
            t2.TextState.ForegroundColor     = Aspose.Pdf.Color.Black;
            t2.TextState.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Center;
            t2.TextState.LineSpacing         = 5f;
            t2.TextState.FontSize            = 12;
            hfFirst.Paragraphs.Add(t2);

            // Create a HeaderFooter object for the section
            HeaderFooter hfFoot = new HeaderFooter();

            // Set the HeaderFooter object to odd & even footer
            page.Footer         = hfFoot;
            hfFoot.Margin.Left  = 50;
            hfFoot.Margin.Right = 50;

            // Add a text paragraph containing current page number of total number of pages
            TextFragment t3 = new TextFragment("Generated on test date");
            TextFragment t4 = new TextFragment("report name ");
            TextFragment t5 = new TextFragment("Page $p of $P");

            // Instantiate a table object
            Table tab2 = new Table();

            // Add the table in paragraphs collection of the desired section
            hfFoot.Paragraphs.Add(tab2);

            // Set with column widths of the table
            tab2.ColumnWidths = "165 172 165";

            // Create rows in the table and then cells in the rows
            Row row3 = tab2.Rows.Add();

            row3.Cells.Add();
            row3.Cells.Add();
            row3.Cells.Add();

            // Set the vertical allignment of the text as center alligned
            row3.Cells[0].Alignment = Aspose.Pdf.HorizontalAlignment.Left;
            row3.Cells[1].Alignment = Aspose.Pdf.HorizontalAlignment.Center;
            row3.Cells[2].Alignment = Aspose.Pdf.HorizontalAlignment.Right;

            row3.Cells[0].Paragraphs.Add(t3);
            row3.Cells[1].Paragraphs.Add(t4);
            row3.Cells[2].Paragraphs.Add(t5);

            // Sec1.Paragraphs.Add(New Text("Aspose.Total for Java is a compilation of every Java component offered by Aspose. It is compiled on a#$NL" + "daily basis to ensure it contains the most up to date versions of each of our Java components. #$NL " + "Using Aspose.Total for Java developers can create a wide range of applications. #$NL #$NL #$NP" + "Aspose.Total for Java is a compilation of every Java component offered by Aspose. It is compiled on a#$NL" + "daily basis to ensure it contains the most up to date versions of each of our Java components. #$NL " + "Using Aspose.Total for Java developers can create a wide range of applications. #$NL #$NL #$NP" + "Aspose.Total for Java is a compilation of every Java component offered by Aspose. It is compiled on a#$NL" + "daily basis to ensure it contains the most up to date versions of each of our Java components. #$NL " + "Using Aspose.Total for Java developers can create a wide range of applications. #$NL #$NL"))
            Table table = new Table();

            table.ColumnWidths              = "33% 33% 34%";
            table.DefaultCellPadding        = new MarginInfo();
            table.DefaultCellPadding.Top    = 10;
            table.DefaultCellPadding.Bottom = 10;

            // Add the table in paragraphs collection of the desired section
            page.Paragraphs.Add(table);

            // Set default cell border using BorderInfo object
            table.DefaultCellBorder = new BorderInfo(BorderSide.All, 0.1f);

            // Set table border using another customized BorderInfo object
            table.Border = new BorderInfo(BorderSide.All, 1f);

            table.RepeatingRowsCount = 1;

            // Create rows in the table and then cells in the rows
            Row row1 = table.Rows.Add();

            row1.Cells.Add("col1");
            row1.Cells.Add("col2");
            row1.Cells.Add("col3");
            const string CRLF = "\r\n";

            for (int i = 0; i <= 10; i++)
            {
                Row row = table.Rows.Add();
                row.IsRowBroken = true;
                for (int c = 0; c <= 2; c++)
                {
                    Cell c1;
                    if (c == 2)
                    {
                        c1 = row.Cells.Add("Aspose.Total for Java is a compilation of every Java component offered by Aspose. It is compiled on a" + CRLF + "daily basis to ensure it contains the most up to date versions of each of our Java components. " + CRLF + "daily basis to ensure it contains the most up to date versions of each of our Java components. " + CRLF + "Using Aspose.Total for Java developers can create a wide range of applications.");
                    }
                    else
                    {
                        c1 = row.Cells.Add("item1" + c);
                    }
                    c1.Margin        = new MarginInfo();
                    c1.Margin.Left   = 30;
                    c1.Margin.Top    = 10;
                    c1.Margin.Bottom = 10;
                }
            }

            dataDir = dataDir + "ReplaceableSymbolsInHeaderFooter_out_.pdf";
            doc.Save(dataDir);
            // ExEnd:ReplaceableSymbolsInHeaderFooter
            Console.WriteLine("\nSymbols replaced successfully in header and footer.\nFile saved at " + dataDir);
        }
Ejemplo n.º 35
0
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public async Task Add(ScheduleAction action)
        {
            await DBTransactionHelper.SqlTransactionWorkAsync(DBTypes.SqlServer, false, false, _dbConnectionFactory.CreateAllForSchedule(), async (conn, transaction) =>
            {
                SqlTransaction sqlTran = null;
                if (transaction != null)
                {
                    sqlTran = (SqlTransaction)transaction;
                }
                using (SqlCommand command = new SqlCommand()
                {
                    Connection = (SqlConnection)conn,
                    CommandType = CommandType.Text,
                    Transaction = sqlTran,
                })
                {
                    SqlParameter parameter;
                    if (action.ID == Guid.Empty)
                    {
                        command.CommandText = @"INSERT INTO [dbo].[ScheduleAction]
                                                    ([id],[name],[triggercondition],[configuration],[mode],[scheduleactionservicefactorytype],[scheduleactionservicefactorytypeusedi],[scheduleactionserviceweburl],[websignature],[status],[createtime],[modifytime])
                                                VALUES
                                                    (default, @name, @triggercondition,@configuration, @mode, @scheduleactionservicefactorytype, @scheduleactionservicefactorytypeusedi, @scheduleactionserviceweburl, @websignature, @status, GETUTCDATE(), GETUTCDATE());
                                                select @newid =[id] from [dbo].[ScheduleAction] where [sequence] = SCOPE_IDENTITY()";
                        parameter           = new SqlParameter("@newid", SqlDbType.UniqueIdentifier)
                        {
                            Direction = ParameterDirection.Output
                        };
                        command.Parameters.Add(parameter);
                    }
                    else
                    {
                        command.CommandText = @"INSERT INTO [dbo].[ScheduleAction]
                                                    ([id],[name],[triggercondition],[configuration],[mode],[scheduleactionservicefactorytype],[scheduleactionservicefactorytypeusedi],[scheduleactionserviceweburl],[websignature],[status],[createtime],[modifytime])
                                                VALUES
                                                    (@id, @name, @triggercondition,@configuration, @mode, @scheduleactionservicefactorytype, @scheduleactionservicefactorytypeusedi, @scheduleactionserviceweburl, @websignature, @status, GETUTCDATE(), GETUTCDATE());";
                        parameter           = new SqlParameter("@id", SqlDbType.UniqueIdentifier)
                        {
                            Value = action.ID
                        };
                        command.Parameters.Add(parameter);
                    }
                    parameter = new SqlParameter("@name", SqlDbType.VarChar, 150)
                    {
                        Value = action.Name
                    };
                    command.Parameters.Add(parameter);

                    parameter = new SqlParameter("@triggercondition", SqlDbType.VarChar, 200)
                    {
                        Value = action.TriggerCondition
                    };
                    command.Parameters.Add(parameter);

                    parameter = new SqlParameter("@configuration", SqlDbType.NVarChar, action.Configuration.Length)
                    {
                        Value = action.Configuration
                    };
                    command.Parameters.Add(parameter);

                    parameter = new SqlParameter("@mode", SqlDbType.Int)
                    {
                        Value = action.Mode
                    };
                    command.Parameters.Add(parameter);
                    if (action.ScheduleActionServiceFactoryType != null)
                    {
                        parameter = new SqlParameter("@scheduleactionservicefactorytype", SqlDbType.VarChar, 200)
                        {
                            Value = action.ScheduleActionServiceFactoryType
                        };
                        command.Parameters.Add(parameter);
                    }
                    else
                    {
                        parameter = new SqlParameter("@scheduleactionservicefactorytype", SqlDbType.VarChar, 200)
                        {
                            Value = DBNull.Value
                        };
                        command.Parameters.Add(parameter);
                    }
                    if (action.ScheduleActionServiceFactoryTypeUseDI != null)
                    {
                        parameter = new SqlParameter("@scheduleactionservicefactorytypeusedi", SqlDbType.Bit)
                        {
                            Value = action.ScheduleActionServiceFactoryTypeUseDI
                        };
                        command.Parameters.Add(parameter);
                    }
                    else
                    {
                        parameter = new SqlParameter("@scheduleactionservicefactorytypeusedi", SqlDbType.Bit)
                        {
                            Value = DBNull.Value
                        };
                        command.Parameters.Add(parameter);
                    }
                    if (action.ScheduleActionServiceWebUrl != null)
                    {
                        parameter = new SqlParameter("@scheduleactionserviceweburl", SqlDbType.VarChar, 200)
                        {
                            Value = action.ScheduleActionServiceWebUrl
                        };
                        command.Parameters.Add(parameter);
                    }
                    else
                    {
                        parameter = new SqlParameter("@scheduleactionserviceweburl", SqlDbType.VarChar, 200)
                        {
                            Value = DBNull.Value
                        };
                        command.Parameters.Add(parameter);
                    }
                    if (action.WebSignature != null)
                    {
                        parameter = new SqlParameter("@websignature", SqlDbType.VarChar, 200)
                        {
                            Value = action.WebSignature
                        };
                        command.Parameters.Add(parameter);
                    }
                    else
                    {
                        parameter = new SqlParameter("@websignature", SqlDbType.VarChar, 200)
                        {
                            Value = DBNull.Value
                        };
                        command.Parameters.Add(parameter);
                    }

                    parameter = new SqlParameter("@status", SqlDbType.Int)
                    {
                        Value = action.Status
                    };
                    command.Parameters.Add(parameter);
                    command.Prepare();

                    try
                    {
                        await command.ExecuteNonQueryAsync();
                    }
                    catch (SqlException ex)
                    {
                        if (ex == null)
                        {
                            throw;
                        }
                        if (ex.Number == 2601)
                        {
                            var fragment = new TextFragment()
                            {
                                Code = TextCodes.ExistScheduleActionByName,
                                DefaultFormatting = "调度动作中存在相同名称\"{0}\"数据",
                                ReplaceParameters = new List <object>()
                                {
                                    action.Name
                                }
                            };

                            throw new UtilityException((int)Errors.ExistScheduleActionByName, fragment);
                        }
                        else
                        {
                            throw;
                        }
                    }
                    //如果用户未赋值ID则创建成功后返回ID
                    if (action.ID == Guid.Empty)
                    {
                        action.ID = (Guid)command.Parameters["@newid"].Value;
                    }
                    ;
                }
            });
        }
        public static void Run()
        {
            // ExStart:CreateMultiColumnPdf
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();

            Document doc = new Document();

            // Specify the left margin info for the PDF file
            doc.PageInfo.Margin.Left = 40;
            // Specify the Right margin info for the PDF file
            doc.PageInfo.Margin.Right = 40;
            Page page = doc.Pages.Add();

            Aspose.Pdf.Drawing.Graph graph1 = new Aspose.Pdf.Drawing.Graph(500, 2);
            // Add the line to paraphraphs collection of section object
            page.Paragraphs.Add(graph1);

            // Specify the coordinates for the line
            float[] posArr             = new float[] { 1, 2, 500, 2 };
            Aspose.Pdf.Drawing.Line l1 = new Aspose.Pdf.Drawing.Line(posArr);
            graph1.Shapes.Add(l1);
            // Create string variables with text containing html tags

            string s = "<font face=\"Times New Roman\" size=4>" +

                       "<strong> How to Steer Clear of money scams</<strong> "
                       + "</font>";
            // Create text paragraphs containing HTML text

            HtmlFragment heading_text = new HtmlFragment(s);

            page.Paragraphs.Add(heading_text);

            Aspose.Pdf.FloatingBox box = new Aspose.Pdf.FloatingBox();
            // Add four columns in the section
            box.ColumnInfo.ColumnCount = 2;
            // Set the spacing between the columns
            box.ColumnInfo.ColumnSpacing = "5";

            box.ColumnInfo.ColumnWidths = "105 105";
            TextFragment text1 = new TextFragment("By A Googler (The Official Google Blog)");

            text1.TextState.FontSize    = 8;
            text1.TextState.LineSpacing = 2;
            box.Paragraphs.Add(text1);
            text1.TextState.FontSize = 10;

            text1.TextState.FontStyle = FontStyles.Italic;
            // Create a graphs object to draw a line
            Aspose.Pdf.Drawing.Graph graph2 = new Aspose.Pdf.Drawing.Graph(50, 10);
            // Specify the coordinates for the line
            float[] posArr2            = new float[] { 1, 10, 100, 10 };
            Aspose.Pdf.Drawing.Line l2 = new Aspose.Pdf.Drawing.Line(posArr2);
            graph2.Shapes.Add(l2);

            // Add the line to paragraphs collection of section object
            box.Paragraphs.Add(graph2);

            TextFragment text2 = new TextFragment(@"Sed augue tortor, sodales id, luctus et, pulvinar ut, eros. Suspendisse vel dolor. Sed quam. Curabitur ut massa vitae eros euismod aliquam. Pellentesque sit amet elit. Vestibulum interdum pellentesque augue. Cras mollis arcu sit amet purus. Donec augue. Nam mollis tortor a elit. Nulla viverra nisl vel mauris. Vivamus sapien. nascetur ridiculus mus. Nam justo lorem, aliquam luctus, sodales et, semper sed, enim Nam justo lorem, aliquam luctus, sodales et,nAenean posuere ante ut neque. Morbi sollicitudin congue felis. Praesent turpis diam, iaculis sed, pharetra non, mollis ac, mauris. Phasellus nisi ipsum, pretium vitae, tempor sed, molestie eu, dui. Duis lacus purus, tristique ut, iaculis cursus, tincidunt vitae, risus. Sed commodo. *** sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam justo lorem, aliquam luctus, sodales et, semper sed, enim Nam justo lorem, aliquam luctus, sodales et, semper sed, enim Nam justo lorem, aliquam luctus, sodales et, semper sed, enim nAenean posuere ante ut neque. Morbi sollicitudin congue felis. Praesent turpis diam, iaculis sed, pharetra non, mollis ac, mauris. Phasellus nisi ipsum, pretium vitae, tempor sed, molestie eu, dui. Duis lacus purus, tristique ut, iaculis cursus, tincidunt vitae, risus. Sed commodo. *** sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed urna. . Duis convallis ultrices nisi. Maecenas non ligula. Nunc nibh est, tincidunt in, placerat sit amet, vestibulum a, nulla. Praesent porttitor turpis eleifend ante. Morbi sodales.nAenean posuere ante ut neque. Morbi sollicitudin congue felis. Praesent turpis diam, iaculis sed, pharetra non, mollis ac, mauris. Phasellus nisi ipsum, pretium vitae, tempor sed, molestie eu, dui. Duis lacus purus, tristique ut, iaculis cursus, tincidunt vitae, risus. Sed commodo. *** sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed urna. . Duis convallis ultrices nisi. Maecenas non ligula. Nunc nibh est, tincidunt in, placerat sit amet, vestibulum a, nulla. Praesent porttitor turpis eleifend ante. Morbi sodales.");

            box.Paragraphs.Add(text2);

            page.Paragraphs.Add(box);

            dataDir = dataDir + "CreateMultiColumnPdf_out_.pdf";
            // Save PDF file
            doc.Save(dataDir);
            // ExEnd:CreateMultiColumnPdf
            Console.WriteLine("\nMulti column pdf file created successfully.\nFile saved at " + dataDir);
        }
Ejemplo n.º 37
0
 private TextFragment CreateFragmentFromRange(TextRange textRange)
 {
     return(TextFragment.Sub(textRange.Position, textRange.Length));
 }
Ejemplo n.º 38
0
        public async Task <string> Genereate(Dictionary <string, object> parameters)
        {
            TextFragment fragment;

            //检查参数
            if (!parameters.ContainsKey(CrmServiceTokenGenerateServiceParameterNames.AdfsUrl) || parameters[CrmServiceTokenGenerateServiceParameterNames.AdfsUrl] == null)
            {
                fragment = new TextFragment()
                {
                    Code = TextCodes.NotFoundParameterInCrmServiceTokenGenerateService,
                    DefaultFormatting = "在Crm服务令牌生成服务{0}中,找不到名称为{1}的参数",
                    ReplaceParameters = new List <object>()
                    {
                        this.GetType().FullName, CrmServiceTokenGenerateServiceParameterNames.AdfsUrl
                    }
                };

                throw new UtilityException((int)Errors.NotFoundParameterInCrmServiceTokenGenerateService, fragment);
            }
            if (!(parameters[CrmServiceTokenGenerateServiceParameterNames.AdfsUrl] is string))
            {
                fragment = new TextFragment()
                {
                    Code = TextCodes.ParameterTypeNotMatchInCrmServiceTokenGenerateService,
                    DefaultFormatting = "在Crm服务令牌生成服务{0}中,名称为{1}的参数期望类型为{2},而实际类型为{3}",
                    ReplaceParameters = new List <object>()
                    {
                        this.GetType().FullName, CrmServiceTokenGenerateServiceParameterNames.AdfsUrl, typeof(string).FullName, parameters[CrmServiceTokenGenerateServiceParameterNames.AdfsUrl].GetType().FullName
                    }
                };

                throw new UtilityException((int)Errors.ParameterTypeNotMatchInCrmServiceTokenGenerateService, fragment);
            }
            string strAdfsUrl = parameters[CrmServiceTokenGenerateServiceParameterNames.AdfsUrl].ToString();

            if (!parameters.ContainsKey(CrmServiceTokenGenerateServiceParameterNames.ClientId) || parameters[CrmServiceTokenGenerateServiceParameterNames.ClientId] == null)
            {
                fragment = new TextFragment()
                {
                    Code = TextCodes.NotFoundParameterInCrmServiceTokenGenerateService,
                    DefaultFormatting = "在Crm服务令牌生成服务{0}中,找不到名称为{1}的参数",
                    ReplaceParameters = new List <object>()
                    {
                        this.GetType().FullName, CrmServiceTokenGenerateServiceParameterNames.ClientId
                    }
                };

                throw new UtilityException((int)Errors.NotFoundParameterInCrmServiceTokenGenerateService, fragment);
            }
            if (!(parameters[CrmServiceTokenGenerateServiceParameterNames.ClientId] is string))
            {
                fragment = new TextFragment()
                {
                    Code = TextCodes.ParameterTypeNotMatchInCrmServiceTokenGenerateService,
                    DefaultFormatting = "在Crm服务令牌生成服务{0}中,名称为{1}的参数期望类型为{2},而实际类型为{3}",
                    ReplaceParameters = new List <object>()
                    {
                        this.GetType().FullName, CrmServiceTokenGenerateServiceParameterNames.ClientId, typeof(string).FullName, parameters[CrmServiceTokenGenerateServiceParameterNames.ClientId].GetType().FullName
                    }
                };

                throw new UtilityException((int)Errors.ParameterTypeNotMatchInCrmServiceTokenGenerateService, fragment);
            }
            string strClientId = parameters[CrmServiceTokenGenerateServiceParameterNames.ClientId].ToString();

            if (!parameters.ContainsKey(CrmServiceTokenGenerateServiceParameterNames.CrmUrl) || parameters[CrmServiceTokenGenerateServiceParameterNames.CrmUrl] == null)
            {
                fragment = new TextFragment()
                {
                    Code = TextCodes.NotFoundParameterInCrmServiceTokenGenerateService,
                    DefaultFormatting = "在Crm服务令牌生成服务{0}中,找不到名称为{1}的参数",
                    ReplaceParameters = new List <object>()
                    {
                        this.GetType().FullName, CrmServiceTokenGenerateServiceParameterNames.CrmUrl
                    }
                };

                throw new UtilityException((int)Errors.NotFoundParameterInCrmServiceTokenGenerateService, fragment);
            }
            if (!(parameters[CrmServiceTokenGenerateServiceParameterNames.CrmUrl] is string))
            {
                fragment = new TextFragment()
                {
                    Code = TextCodes.ParameterTypeNotMatchInCrmServiceTokenGenerateService,
                    DefaultFormatting = "在Crm服务令牌生成服务{0}中,名称为{1}的参数期望类型为{2},而实际类型为{3}",
                    ReplaceParameters = new List <object>()
                    {
                        this.GetType().FullName, CrmServiceTokenGenerateServiceParameterNames.CrmUrl, typeof(string).FullName, parameters[CrmServiceTokenGenerateServiceParameterNames.CrmUrl].GetType().FullName
                    }
                };

                throw new UtilityException((int)Errors.ParameterTypeNotMatchInCrmServiceTokenGenerateService, fragment);
            }
            string strCrmUrl = parameters[CrmServiceTokenGenerateServiceParameterNames.CrmUrl].ToString();

            if (!parameters.ContainsKey(CrmServiceTokenGenerateServiceParameterNames.RedirectUri) || parameters[CrmServiceTokenGenerateServiceParameterNames.RedirectUri] == null)
            {
                fragment = new TextFragment()
                {
                    Code = TextCodes.NotFoundParameterInCrmServiceTokenGenerateService,
                    DefaultFormatting = "在Crm服务令牌生成服务{0}中,找不到名称为{1}的参数",
                    ReplaceParameters = new List <object>()
                    {
                        this.GetType().FullName, CrmServiceTokenGenerateServiceParameterNames.RedirectUri
                    }
                };

                throw new UtilityException((int)Errors.NotFoundParameterInCrmServiceTokenGenerateService, fragment);
            }
            if (!(parameters[CrmServiceTokenGenerateServiceParameterNames.RedirectUri] is string))
            {
                fragment = new TextFragment()
                {
                    Code = TextCodes.ParameterTypeNotMatchInCrmServiceTokenGenerateService,
                    DefaultFormatting = "在Crm服务令牌生成服务{0}中,名称为{1}的参数期望类型为{2},而实际类型为{3}",
                    ReplaceParameters = new List <object>()
                    {
                        this.GetType().FullName, CrmServiceTokenGenerateServiceParameterNames.RedirectUri, typeof(string).FullName, parameters[CrmServiceTokenGenerateServiceParameterNames.RedirectUri].GetType().FullName
                    }
                };

                throw new UtilityException((int)Errors.ParameterTypeNotMatchInCrmServiceTokenGenerateService, fragment);
            }
            string strRedirectUri = parameters[CrmServiceTokenGenerateServiceParameterNames.RedirectUri].ToString();

            if (!parameters.ContainsKey(CrmServiceTokenGenerateServiceParameterNames.UserName) || parameters[CrmServiceTokenGenerateServiceParameterNames.UserName] == null)
            {
                fragment = new TextFragment()
                {
                    Code = TextCodes.NotFoundParameterInCrmServiceTokenGenerateService,
                    DefaultFormatting = "在Crm服务令牌生成服务{0}中,找不到名称为{1}的参数",
                    ReplaceParameters = new List <object>()
                    {
                        this.GetType().FullName, CrmServiceTokenGenerateServiceParameterNames.UserName
                    }
                };

                throw new UtilityException((int)Errors.NotFoundParameterInCrmServiceTokenGenerateService, fragment);
            }
            if (!(parameters[CrmServiceTokenGenerateServiceParameterNames.UserName] is string))
            {
                fragment = new TextFragment()
                {
                    Code = TextCodes.ParameterTypeNotMatchInCrmServiceTokenGenerateService,
                    DefaultFormatting = "在Crm服务令牌生成服务{0}中,名称为{1}的参数期望类型为{2},而实际类型为{3}",
                    ReplaceParameters = new List <object>()
                    {
                        this.GetType().FullName, CrmServiceTokenGenerateServiceParameterNames.UserName, typeof(string).FullName, parameters[CrmServiceTokenGenerateServiceParameterNames.UserName].GetType().FullName
                    }
                };

                throw new UtilityException((int)Errors.ParameterTypeNotMatchInCrmServiceTokenGenerateService, fragment);
            }
            string strUserName = parameters[CrmServiceTokenGenerateServiceParameterNames.UserName].ToString();

            if (!parameters.ContainsKey(CrmServiceTokenGenerateServiceParameterNames.Password) || parameters[CrmServiceTokenGenerateServiceParameterNames.Password] == null)
            {
                fragment = new TextFragment()
                {
                    Code = TextCodes.NotFoundParameterInCrmServiceTokenGenerateService,
                    DefaultFormatting = "在Crm服务令牌生成服务{0}中,找不到名称为{1}的参数",
                    ReplaceParameters = new List <object>()
                    {
                        this.GetType().FullName, CrmServiceTokenGenerateServiceParameterNames.Password
                    }
                };

                throw new UtilityException((int)Errors.NotFoundParameterInCrmServiceTokenGenerateService, fragment);
            }
            if (!(parameters[CrmServiceTokenGenerateServiceParameterNames.Password] is string))
            {
                fragment = new TextFragment()
                {
                    Code = TextCodes.ParameterTypeNotMatchInCrmServiceTokenGenerateService,
                    DefaultFormatting = "在Crm服务令牌生成服务{0}中,名称为{1}的参数期望类型为{2},而实际类型为{3}",
                    ReplaceParameters = new List <object>()
                    {
                        this.GetType().FullName, CrmServiceTokenGenerateServiceParameterNames.Password, typeof(string).FullName, parameters[CrmServiceTokenGenerateServiceParameterNames.Password].GetType().FullName
                    }
                };

                throw new UtilityException((int)Errors.ParameterTypeNotMatchInCrmServiceTokenGenerateService, fragment);
            }
            string strPassword = parameters[CrmServiceTokenGenerateServiceParameterNames.Password].ToString();

            string strToken = null;

            await GetAdfsAuth(strAdfsUrl, strClientId, strRedirectUri, strCrmUrl, strUserName, strPassword, async (adfsAuth) =>
            {
                strToken = adfsAuth.AccessToken;
                await Task.FromResult(0);
            });

            return($"Bearer {strToken}");
        }
        public async Task <CrmRequestMessageHandleResult> ExecuteRequest(CrmRequestMessage request)
        {
            if (!(request is CrmRetrieveLookupAttributeReferenceRequestMessage))
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.CrmRequestMessageTypeNotMatch,
                    DefaultFormatting = "消息请求类型不匹配,期待的类型为{0},实际类型为{1},位置为{2}",
                    ReplaceParameters = new List <object>()
                    {
                        typeof(CrmRetrieveLookupAttributeReferenceRequestMessage).FullName, request.GetType().FullName, $"{ this.GetType().FullName }.ExecuteRequest"
                    }
                };

                throw new UtilityException((int)Errors.CrmRequestMessageTypeNotMatch, fragment);
            }

            var realRequest = request as CrmRetrieveLookupAttributeReferenceRequestMessage;

            //如果唯一键集合不为空,则使用唯一键作为主键,否则,使用Entity的Id作为主键
            var url = $"{realRequest.OrganizationURI}/api/data/v{realRequest.ApiVersion}/{realRequest.EntityName.ToPlural()}";

            if (realRequest.AlternateKeys != null && realRequest.AlternateKeys.Count > 0)
            {
                StringBuilder strAlternateKey = new StringBuilder();
                foreach (var keyItem in realRequest.AlternateKeys)
                {
                    strAlternateKey.Append(keyItem.Key);
                    strAlternateKey.Append("=");
                    strAlternateKey.Append(await _crmAlternateKeyTypeHandle.Convert(keyItem.Value));
                    strAlternateKey.Append(",");
                }

                if (strAlternateKey.Length > 0)
                {
                    strAlternateKey.Remove(strAlternateKey.Length - 1, 1);
                }

                url = $"{url}({strAlternateKey.ToString()})";
            }
            else
            {
                url = $"{url}({realRequest.EntityId.ToString()})";
            }

            url = $"{url}/{realRequest.AttributeName}/$ref";

            var headers = new Dictionary <string, IEnumerable <string> >();

            headers["OData-MaxVersion"] = new List <string> {
                "4.0"
            };
            headers["OData-Version"] = new List <string> {
                "4.0"
            };
            headers["Content-Type"] = new List <string> {
                "application/json"
            };
            headers["Content-Type-ChartSet"] = new List <string> {
                "utf-8"
            };
            headers["Accept"] = new List <string> {
                "application/json"
            };

            foreach (var itemHeader in realRequest.Headers)
            {
                headers[itemHeader.Key] = itemHeader.Value;
            }

            CrmRequestMessageHandleResult result = new CrmRequestMessageHandleResult();

            result.Url       = url;
            result.Method    = HttpMethod.Get;
            result.Headers   = headers;
            result.Extension = realRequest;

            return(await Task.FromResult(result));
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="endpoint"></param>
        /// <returns></returns>
        public async Task Update(ClientSMessageTypeListenerEndpoint endpoint)
        {
            await DBTransactionHelper.SqlTransactionWorkAsync(DBTypes.SqlServer, false, false, _messageQueueConnectionFactory.CreateAllForMessageQueueMain(), async (conn, transaction) =>
            {
                SqlTransaction sqlTran = null;
                if (sqlTran != null)
                {
                    sqlTran = (SqlTransaction)transaction;
                }
                await using (SqlCommand command = new SqlCommand()
                {
                    Connection = (SqlConnection)conn,
                    CommandType = CommandType.Text,
                    Transaction = sqlTran
                })
                {
                    command.CommandText = @"UPDATE [dbo].[ClientSMessageTypeListenerEndpoint]
                                               SET 
                                                  [name] =@name
                                                  ,[signaturekey] = @signaturekey
                                                  ,[modifytime] = GETUTCDATE()
                                             WHERE id=@id;";
                    SqlParameter parameter;
                    parameter = new SqlParameter("@id", SqlDbType.UniqueIdentifier)
                    {
                        Value = endpoint.ID
                    };
                    command.Parameters.Add(parameter);
                    parameter = new SqlParameter("@name", SqlDbType.NVarChar, 500)
                    {
                        Value = endpoint.Name
                    };
                    command.Parameters.Add(parameter);
                    parameter = new SqlParameter("@signaturekey", SqlDbType.NVarChar, 150)
                    {
                        Value = endpoint.SignatureKey
                    };
                    command.Parameters.Add(parameter);
                    await command.PrepareAsync();

                    try
                    {
                        await command.ExecuteNonQueryAsync();
                    }
                    catch (SqlException ex)
                    {
                        if (ex == null)
                        {
                            throw;
                        }
                        if (ex.Number == 2601)
                        {
                            var fragment = new TextFragment()
                            {
                                Code = TextCodes.ExistClientSMessageTypeListenerEndpointByName,
                                DefaultFormatting = "客户端消息类型监听终结点中存在相同的名称\"{0}\"数据",
                                ReplaceParameters = new List <object>()
                                {
                                    endpoint.Name
                                }
                            };

                            throw new UtilityException((int)Errors.ExistClientSMessageTypeListenerEndpointByName, fragment);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            });
        }
Ejemplo n.º 41
0
        private async Task DoProcessReceive(SocketAsyncEventArgs e, bool useSocket = false, byte[] buffer = null)
        {
            TcpAcceptContext token = (TcpAcceptContext)e.UserToken;
            var innerResult        = await InnerDoProcessReceive(e, useSocket, buffer);

            while (!innerResult.Complete)
            {
                innerResult = await InnerDoProcessReceive(e, true, innerResult.Buffer);
            }

            bool willRaiseEvent;
            //处理接收到的数据
            var strData = UTF8Encoding.UTF8.GetString(token.RetrieveBytes.ToArray());


            //创建接收处理上下文

            //检查是否是心跳包
            //心跳包的格式固定为字符串“HeartBeat”
            if (strData.ToLower() == _listener.HeartBeatSendData.ToLower())
            {
                //标识处理状态为成功,并停止计时
                token.ExecuteSuccess = true;
                token.Watch.Stop();
                await AddLog(token);


                token.LatestRunning = DateTime.UtcNow;

                var responseBytes = UTF8Encoding.UTF8.GetBytes(_emptyResponse);

                e.SetBuffer(responseBytes, 0, responseBytes.Length);

                willRaiseEvent = e.AcceptSocket.SendAsync(e);
                if (!willRaiseEvent)
                {
                    await ProcessSend(e);
                }

                return;
            }

            //如果收到的是空字节,表示客户端已经关闭,服务端也需要关闭
            if (token.RetrieveBytes.Count == 0)
            {
                lock (token.LockObj)
                {
                    token.Status = -1;
                }
                token.ReleaseReceiveSemaphore();
                return;
            }

            if (!_tcpDataExecuteFactories.TryGetValue(_listener.ExecuteDataFactoryType, out IFactory <ITcpDataExecute> tcpDataExecuteFactory))
            {
                lock (_tcpDataExecuteFactories)
                {
                    Type tcpDataExecuteFactoryType = Type.GetType(_listener.ExecuteDataFactoryType);

                    if (!_tcpDataExecuteFactories.TryGetValue(_listener.ExecuteDataFactoryType, out tcpDataExecuteFactory))
                    {
                        object objTcpDataExecuteFactory;
                        if (_listener.ExecuteDataFactoryTypeUseDI == true)
                        {
                            //通过DI容器创建
                            objTcpDataExecuteFactory = DIContainerContainer.Get(tcpDataExecuteFactoryType);
                        }
                        else
                        {
                            //通过反射创建
                            objTcpDataExecuteFactory = tcpDataExecuteFactoryType.Assembly.CreateInstance(tcpDataExecuteFactoryType.FullName);
                        }

                        if (!(objTcpDataExecuteFactory is IFactory <ITcpDataExecute>))
                        {
                            var fragment = new TextFragment()
                            {
                                Code = TextCodes.TcpDataExecuteTypeError,
                                DefaultFormatting = "Tcp监听{0}中,数据处理的工厂类型{1}未实现接口IFactory<ITcpDataExecute>",
                                ReplaceParameters = new List <object>()
                                {
                                    _listener.Name, _listener.ExecuteDataFactoryType
                                }
                            };

                            throw new UtilityException((int)Errors.TcpDataExecuteTypeError, fragment);
                        }

                        tcpDataExecuteFactory = (IFactory <ITcpDataExecute>)objTcpDataExecuteFactory;
                        _tcpDataExecuteFactories.Add(_listener.ExecuteDataFactoryType, tcpDataExecuteFactory);
                    }
                }
            }

            var tcpDataExecute = tcpDataExecuteFactory.Create();

            var byteResult = await tcpDataExecute.Execute(token.RetrieveBytes.ToArray());

            //标识处理状态为成功,并停止计时
            token.ExecuteSuccess = true;
            token.Watch.Stop();

            if (byteResult != null)
            {
                token.ResponseBytes = byteResult.ToList();
            }

            await AddLog(token);

            //发送返回值

            if (byteResult != null)
            {
                /*var bytes = UTF8Encoding.UTF8.GetBytes(strResult);
                 *
                 * var totalByteList = bytes.Length.ToBytes().ToList();
                 *
                 * totalByteList.AddRange(bytes);
                 *
                 * var totalBytes = totalByteList.ToArray();*/

                e.SetBuffer(byteResult, 0, byteResult.Length);
            }
            else
            {
                var responseBytes = UTF8Encoding.UTF8.GetBytes(_emptyResponse);
                e.SetBuffer(responseBytes, 0, responseBytes.Length);
            }


            willRaiseEvent = e.AcceptSocket.SendAsync(e);
            if (!willRaiseEvent)
            {
                await ProcessSend(e);
            }
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="endpoint"></param>
        /// <returns></returns>
        public async Task Add(ClientSMessageTypeListenerEndpoint endpoint)
        {
            await DBTransactionHelper.SqlTransactionWorkAsync(DBTypes.SqlServer, false, false, _messageQueueConnectionFactory.CreateAllForMessageQueueMain(), async (conn, transaction) =>
            {
                SqlTransaction sqlTran = null;
                if (sqlTran != null)
                {
                    sqlTran = (SqlTransaction)transaction;
                }
                await using (SqlCommand command = new SqlCommand()
                {
                    Connection = (SqlConnection)conn,
                    CommandType = CommandType.Text,
                    Transaction = sqlTran
                })
                {
                    SqlParameter parameter;
                    if (endpoint.ID == Guid.Empty)
                    {
                        command.CommandText = @"INSERT INTO [dbo].[ClientSMessageTypeListenerEndpoint]
                                                       ([id]
                                                       ,[name]
                                                       ,[signaturekey]
                                                       ,[createtime]
                                                       ,[modifytime])
                                                 VALUES
                                                       (DEFAULT
                                                       ,@name
                                                       ,@signaturekey
                                                       ,GETUTCDATE()
                                                       ,GETUTCDATE());
                                                SELECT @newid = id FROM [dbo].[ClientSMessageTypeListenerEndpoint] WHERE [sequence] = SCOPE_IDENTITY();";

                        parameter = new SqlParameter("@newid", SqlDbType.UniqueIdentifier)
                        {
                            Direction = ParameterDirection.Output
                        };
                        command.Parameters.Add(parameter);
                    }
                    else
                    {
                        command.CommandText = @"INSERT INTO [dbo].[ClientSMessageTypeListenerEndpoint]
                                                       ([id]
                                                       ,[name]
                                                       ,[signaturekey]
                                                       ,[createtime]
                                                       ,[modifytime])
                                                 VALUES
                                                       (@id
                                                       ,@name
                                                       ,@signaturekey
                                                       ,GETUTCDATE()
                                                       ,GETUTCDATE());";
                        parameter           = new SqlParameter("@id", SqlDbType.UniqueIdentifier)
                        {
                            Value = endpoint.ID
                        };
                        command.Parameters.Add(parameter);
                    }
                    parameter = new SqlParameter("@name", SqlDbType.NVarChar, 500)
                    {
                        Value = endpoint.Name
                    };
                    command.Parameters.Add(parameter);
                    parameter = new SqlParameter("@signaturekey", SqlDbType.NVarChar, 150)
                    {
                        Value = endpoint.SignatureKey
                    };
                    command.Parameters.Add(parameter);
                    await command.PrepareAsync();

                    try
                    {
                        await command.ExecuteNonQueryAsync();
                    }
                    catch (SqlException ex)
                    {
                        if (ex == null)
                        {
                            throw;
                        }
                        if (ex.Number == 2601)
                        {
                            var fragment = new TextFragment()
                            {
                                Code = TextCodes.ExistClientSMessageTypeListenerEndpointByName,
                                DefaultFormatting = "客户端消息类型监听终结点中存在相同的名称\"{0}\"数据",
                                ReplaceParameters = new List <object>()
                                {
                                    endpoint.Name
                                }
                            };

                            throw new UtilityException((int)Errors.ExistClientSMessageTypeListenerEndpointByName, fragment);
                        }
                        else
                        {
                            throw;
                        }
                    }
                    if (endpoint.ID == Guid.Empty)
                    {
                        endpoint.ID = (Guid)command.Parameters["@newid"].Value;
                    }
                    ;
                }
            });
        }
        public static void Run()
        {
            // ExStart:CreateMultiColumnPdf
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();

            Document doc = new Document();
            // Specify the left margin info for the PDF file
            doc.PageInfo.Margin.Left = 40;
            // Specify the Right margin info for the PDF file
            doc.PageInfo.Margin.Right = 40;
            Page page = doc.Pages.Add();

            Aspose.Pdf.Drawing.Graph graph1 = new Aspose.Pdf.Drawing.Graph(500, 2);
            // Add the line to paraphraphs collection of section object
            page.Paragraphs.Add(graph1);

            // Specify the coordinates for the line
            float[] posArr = new float[] { 1, 2, 500, 2 };
            Aspose.Pdf.Drawing.Line l1 = new Aspose.Pdf.Drawing.Line(posArr);
            graph1.Shapes.Add(l1);
            // Create string variables with text containing html tags

            string s = "<font face=\"Times New Roman\" size=4>" +

            "<strong> How to Steer Clear of money scams</<strong> "
            + "</font>";
            // Create text paragraphs containing HTML text

            HtmlFragment heading_text = new HtmlFragment(s);
            page.Paragraphs.Add(heading_text);

            Aspose.Pdf.FloatingBox box = new Aspose.Pdf.FloatingBox();
            // Add four columns in the section
            box.ColumnInfo.ColumnCount = 2;
            // Set the spacing between the columns
            box.ColumnInfo.ColumnSpacing = "5";

            box.ColumnInfo.ColumnWidths = "105 105";
            TextFragment text1 = new TextFragment("By A Googler (The Official Google Blog)");
            text1.TextState.FontSize = 8;
            text1.TextState.LineSpacing = 2;
            box.Paragraphs.Add(text1);
            text1.TextState.FontSize = 10;

            text1.TextState.FontStyle = FontStyles.Italic;
            // Create a graphs object to draw a line
            Aspose.Pdf.Drawing.Graph graph2 = new Aspose.Pdf.Drawing.Graph(50, 10);
            // Specify the coordinates for the line
            float[] posArr2 = new float[] { 1, 10, 100, 10 };
            Aspose.Pdf.Drawing.Line l2 = new Aspose.Pdf.Drawing.Line(posArr2);
            graph2.Shapes.Add(l2);

            // Add the line to paragraphs collection of section object
            box.Paragraphs.Add(graph2);

            TextFragment text2 = new TextFragment(@"Sed augue tortor, sodales id, luctus et, pulvinar ut, eros. Suspendisse vel dolor. Sed quam. Curabitur ut massa vitae eros euismod aliquam. Pellentesque sit amet elit. Vestibulum interdum pellentesque augue. Cras mollis arcu sit amet purus. Donec augue. Nam mollis tortor a elit. Nulla viverra nisl vel mauris. Vivamus sapien. nascetur ridiculus mus. Nam justo lorem, aliquam luctus, sodales et, semper sed, enim Nam justo lorem, aliquam luctus, sodales et,nAenean posuere ante ut neque. Morbi sollicitudin congue felis. Praesent turpis diam, iaculis sed, pharetra non, mollis ac, mauris. Phasellus nisi ipsum, pretium vitae, tempor sed, molestie eu, dui. Duis lacus purus, tristique ut, iaculis cursus, tincidunt vitae, risus. Sed commodo. *** sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam justo lorem, aliquam luctus, sodales et, semper sed, enim Nam justo lorem, aliquam luctus, sodales et, semper sed, enim Nam justo lorem, aliquam luctus, sodales et, semper sed, enim nAenean posuere ante ut neque. Morbi sollicitudin congue felis. Praesent turpis diam, iaculis sed, pharetra non, mollis ac, mauris. Phasellus nisi ipsum, pretium vitae, tempor sed, molestie eu, dui. Duis lacus purus, tristique ut, iaculis cursus, tincidunt vitae, risus. Sed commodo. *** sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed urna. . Duis convallis ultrices nisi. Maecenas non ligula. Nunc nibh est, tincidunt in, placerat sit amet, vestibulum a, nulla. Praesent porttitor turpis eleifend ante. Morbi sodales.nAenean posuere ante ut neque. Morbi sollicitudin congue felis. Praesent turpis diam, iaculis sed, pharetra non, mollis ac, mauris. Phasellus nisi ipsum, pretium vitae, tempor sed, molestie eu, dui. Duis lacus purus, tristique ut, iaculis cursus, tincidunt vitae, risus. Sed commodo. *** sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed urna. . Duis convallis ultrices nisi. Maecenas non ligula. Nunc nibh est, tincidunt in, placerat sit amet, vestibulum a, nulla. Praesent porttitor turpis eleifend ante. Morbi sodales.");
            box.Paragraphs.Add(text2);

            page.Paragraphs.Add(box);

            dataDir = dataDir + "CreateMultiColumnPdf_out.pdf";
            // Save PDF file
            doc.Save(dataDir);
            // ExEnd:CreateMultiColumnPdf            
            Console.WriteLine("\nMulti column pdf file created successfully.\nFile saved at " + dataDir);
        }
Ejemplo n.º 44
0
        public async Task <RealWorkfolwActivityDescription> Execute(string activityConfiguration)
        {
            XElement element = null;

            try
            {
                element = XElement.Parse(activityConfiguration);
            }
            catch (Exception ex)
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.RealWorkfolwActivityConfigurationParseXMLError,
                    DefaultFormatting = "工作流活动配置转换成XML时出错,活动配置:{0},错误原因:{1}",
                    ReplaceParameters = new List <object>()
                    {
                        activityConfiguration, ex.Message
                    }
                };

                var exception = new UtilityException((int)Errors.RealWorkfolwActivityConfigurationParseXMLError, fragment);
                exception.Data[UtilityExceptionDataKeys.Catch] = true;
                throw exception;
            }

            var idAttribute = element.Attribute("id");

            if (idAttribute == null)
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.RealWorkfolwActivityConfigurationParseXMLError,
                    DefaultFormatting = "工作流活动配置转换成XML时出错,活动配置:{0},错误原因:{1}",
                    ReplaceParameters = new List <object>()
                    {
                        activityConfiguration, new TextFragment()
                        {
                            Code = TextCodes.RealWorkfolwActivityConfigurationMissXMLAttribute, DefaultFormatting = "工作流活动配置缺少XML属性{0}", ReplaceParameters = new List <object>()
                            {
                                "id"
                            }
                        }
                    }
                };

                var exception = new UtilityException((int)Errors.RealWorkfolwActivityConfigurationParseXMLError, fragment);
                exception.Data[UtilityExceptionDataKeys.Catch] = true;
                throw exception;
            }

            if (!Guid.TryParse(idAttribute.Value, out Guid id))
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.RealWorkfolwActivityConfigurationParseXMLError,
                    DefaultFormatting = "工作流活动配置转换成XML时出错,活动配置:{0},错误原因:{1}",
                    ReplaceParameters = new List <object>()
                    {
                        activityConfiguration, new TextFragment()
                        {
                            Code = TextCodes.RealWorkfolwActivityConfigurationIdAttributeParseError, DefaultFormatting = "工作流活动配置的Id属性不能转换成Guid,当前的Id属性为{0}", ReplaceParameters = new List <object>()
                            {
                                idAttribute.Value
                            }
                        }
                    }
                };

                var exception = new UtilityException((int)Errors.RealWorkfolwActivityConfigurationParseXMLError, fragment);
                exception.Data[UtilityExceptionDataKeys.Catch] = true;
                throw exception;
            }

            if (!_resolveFactories.TryGetValue(element.Name.ToString().ToLower(), out IFactory <IRealWorkfolwActivityResolve> resolveFactory))
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.NotFoundRealWorkfolwActivityResolveByName,
                    DefaultFormatting = "找不到名称为{0}的工作流活动解析",
                    ReplaceParameters = new List <object>()
                    {
                        element.Name.ToString().ToLower()
                    }
                };

                throw new UtilityException((int)Errors.NotFoundRealWorkfolwActivityResolveByName, fragment);
            }

            var description = await resolveFactory.Create().Execute(activityConfiguration);

            description.InputParameters = await _activityConfigurationService.ResolveActivityInputParameters(activityConfiguration);

            description.OutputParameters = await _activityConfigurationService.ResolveActivityOutputParameters(activityConfiguration);

            description.Name = element.Name.ToString().ToLower();
            description.Id   = id;
            return(description);
        }
        public static void Run()
        {
            // ExStart:ApplyNumberStyle
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Headings();

            Document pdfDoc = new Document();
            pdfDoc.PageInfo.Width = 612.0;
            pdfDoc.PageInfo.Height = 792.0;
            pdfDoc.PageInfo.Margin = new Aspose.Pdf.MarginInfo();
            pdfDoc.PageInfo.Margin.Left = 72;
            pdfDoc.PageInfo.Margin.Right = 72;
            pdfDoc.PageInfo.Margin.Top = 72;
            pdfDoc.PageInfo.Margin.Bottom = 72;

            Aspose.Pdf.Page pdfPage = pdfDoc.Pages.Add();
            pdfPage.PageInfo.Width = 612.0;
            pdfPage.PageInfo.Height = 792.0;
            pdfPage.PageInfo.Margin = new Aspose.Pdf.MarginInfo();
            pdfPage.PageInfo.Margin.Left = 72;
            pdfPage.PageInfo.Margin.Right = 72;
            pdfPage.PageInfo.Margin.Top = 72;
            pdfPage.PageInfo.Margin.Bottom = 72;

            Aspose.Pdf.FloatingBox floatBox = new Aspose.Pdf.FloatingBox();
            floatBox.Margin = pdfPage.PageInfo.Margin;

            pdfPage.Paragraphs.Add(floatBox);

            TextFragment textFragment = new TextFragment();
            TextSegment segment = new TextSegment();

            Aspose.Pdf.Heading heading = new Aspose.Pdf.Heading(1);
            heading.IsInList = true;
            heading.StartNumber = 1;
            heading.Text = "List 1";
            heading.Style = NumberingStyle.NumeralsRomanLowercase;
            heading.IsAutoSequence = true;

            floatBox.Paragraphs.Add(heading);

            Aspose.Pdf.Heading heading2 = new Aspose.Pdf.Heading(1);
            heading2.IsInList = true;
            heading2.StartNumber = 13;
            heading2.Text = "List 2";
            heading2.Style = NumberingStyle.NumeralsRomanLowercase;
            heading2.IsAutoSequence = true;

            floatBox.Paragraphs.Add(heading2);

            Aspose.Pdf.Heading heading3 = new Aspose.Pdf.Heading(2);
            heading3.IsInList = true;
            heading3.StartNumber = 1;
            heading3.Text = "the value, as of the effective date of the plan, of property to be distributed under the plan onaccount of each allowed";
            heading3.Style = NumberingStyle.LettersLowercase;
            heading3.IsAutoSequence = true;

            floatBox.Paragraphs.Add(heading3);
            dataDir = dataDir + "ApplyNumberStyle_out.pdf";
            pdfDoc.Save(dataDir);
            // ExEnd:ApplyNumberStyle
            Console.WriteLine("\nNumber style applied successfully in headings.\nFile saved at " + dataDir);            
        }
Ejemplo n.º 46
0
        public static void AddStrikeOutText()
        {
            try
            {
                // ExStart:AddStrikeOutText
                // The path to the documents directory.
                string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
                // Open document
                Document pdfDocument = new Document();
                // Get particular page
                Page pdfPage = (Page)pdfDocument.Pages.Add();

                // Create text fragment
                TextFragment textFragment = new TextFragment("main text");
                textFragment.Position = new Position(100, 600);

                // Set text properties
                textFragment.TextState.FontSize = 12;
                textFragment.TextState.Font = FontRepository.FindFont("TimesNewRoman");
                textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray;
                textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.Red;
                // Set StrikeOut property
                textFragment.TextState.StrikeOut = true;
                // Mark text as Bold
                textFragment.TextState.FontStyle = FontStyles.Bold;

                // Create TextBuilder object
                TextBuilder textBuilder = new TextBuilder(pdfPage);
                // Append the text fragment to the PDF page
                textBuilder.AppendText(textFragment);


                dataDir = dataDir + "AddStrikeOutText_out.pdf";

                // Save resulting PDF document.
                pdfDocument.Save(dataDir);
                // ExEnd:AddStrikeOutText
                Console.WriteLine("\nStrikeOut text added successfully.\nFile saved at " + dataDir);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 47
0
        public static void LoadingFontFromStream()
        {
            // ExStart:LoadingFontFromStream
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
            string fontFile = "";

            // Load input PDF file
            Document doc = new Document( dataDir + "input.pdf");
            // Create text builder object for first page of document
            TextBuilder textBuilder = new TextBuilder(doc.Pages[1]);
            // Create text fragment with sample string
            TextFragment textFragment = new TextFragment("Hello world");

            if (fontFile != "")
            {
                // Load the TrueType font into stream object
                using (FileStream fontStream = File.OpenRead(fontFile))
                {
                    // Set the font name for text string
                    textFragment.TextState.Font = FontRepository.OpenFont(fontStream, FontTypes.TTF);
                    // Specify the position for Text Fragment
                    textFragment.Position = new Position(10, 10);
                    // Add the text to TextBuilder so that it can be placed over the PDF file
                    textBuilder.AppendText(textFragment);
                }

                dataDir = dataDir + "LoadingFontFromStream_out.pdf";

                // Save resulting PDF document.
                doc.Save(dataDir);
            }
            // ExEnd:LoadingFontFromStream
            Console.WriteLine("\nFont from stream loaded successfully.\nFile saved at " + dataDir);
        }
Ejemplo n.º 48
0
            public async Task Execute(IJobExecutionContext context)
            {
                //获取调度动作名称
                var actionName = context.JobDetail.JobDataMap.GetString("ActionName");
                //获取调度动作名称
                var groupName = context.JobDetail.JobDataMap.GetString("GroupName");
                //获取初始化类型
                var initType = context.JobDetail.JobDataMap.GetString("InitType");
                //获取初始化配置
                var initConfiguration = context.JobDetail.JobDataMap.GetString("InitConfiguration");


                try
                {
                    if (!_actionRunStatuses.TryGetValue(actionName, out ScheduleActionRunStatus runStatus))
                    {
                        var scheduleAction = await _scheduleActionRepository.QueryByName(actionName);

                        if (scheduleAction == null)
                        {
                            var fragment = new TextFragment()
                            {
                                Code = TextCodes.NotFoundScheduleActionByName,
                                DefaultFormatting = "找不到名称为{0}的调度动作",
                                ReplaceParameters = new List <object>()
                                {
                                    actionName
                                }
                            };

                            throw new UtilityException((int)Errors.NotFoundScheduleActionByName, fragment);
                        }
                        runStatus = new ScheduleActionRunStatus()
                        {
                            Action = scheduleAction, Status = 0
                        };
                        _actionRunStatuses.Add(actionName, runStatus);
                    }


                    if (runStatus.Status == 0)
                    {
                        /* var environmentClaimGenerator = await _environmentClaimGeneratorRepository.QueryByName(_environmentClaimGeneratorName);
                         * var claimContextGenerator = await _claimContextGeneratorRepository.QueryByName(_claimContextGeneratorName);
                         *
                         *
                         *
                         * if (environmentClaimGenerator == null)
                         * {
                         *   var fragment = new TextFragment()
                         *   {
                         *       Code = TextCodes.NotFoundEnvironmentClaimGeneratorByName,
                         *       DefaultFormatting = "没有找到名称为{0}的上下文生成器",
                         *       ReplaceParameters = new List<object>() { _environmentClaimGeneratorName }
                         *   };
                         *
                         *   throw new UtilityException((int)Errors.NotFoundEnvironmentClaimGeneratorByName, fragment);
                         * }
                         *
                         * if (claimContextGenerator == null)
                         * {
                         *   var fragment = new TextFragment()
                         *   {
                         *       Code = TextCodes.NotFoundClaimContextGeneratorByName,
                         *       DefaultFormatting = "没有找到名称为{0}的上下文生成器",
                         *       ReplaceParameters = new List<object>() { _claimContextGeneratorName }
                         *   };
                         *
                         *   throw new UtilityException((int)Errors.NotFoundClaimContextGeneratorByName, fragment);
                         * }
                         *
                         * var claims = await environmentClaimGenerator.Generate();
                         * claimContextGenerator.ContextInit(claims.Claims);
                         */
                        using (var diContainer = DIContainerContainer.CreateContainer())
                        {
                            var orginialDI = ContextContainer.GetValue <IDIContainer>("DI");
                            try
                            {
                                ContextContainer.SetValue <IDIContainer>("DI", diContainer);

                                var initGeneratorService = getInitGeneratorService(initType);
                                var initService          = await initGeneratorService.Generator(initConfiguration);

                                initService.Init();

                                if (_useLog)
                                {
                                    LoggerHelper.LogInformation(_informationCategory, $"ScheduleAction {actionName} in Grioup {groupName} start");
                                }
                                var actionResult = await runStatus.Action.Execute();

                                runStatus.Result = actionResult;

                                if (runStatus.Result.Polling)
                                {
                                    runStatus.Status = 1;
                                }
                                else
                                {
                                    await runStatus.Result.Stop();

                                    if (_useLog)
                                    {
                                        LoggerHelper.LogInformation(_informationCategory, $"ScheduleAction {actionName} in Grioup {groupName} stop");
                                    }
                                }
                            }
                            finally
                            {
                                ContextContainer.SetValue <IDIContainer>("DI", orginialDI);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LoggerHelper.LogError(_errorCategory, $"ScheduleAction {actionName} in Grioup {groupName} start error,detail:{ex.Message},stacktrace:{ex.StackTrace}");
                    //throw;
                }
            }
Ejemplo n.º 49
0
        public static void AddTextUsingTextParagraph()
        {
            // ExStart:AddTextUsingTextParagraph
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
            // Open document
            Document doc = new Document();
            // Add page to pages collection of Document object
            Page page = doc.Pages.Add();
            TextBuilder builder = new TextBuilder(page);
            // Create text paragraph
            TextParagraph paragraph = new TextParagraph();
            // Set subsequent lines indent
            paragraph.SubsequentLinesIndent = 20;
            // Specify the location to add TextParagraph
            paragraph.Rectangle = new Aspose.Pdf.Rectangle(100, 300, 200, 700);
            // Specify word wraping mode
            paragraph.FormattingOptions.WrapMode = TextFormattingOptions.WordWrapMode.ByWords;
            // Create text fragment
            TextFragment fragment1 = new TextFragment("the quick brown fox jumps over the lazy dog");
            fragment1.TextState.Font = FontRepository.FindFont("Times New Roman");
            fragment1.TextState.FontSize = 12;
            // Add fragment to paragraph
            paragraph.AppendLine(fragment1);
            // Add paragraph
            builder.AppendParagraph(paragraph);

            dataDir = dataDir + "AddTextUsingTextParagraph_out.pdf";

            // Save resulting PDF document.
            doc.Save(dataDir);
            
            // ExEnd:AddTextUsingTextParagraph
            Console.WriteLine("\nText using text paragraph added successfully.\nFile saved at " + dataDir);
        }
Ejemplo n.º 50
0
        public ActionResult ApartmentsToPDF()
        {
            ViewData["Report"] = reportTitle2;
            var appartments = GererateListOfApartments()
                              .GroupBy(apt => apt.Region, (key, group) =>
                                       new GroupViewModel <string, ApartmentView>
            {
                Key    = key,
                Values = group.Select(g =>
                                      new ApartmentView
                {
                    City = g.City, Address = g.Address, TotalArea = g.TotalArea
                }
                                      )
            });


            // Create new a PDF document
            var document = new Document
            {
                PageInfo = new PageInfo {
                    Margin = new MarginInfo(28, 28, 28, 42)
                }
            };

            var pdfPage = document.Pages.Add();

            // Initializes a new instance of the TextFragment for report's title
            var textFragment = new TextFragment(reportTitle2);

            // Set text properties
            textFragment.TextState.FontSize  = 12;
            textFragment.TextState.Font      = FontRepository.FindFont("TimesNewRoman");
            textFragment.TextState.FontStyle = FontStyles.Bold;

            // Initializes a new instance of the Table
            Table table = new Table
            {
                // Set column auto widths of the table
                ColumnWidths     = "10 10 10",
                ColumnAdjustment = ColumnAdjustment.AutoFitToContent,
                // Set cell padding
                DefaultCellPadding = new MarginInfo(5, 5, 5, 5),
                // Set the table border color as Black
                Border = new BorderInfo(BorderSide.All, .5f, Color.Black),
                // Set the border for table cells as Black
                DefaultCellBorder = new BorderInfo(BorderSide.All, .2f, Color.Black),
            };

            table.DefaultCellTextState = new TextState("TimesNewRoman", 10);
            table.Margin.Left          = 40;
            //Repeat Header
            table.RepeatingRowsCount = 1;

            table.ImportGroupedData(appartments);

            // Add text fragment object to first page of input document
            pdfPage.Paragraphs.Add(textFragment);
            // Add table object to first page of input document
            pdfPage.Paragraphs.Add(table);


            using (var streamOut = new MemoryStream())
            {
                document.Save(streamOut);
                return(new FileContentResult(streamOut.ToArray(), "application/pdf")
                {
                    FileDownloadName = "apartmnets.pdf"
                });
            }
        }
Ejemplo n.º 51
0
        public static void OTFFont()
        {
            // ExStart:OTFFont
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
            // Create new document instance
            Document pdfDocument = new Document();
            // Add page to pages collection of PDF file
            Aspose.Pdf.Page page = pdfDocument.Pages.Add();
            // Create TextFragment instnace with sample text
            TextFragment fragment = new TextFragment("Sample Text in OTF font");
            // Find font inside system font directory
            // Fragment.TextState.Font = FontRepository.FindFont("HelveticaNeueLT Pro 45 Lt");
            // Or you can even specify the path of OTF font in system directory
            fragment.TextState.Font = FontRepository.OpenFont(dataDir + "space age.otf");
            // Specify to emend font inside PDF file, so that its displayed properly,
            // Even if specific font is not installed/present over target machine
            fragment.TextState.Font.IsEmbedded = true;
            // Add TextFragment to paragraphs collection of Page instance
            page.Paragraphs.Add(fragment);

            dataDir = dataDir + "OTFFont_out.pdf";

            // Save resulting PDF document.
            pdfDocument.Save(dataDir);

            // ExEnd:OTFFont
            Console.WriteLine("\nOTF font used successfully.\nFile saved at " + dataDir);
        }
Ejemplo n.º 52
0
        public async Task Execute(MatrixDataHandler handler, int skip, int size, int paralleNumber, Func <MatrixDataRow, int, Task> rowCompleteAction, Func <MatrixDataRow, int, Exception, Task> rowExceptionAction)
        {
            if (!_matrixDataHandlerServiceFactories.TryGetValue(handler.Type, out IFactory <IMatrixDataHandlerService> serviceFactory))
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.NotFoundMatrixDataHandlerServiceByType,
                    DefaultFormatting = "找不到类型为{0}的矩阵数据处理方服务,发生位置:{1}",
                    ReplaceParameters = new List <object>()
                    {
                        handler.Type, $"{this.GetType().FullName}.MatrixDataHandlerServiceFactories"
                    }
                };
                throw new UtilityException((int)Errors.NotFoundMatrixDataHandlerServiceByType, fragment);
            }

            var service = serviceFactory.Create();
            MatrixDataHandlerContext context = new MatrixDataHandlerContext();
            await service.PreExecute(context);

            await ParallelHelper.RunCircle(paralleNumber, async (int index) =>
            {
                int start   = index *size + skip;
                bool result = true;
                await handler.Provider.ExecuteAll(start, size, async(rowList) =>
                {
                    if (rowList.Count < size)
                    {
                        result = false;
                    }

                    if (rowList.Count > 0)
                    {
                        for (var i = 0; i <= rowList.Count - 1; i++)
                        {
                            start++;
                            bool executeResult = true;
                            try
                            {
                                await service.Execute(context, handler.Configuration, rowList[i]);
                            }
                            catch (Exception ex)
                            {
                                executeResult = false;
                                await rowExceptionAction(rowList[i], start, ex);
                            }

                            if (executeResult)
                            {
                                await rowCompleteAction(rowList[i], start);
                            }
                        }
                    }

                    return(false);
                });

                return(await Task.FromResult(result));
            });

            await service.PostExecute(context);
        }
        public static void AddImageAndTable()
        {
            // ExStart:AddImageAndTable
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
            
            Document doc = new Document();
            Page page = doc.Pages.Add();
            TextFragment text = new TextFragment("some text");
            page.Paragraphs.Add(text);

            text.FootNote = new Note();
            Aspose.Pdf.Image image = new Aspose.Pdf.Image();
            image.File = dataDir + "aspose-logo.jpg";
            image.FixHeight = 20;
            text.FootNote.Paragraphs.Add(image);
            TextFragment footNote = new TextFragment("footnote text");
            footNote.TextState.FontSize = 20;
            footNote.IsInLineParagraph = true;
            text.FootNote.Paragraphs.Add(footNote);
            Aspose.Pdf.Table table = new Aspose.Pdf.Table();
            table.Rows.Add().Cells.Add().Paragraphs.Add(new TextFragment("Row 1 Cell 1"));
            text.FootNote.Paragraphs.Add(table);

            dataDir = dataDir + "AddImageAndTable_out.pdf";

            // Save resulting PDF document.
            doc.Save(dataDir);
            // ExEnd:AddImageAndTable
            Console.WriteLine("\nTable and image added successfully to FootNote.\nFile saved at " + dataDir);
        }
Ejemplo n.º 54
0
        /// <summary> Parses a string to find placeholders of format ${placeholder}.
        /// <para>
        /// Example: "My ${thing} is ${color}"
        /// </para>
        /// <para>
        /// The example above parses into 4 fragements: a text fragment of value "My ",
        /// a parameter fragment "thing", a text fragement " is " and a parameter
        /// fragment "color".
        /// </para>
        /// </summary>
        /// <param name="parseString">is the string to parse
        /// </param>
        /// <returns> list of fragements that can be either text fragments or placeholder fragments
        /// </returns>
        /// <throws>  PlaceholderParseException if the string cannot be parsed to indicate syntax errors </throws>

        public static IList <Fragment> ParsePlaceholder(String parseString)
        {
            List <Fragment> result          = new List <Fragment>();
            int             currOutputIndex = 0;
            int             currSearchIndex = 0;

            while (true)
            {
                if (currSearchIndex == parseString.Length)
                {
                    break;
                }

                int startIndex = parseString.IndexOf("${", currSearchIndex);
                if (startIndex == -1)
                {
                    // no more parameters, add any remainder of string
                    if (currOutputIndex < parseString.Length)
                    {
                        String       endString    = parseString.Substring(currOutputIndex);
                        TextFragment textFragment = new TextFragment(endString);
                        result.Add(textFragment);
                    }
                    break;
                }
                // add text so far
                if (startIndex > 0)
                {
                    String textSoFar = parseString.Substring(currOutputIndex, startIndex - currOutputIndex);
                    if (textSoFar.Length != 0)
                    {
                        result.Add(new TextFragment(textSoFar));
                    }
                }
                // check if the parameter is escaped
                if ((startIndex > 0) && (parseString[startIndex - 1] == '$'))
                {
                    currOutputIndex = startIndex + 1;
                    currSearchIndex = startIndex + 1;
                    continue;
                }

                int endIndex = parseString.IndexOf("}", startIndex);
                if (endIndex == -1)
                {
                    throw new PlaceholderParseException("Syntax error in property or variable: '" + parseString.Substring(startIndex) + "'");
                }

                // add placeholder
                String            between           = parseString.Substring(startIndex + 2, endIndex - startIndex - 2);
                ParameterFragment parameterFragment = new ParameterFragment(between);
                result.Add(parameterFragment);
                currOutputIndex = endIndex + 1;
                currSearchIndex = endIndex;
            }

            // Combine adjacent text fragements
            var fragments = new LinkedList <Fragment>();

            fragments.AddLast(result[0]);
            for (int i = 1; i < result.Count; i++)
            {
                Fragment fragment = result[i];
                if (!(result[i] is TextFragment))
                {
                    fragments.AddLast(fragment);
                    continue;
                }
                if (!(fragments.Last.Value is TextFragment))
                {
                    fragments.AddLast(fragment);
                    continue;
                }
                TextFragment textFragment = (TextFragment)fragments.Last.Value;
                fragments.RemoveLast();
                fragments.AddLast(new TextFragment(textFragment.Value + fragment.Value));
            }

            return(new List <Fragment>(fragments));
        }
Ejemplo n.º 55
0
		public IEnumerable<NewFolding> CreateNewFoldings(ITextSource document)
		{
			List<NewFolding> newFoldings = new List<NewFolding>();
            _procList = new List<ProcListItem>();

            int startPos = 0;
            int len = document.TextLength;

            int currentStart = 0;

            bool MethodIsOpen = false;
            string MethodName ="";
            string EndToken = null;

            int PreCommentStart = -1;

            //var Reader = document.CreateReader();

            string FullText = document.Text;
            int DocLine = 0;
            int MethodStart = 0;

            const string kProcStart = "ПРОЦЕДУРА";
            const string kProcEnd = "КОНЕЦПРОЦЕДУРЫ";
            const string kFuncStart = "ФУНКЦИЯ";
            const string kFuncEnd = "КОНЕЦФУНКЦИИ";

            char[] trimArr = new char[]{' ','\t'};

            do
            {
                int prev_start = startPos;
                string lineText = ReadLine(FullText, ref startPos);
                
                DocLine++;

                if (lineText == null)
                {
                    break;
                }
                
                TextFragment tf = new TextFragment();
                tf.offset = prev_start;
                tf.len = lineText.Length;

                //startPos += lineText.Length + 2;

                if (!MethodIsOpen)
                {
                    bool CommentBreak = false;
                    
                    if (lineText.StartsWith("//"))
                    {
                        if (PreCommentStart < 0)
                        {
                            PreCommentStart = tf.offset + tf.len;
                        }
                    }
                    else
                    {
                        CommentBreak = true;
                    }
                    
                    if (LineIsKeyword(lineText.TrimStart(trimArr), kProcStart))
                    {
                        MethodIsOpen = true;
                        MethodName = ScanForParamList(FullText, prev_start+kProcStart.Length);
                        EndToken = kProcEnd;
                        MethodStart = DocLine;
                    }
                    else if(LineIsKeyword(lineText.TrimStart(trimArr), kFuncStart))
                    {
                        MethodIsOpen = true;
                        MethodName = ScanForParamList(FullText, prev_start + kFuncStart.Length);
                        EndToken = kFuncEnd;
                        MethodStart = DocLine;
                    }

                    if (MethodIsOpen)
                    {
                        currentStart = tf.offset + tf.len;

                        if (PreCommentStart >= 0)
                        {
                            var Folding = new NewFolding(PreCommentStart, tf.offset-1);
                            newFoldings.Add(Folding);
                            PreCommentStart = -1;
                        }
                    }
                    else if(CommentBreak)
                    {
                        PreCommentStart = -1;
                    }
                    
                }
                else if (LineIsKeyword(lineText.TrimStart(trimArr), EndToken))
                {
                    var Folding = new NewFolding(currentStart, tf.offset + tf.len);
                    newFoldings.Add(Folding);

                    if (MethodName != "")
                    {
                        ProcListItem pli = new ProcListItem();
                        pli.Name = MethodName;
                        pli.StartLine = MethodStart;
                        pli.EndLine = DocLine;
                        pli.ListIndex = _procList.Count;

                        _procList.Add(pli);
                        
                        MethodName = "";
                    }

                    MethodIsOpen = false;
                }
                
            }
            while (true);

			return newFoldings;
		}
        public static void CreateEndNotes()
        {
            // ExStart:CreateEndNotes
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
            // Create Document instance
            Document doc = new Document();
            // Add page to pages collection of PDF
            Page page = doc.Pages.Add();
            // Create TextFragment instance
            TextFragment text = new TextFragment("Hello World");
            // Set FootNote value for TextFragment
            text.EndNote = new Note("sample End note");
            // Specify custom label for FootNote
            text.EndNote.Text = " Aspose(2015)";
            // Add TextFragment to paragraphs collection of first page of document
            page.Paragraphs.Add(text);

            dataDir = dataDir + "CreateEndNotes_out.pdf";
            // Save resulting PDF document.
            doc.Save(dataDir);
            // ExEnd:CreateEndNotes
            Console.WriteLine("\nEndNotes created successfully.\nFile saved at " + dataDir);
        }        
Ejemplo n.º 57
0
        public async Task Acquire(string configuration, string resourceName, int expireMillisecond)
        {
            var configurationObj   = JsonSerializerHelper.Deserialize <Configuration>(configuration);
            var redisClientFactory = await _redisClientFactoryRepositoryCacheProxy.QueryByName(configurationObj.RedisClientFactoryName);

            if (redisClientFactory == null)
            {
                var fragment = new TextFragment()
                {
                    Code = TextCodes.NotFoundRedisClientFactoryByName,
                    DefaultFormatting = "找不到名称为{0}的Redis客户端工厂",
                    ReplaceParameters = new List <object>()
                    {
                        configurationObj.RedisClientFactoryName
                    }
                };

                throw new UtilityException((int)Errors.NotFoundRedisClientFactoryByName, fragment);
            }
            //获取Redis客户端
            var redisClient = await redisClientFactory.GenerateClient();

            while (true)
            {
                //尝试在Redis生成Hash键,确保Redis中有值
                await redisClient.HSetNxAsync(resourceName, _datetimeField, DateTime.UtcNow.Ticks);

                await redisClient.HSetNxAsync(resourceName, _count, configurationObj.TokenMax);

                await redisClient.HSetNxAsync(resourceName, _version, Guid.NewGuid().ToString());

                //计算当前时刻令牌桶中应该有的数量
                var dict = await redisClient.HGetAllAsync(resourceName);

                var dictDatetime = new DateTime(long.Parse(dict[_datetimeField]));
                var dictCount    = int.Parse(dict[_count]);
                var now          = DateTime.UtcNow;
                var shouldCount  = ((long)(now - dictDatetime).TotalMilliseconds / configurationObj.TokenDurationMillisecond) * configurationObj.TokenDurationNumber;
                if (shouldCount + dictCount > configurationObj.TokenMax)
                {
                    shouldCount = configurationObj.TokenMax - dictCount;
                }

                string strLua = getLua();


                var execResult = (int)await redisClient.EvalAsync(strLua, resourceName, (int)shouldCount, now.Ticks, dict[_version], Guid.NewGuid().ToString());

                int waitMillisecond = 0;
                if (execResult == 1)
                {
                    break;
                }
                else
                {
                    if (expireMillisecond > 0)
                    {
                        if (waitMillisecond >= expireMillisecond)
                        {
                            var fragment = new TextFragment()
                            {
                                Code = TextCodes.AcquireRedisLimitTokenExpire,
                                DefaultFormatting = "从Redis限流令牌桶中获取令牌超时,请求的令牌桶名称为{0},Redis客户端工厂名称为{1}",
                                ReplaceParameters = new List <object>()
                                {
                                    resourceName, configurationObj.RedisClientFactoryName
                                }
                            };

                            throw new UtilityException((int)Errors.AcquireRedisLimitTokenExpire, fragment);
                        }
                    }

                    await Task.Delay(expireMillisecond);

                    if (expireMillisecond > 0)
                    {
                        waitMillisecond += expireMillisecond;
                    }
                }
            }
        }
        public static void Run()
        {
            // ExStart:ReplaceableSymbolsInHeaderFooter
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();

            Document doc = new Document();
            Page page = doc.Pages.Add();

            MarginInfo marginInfo = new MarginInfo();
            marginInfo.Top = 90;
            marginInfo.Bottom = 50;
            marginInfo.Left = 50;
            marginInfo.Right = 50;
            // Assign the marginInfo instance to Margin property of sec1.PageInfo
            page.PageInfo.Margin = marginInfo;

            HeaderFooter hfFirst = new HeaderFooter();
            page.Header = hfFirst;
            hfFirst.Margin.Left = 50;
            hfFirst.Margin.Right = 50;

            // Instantiate a Text paragraph that will store the content to show as header
            TextFragment t1 = new TextFragment("report title");
            t1.TextState.Font = FontRepository.FindFont("Arial");
            t1.TextState.FontSize = 16;
            t1.TextState.ForegroundColor = Aspose.Pdf.Color.Black;
            t1.TextState.FontStyle = FontStyles.Bold;
            t1.TextState.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Center;
            t1.TextState.LineSpacing = 5f;
            hfFirst.Paragraphs.Add(t1);

            TextFragment t2 = new TextFragment("Report_Name");
            t2.TextState.Font = FontRepository.FindFont("Arial");
            t2.TextState.ForegroundColor = Aspose.Pdf.Color.Black;
            t2.TextState.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Center;
            t2.TextState.LineSpacing = 5f;
            t2.TextState.FontSize = 12;
            hfFirst.Paragraphs.Add(t2);

            // Create a HeaderFooter object for the section
            HeaderFooter hfFoot = new HeaderFooter();
            // Set the HeaderFooter object to odd & even footer
            page.Footer = hfFoot;
            hfFoot.Margin.Left = 50;
            hfFoot.Margin.Right = 50;

            // Add a text paragraph containing current page number of total number of pages
            TextFragment t3 = new TextFragment("Generated on test date");
            TextFragment t4 = new TextFragment("report name ");
            TextFragment t5 = new TextFragment("Page $p of $P");

            // Instantiate a table object
            Table tab2 = new Table();

            // Add the table in paragraphs collection of the desired section
            hfFoot.Paragraphs.Add(tab2);

            // Set with column widths of the table
            tab2.ColumnWidths = "165 172 165";

            // Create rows in the table and then cells in the rows
            Row row3 = tab2.Rows.Add();

            row3.Cells.Add();
            row3.Cells.Add();
            row3.Cells.Add();

            // Set the vertical allignment of the text as center alligned
            row3.Cells[0].Alignment = Aspose.Pdf.HorizontalAlignment.Left;
            row3.Cells[1].Alignment = Aspose.Pdf.HorizontalAlignment.Center;
            row3.Cells[2].Alignment = Aspose.Pdf.HorizontalAlignment.Right;

            row3.Cells[0].Paragraphs.Add(t3);
            row3.Cells[1].Paragraphs.Add(t4);
            row3.Cells[2].Paragraphs.Add(t5);

            // Sec1.Paragraphs.Add(New Text("Aspose.Total for Java is a compilation of every Java component offered by Aspose. It is compiled on a#$NL" + "daily basis to ensure it contains the most up to date versions of each of our Java components. #$NL " + "Using Aspose.Total for Java developers can create a wide range of applications. #$NL #$NL #$NP" + "Aspose.Total for Java is a compilation of every Java component offered by Aspose. It is compiled on a#$NL" + "daily basis to ensure it contains the most up to date versions of each of our Java components. #$NL " + "Using Aspose.Total for Java developers can create a wide range of applications. #$NL #$NL #$NP" + "Aspose.Total for Java is a compilation of every Java component offered by Aspose. It is compiled on a#$NL" + "daily basis to ensure it contains the most up to date versions of each of our Java components. #$NL " + "Using Aspose.Total for Java developers can create a wide range of applications. #$NL #$NL"))
            Table table = new Table();

            table.ColumnWidths = "33% 33% 34%";
            table.DefaultCellPadding = new MarginInfo();
            table.DefaultCellPadding.Top = 10;
            table.DefaultCellPadding.Bottom = 10;

            // Add the table in paragraphs collection of the desired section
            page.Paragraphs.Add(table);

            // Set default cell border using BorderInfo object
            table.DefaultCellBorder = new BorderInfo(BorderSide.All, 0.1f);

            // Set table border using another customized BorderInfo object
            table.Border = new BorderInfo(BorderSide.All, 1f);

            table.RepeatingRowsCount = 1;

            // Create rows in the table and then cells in the rows
            Row row1 = table.Rows.Add();

            row1.Cells.Add("col1");
            row1.Cells.Add("col2");
            row1.Cells.Add("col3");
            const string CRLF = "\r\n";
            for (int i = 0; i <= 10; i++)
            {
                Row row = table.Rows.Add();
                row.IsRowBroken = true;
                for (int c = 0; c <= 2; c++)
                {
                    Cell c1;
                    if (c == 2)
                        c1 = row.Cells.Add("Aspose.Total for Java is a compilation of every Java component offered by Aspose. It is compiled on a" + CRLF + "daily basis to ensure it contains the most up to date versions of each of our Java components. " + CRLF + "daily basis to ensure it contains the most up to date versions of each of our Java components. " + CRLF + "Using Aspose.Total for Java developers can create a wide range of applications.");
                    else
                        c1 = row.Cells.Add("item1" + c);
                    c1.Margin = new MarginInfo();
                    c1.Margin.Left = 30;
                    c1.Margin.Top = 10;
                    c1.Margin.Bottom = 10;
                }
            }

            dataDir = dataDir + "ReplaceableSymbolsInHeaderFooter_out.pdf";
            doc.Save(dataDir);
            // ExEnd:ReplaceableSymbolsInHeaderFooter            
            Console.WriteLine("\nSymbols replaced successfully in header and footer.\nFile saved at " + dataDir);
        }