コード例 #1
0
ファイル: PdfManip.cs プロジェクト: markdevel/clicklabel
 public void Process(Stream outputStream, Stream[] inputStreams, PageLayout pageLayout)
 {
     using (var buffer1 = new MemoryStream())
     {
         using (var doc = new Document(pageLayout.PageSize))
         using (var writer = PdfWriter.GetInstance(doc, buffer1))
         {
             writer.CloseStream = false;
             doc.Open();
             var cb = writer.DirectContent;
             for (var i = 0; i < inputStreams.Length; ++i)
             {
                 using (var buffer2 = new MemoryStream())
                 { 
                     TrimPDFFile(buffer2, inputStreams[i], pageLayout);
                     var reader = new PdfReader(buffer2.ToArray());
                     var page = writer.GetImportedPage(reader, 1);
                     var offset = pageLayout.GetLabelRect(i);
                     cb.AddTemplate(page, 1.0f, 0, 0, 1.0f, offset.Left, offset.Bottom);
                 }
             }
         }
         buffer1.Position = 0;
         OptimizePDFFile(outputStream, buffer1);
     }
 }
コード例 #2
0
ファイル: Tile.cs プロジェクト: Theojim92/SCP-with-O365
 private void CreateBoolPoll()
 {
     TextBlock nameTextBlock = new TextBlock() { Color = Colors.Blue.ToBandColor(), ElementId = 1, Rect = new PageRect(0, 0, 200, 30) };
     WrappedTextBlock questionBlock = new WrappedTextBlock() { ElementId = 2, Rect = new PageRect(0, 25, 200, 60) };
     TextButton button1 = new TextButton() { ElementId = 3, Rect = new PageRect(0, 0, 100, 100), PressedColor = new BandColor(0xFF, 0x00, 0x00) };
     TextButton button2 = new TextButton() { ElementId = 4, Rect = new PageRect(0, 0, 100, 100), PressedColor = new BandColor(0xFF, 0x00, 0x00) };
     FlowPanel panel1 = new FlowPanel(nameTextBlock, questionBlock)
     {
         Orientation = FlowPanelOrientation.Vertical,
         Rect = new PageRect(0, 0, 200, 102)
     };
     FlowPanel panel2 = new FlowPanel(button1, button2)
     {
         Orientation = FlowPanelOrientation.Horizontal,
         Rect = new PageRect(0, 0, 200, 102)
     };
     ScrollFlowPanel panelBool = new ScrollFlowPanel(panel1, panel2)
     {
         Orientation = FlowPanelOrientation.Horizontal,
         Rect = new PageRect(0, 0, 200, 102),
         ScrollBarColorSource = ElementColorSource.BandBase
     };
     PageLayout pageLayout = new PageLayout(panelBool);
     PageLayouts.Add(pageLayout);
 }
コード例 #3
0
        /// <summary>
        /// Update Layout
        /// </summary>
        /// <param name="layout"></param>
        private void updateLayout(PageLayout layout)
        {
            SPFile file = layout.ListItem.File;
            if (!layout.ListItem.HasPublishedVersion)
            {
                file.CheckIn("Automatically checked in by PROTECALayout feature", SPCheckinType.MajorCheckIn);
                file.Update();

                file.Approve("Automatically approved by PROTECALayout feature");
                file.Update();
            }
            else
            {
                if (file.CheckedOutByUser != null)
                {
                    file.UndoCheckOut();
                    file.Update();
                }

                file.CheckOut();
                file.Update();
                file.CheckIn("Automatically checked in by PROTECALayout feature", SPCheckinType.MajorCheckIn);
                file.Update();
                file.Approve("Automatically approved by PROTECALayout feature");
                file.Update();
            }
        }
コード例 #4
0
        public void Delete(PageLayout entity)
        {
            //if (context.Entry(entity).State == System.Data.EntityState.Detached)
            //{
            //	context.PageLayouts.Attach(entity);
            //}

            clearCachedItemByID(entity.PageLayoutID);
            context.PageLayouts.Remove(entity);
        }
コード例 #5
0
ファイル: PdfManip.cs プロジェクト: markdevel/clicklabel
 public void TrimPDFFile(Stream outputStream, Stream inputStream, PageLayout pageLayout)
 {
     using (var reader = new PdfReader(inputStream))
     {
         var inputPageSize = reader.GetPageSize(1);
         var inputPage = reader.GetPageN(1);
         inputPage.Put(PdfName.MEDIABOX, new PdfRectangle(PageLayoutA4.GetLabelRect(0)));
         using (var stamper = new PdfStamper(reader, outputStream))
         {
             stamper.Writer.CloseStream = false;
             stamper.MarkUsed(inputPage);
         }
     }
 }
コード例 #6
0
        public PageLayout Create(PageLayout entity)
        {
            DomainObjectValidator.ThrowIfInvalid(entity);

            // make sure the name/username is unique
            var links = FindAll(l => l.UserName == entity.UserName && l.Title.ToLower() == entity.Title.ToLower()).FirstOrDefault();
            if (links != null)
            {
                throw new DomainValidationException(string.Format("There is already a set of links named {0}.", entity.Title));
            }

            entity = context.PageLayouts.Add(entity);
            return entity;
        }
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWeb web = (SPWeb)properties.Feature.Parent;

            PublishingWeb publishingWeb = null;
            if (PublishingWeb.IsPublishingWeb(web))
            {
                publishingWeb = PublishingWeb.GetPublishingWeb(web);

                PageLayout[] pageLayouts = publishingWeb.GetAvailablePageLayouts();
                PageLayout[] availablePageLayouts = new PageLayout[1];

                availablePageLayouts[0] = pageLayouts[0];

                publishingWeb.SetAvailablePageLayouts(availablePageLayouts, true);
                publishingWeb.SetDefaultPageLayout(availablePageLayouts[0], true);
                publishingWeb.Update();
            }
        }
コード例 #8
0
        public static void SwapPageLayout(PublishingWeb publishingWeb, PageLayout defaultPageLayout, SPContentType ctype)
        {
            string checkInComment = "WET4 Automatic Event Handler Page Layout Fix";
            //
            // Validate the input parameters.
            if (null == publishingWeb)
            {
                throw new System.ArgumentNullException("publishingWeb");
            }
            if (null == defaultPageLayout)
            {
                throw new System.ArgumentNullException("defaultPageLayout");
            }

            SPList list = publishingWeb.PagesList;
            if (list.ContentTypes[defaultPageLayout.AssociatedContentType.Name] == null)
            {
                list.ContentTypes.Add(ctype);
            }
            SPContentType ct = list.ContentTypes[defaultPageLayout.AssociatedContentType.Name];

            PublishingPageCollection publishingPages = publishingWeb.GetPublishingPages();
            foreach (PublishingPage publishingPage in publishingPages)
            {
                if (publishingPage.ListItem.File.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    publishingPage.CheckOut();
                }
                publishingPage.ListItem["ContentTypeId"] = ct.Id;

                switch (publishingPage.Url)
                {
                    default:
                        publishingPage.Layout = defaultPageLayout;
                        publishingPage.Title = publishingWeb.Title;
                        break;
                }
                publishingPage.Update();
                publishingPage.CheckIn(checkInComment);
            }
        }
コード例 #9
0
        private static PageLayout CreateMessageLayout()
        {
            var messageWrappedTextBlock = new WrappedTextBlock()
            {
                ElementId = PageElementKind.CustomMessageText,
                Rect = new PageRect(0, 0, 258, 102),
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Top
            };

            var messageWithoutAckButtonPanel = new ScrollFlowPanel(messageWrappedTextBlock)
            {
                Orientation = FlowPanelOrientation.Vertical,
                Rect = new PageRect(0, 0, 258, 102),
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Top,
            };

            var messageWithoutAckButtonLayout = new PageLayout(messageWithoutAckButtonPanel);
            return messageWithoutAckButtonLayout;
        }
コード例 #10
0
        private IEnumerable<PageLayout> GetAvailablePageLayouts(Web web)
        {
            var defaultLayoutXml = web.GetPropertyBagValueString(DEFAULTPAGELAYOUT, null);

            var defaultPageLayoutUrl = string.Empty;
            if (defaultLayoutXml != null && defaultLayoutXml != "__inherit")
            {
                defaultPageLayoutUrl = XElement.Parse(defaultLayoutXml).Attribute("url").Value;
            }

            List<PageLayout> layouts = new List<PageLayout>();

            var layoutsXml = web.GetPropertyBagValueString(AVAILABLEPAGELAYOUTS, null);

            if (!string.IsNullOrEmpty(layoutsXml) && layoutsXml != "__inherit")
            {
                var layoutsElement = XElement.Parse(layoutsXml);

                foreach (var layout in layoutsElement.Descendants("layout"))
                {
                    if (layout.Attribute("url") != null)
                    {
                        var pageLayout = new PageLayout();
                        pageLayout.Path = layout.Attribute("url").Value;

                        if (pageLayout.Path == defaultPageLayoutUrl)
                        {
                            pageLayout.IsDefault = true;
                        }
                        layouts.Add(pageLayout);
                    }

                }
            }
            return layouts;
        }
コード例 #11
0
		/// <summary>
		///		Updates the wizard layout to match the suggested <see cref="PageLayout"/>.
		/// </summary>
		/// <param name="layout">The suggested layout to use</param>
		protected virtual void UpdateLayout(PageLayout layout)
		{
			// Should we perform a layout?
			if( layout == PageLayout.None )
				return;

			SuspendLayout();
			try
			{
				switch( layout )
				{
					case PageLayout.InteriorPage:
						// Show the top bar
						wizardTop.Visible = true;
						wizardTop.Dock = DockStyle.Top;
						wizardTop.Height = 64;
					
						// Show the top line
						topLine.Visible = true;
						topLine.Dock = DockStyle.Top;

						// Hide the side bar
						sidePanel.Visible = false;

						// Position and size the step panel
						panelStep.Dock = DockStyle.Fill;
						panelStep.DockPadding.All = 8;
					
						BackColor = SystemColors.Control;
						panelStep.BackColor = SystemColors.Control;
						break;
					case PageLayout.ExteriorPage:
						// Hide the top bar
						wizardTop.Visible = false;
						topLine.Visible = false;
				
						//BackColor = Color.White;
						panelStep.BackColor = Color.White;

						panelStep.Dock = DockStyle.Fill;

						sidePanel.Visible = true;
						sidePanel.Dock = DockStyle.Left;
						sidePanel.Width = 160;
						break;
					default:
						throw new InvalidOperationException("WizardLayout is not set to one of the allowed values");
				}

				panelStep.BringToFront();
			}
			finally
			{
				ResumeLayout();
			}
		}
コード例 #12
0
        public TransactionTileLayout()
        {
            LoadIconMethod  = LoadIcon;
            AdjustUriMethod = (uri) => uri;

            panel                     = new FlowPanel();
            panel.Orientation         = FlowPanelOrientation.Vertical;
            panel.Rect                = new PageRect(0, 0, 258, 128);
            panel.ElementId           = 1;
            panel.Margins             = new Margins(0, 0, 0, 0);
            panel.HorizontalAlignment = HorizontalAlignment.Left;
            panel.VerticalAlignment   = VerticalAlignment.Top;

            textBlock                     = new TextBlock();
            textBlock.Font                = TextBlockFont.Small;
            textBlock.Baseline            = 0;
            textBlock.BaselineAlignment   = TextBlockBaselineAlignment.Automatic;
            textBlock.AutoWidth           = true;
            textBlock.ColorSource         = ElementColorSource.BandBase;
            textBlock.Rect                = new PageRect(0, 0, 32, 32);
            textBlock.ElementId           = 2;
            textBlock.Margins             = new Margins(12, 8, 0, 0);
            textBlock.HorizontalAlignment = HorizontalAlignment.Left;
            textBlock.VerticalAlignment   = VerticalAlignment.Top;

            panel.Elements.Add(textBlock);

            AmountDecimalButton = new TextButton();
            AmountDecimalButton.PressedColor        = new BandColor(32, 32, 32);
            AmountDecimalButton.Rect                = new PageRect(0, 0, 80, 44);
            AmountDecimalButton.ElementId           = 3;
            AmountDecimalButton.Margins             = new Margins(12, 20, 0, 0);
            AmountDecimalButton.HorizontalAlignment = HorizontalAlignment.Right;
            AmountDecimalButton.VerticalAlignment   = VerticalAlignment.Top;

            panel.Elements.Add(AmountDecimalButton);

            icon                     = new Icon();
            icon.ColorSource         = ElementColorSource.Custom;
            icon.Color               = new BandColor(255, 21, 28);
            icon.Rect                = new PageRect(0, 0, 32, 32);
            icon.ElementId           = 5;
            icon.Margins             = new Margins(190, -38, 0, 0);
            icon.HorizontalAlignment = HorizontalAlignment.Center;
            icon.VerticalAlignment   = VerticalAlignment.Center;

            panel.Elements.Add(icon);

            CategoryButton = new FilledButton();
            CategoryButton.BackgroundColor     = new BandColor(53, 53, 53);
            CategoryButton.Rect                = new PageRect(0, 0, 44, 44);
            CategoryButton.ElementId           = 4;
            CategoryButton.Margins             = new Margins(184, -40, 0, 0);
            CategoryButton.HorizontalAlignment = HorizontalAlignment.Center;
            CategoryButton.VerticalAlignment   = VerticalAlignment.Center;

            panel.Elements.Add(CategoryButton);

            AmountSingleButton = new TextButton();
            AmountSingleButton.PressedColor        = new BandColor(32, 32, 32);
            AmountSingleButton.Rect                = new PageRect(0, 0, 80, 44);
            AmountSingleButton.ElementId           = 6;
            AmountSingleButton.Margins             = new Margins(92, -44, 0, 0);
            AmountSingleButton.HorizontalAlignment = HorizontalAlignment.Left;
            AmountSingleButton.VerticalAlignment   = VerticalAlignment.Top;

            panel.Elements.Add(AmountSingleButton);
            pageLayout = new PageLayout(panel);

            PageElementData[] pageElementDataArray = new PageElementData[5];
            pageElementDataArray[0] = textBlockData;
            pageElementDataArray[1] = AmountDecimalButtonData;
            pageElementDataArray[2] = iconData;
            pageElementDataArray[3] = CategoryButtonData;
            pageElementDataArray[4] = AmountSingleButtonData;

            pageLayoutData = new PageLayoutData(pageElementDataArray);
        }
コード例 #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DisplayProperties" /> class.
 /// </summary>
 /// <param name="Links">Link to the document.</param>
 /// <param name="CenterWindow">Gets or sets flag specifying whether position of the document&#39;s window will be centerd on the screen.</param>
 /// <param name="Direction">Gets or sets reading order of text: L2R (left to right) or R2L (right to left).</param>
 /// <param name="DisplayDocTitle">Gets or sets flag specifying whether document&#39;s window title bar should display document title.</param>
 /// <param name="HideMenuBar">Gets or sets flag specifying whether menu bar should be hidden when document is active.</param>
 /// <param name="HideToolBar">Gets or sets flag specifying whether toolbar should be hidden when document is active.</param>
 /// <param name="HideWindowUI">Gets or sets flag specifying whether user interface elements should be hidden when document is active.</param>
 /// <param name="NonFullScreenPageMode">Gets or sets page mode, specifying how to display the document on exiting full-screen mode.</param>
 /// <param name="PageLayout">Gets or sets page layout which shall be used when the document is opened.</param>
 /// <param name="PageMode">Gets or sets page mode, specifying how document should be displayed when opened.</param>
 public DisplayProperties(List <Link> Links = default(List <Link>), bool?CenterWindow = default(bool?), Direction Direction = default(Direction), bool?DisplayDocTitle = default(bool?), bool?HideMenuBar = default(bool?), bool?HideToolBar = default(bool?), bool?HideWindowUI = default(bool?), PageMode NonFullScreenPageMode = default(PageMode), PageLayout PageLayout = default(PageLayout), PageMode PageMode = default(PageMode))
 {
     this.Links                 = Links;
     this.CenterWindow          = CenterWindow;
     this.Direction             = Direction;
     this.DisplayDocTitle       = DisplayDocTitle;
     this.HideMenuBar           = HideMenuBar;
     this.HideToolBar           = HideToolBar;
     this.HideWindowUI          = HideWindowUI;
     this.NonFullScreenPageMode = NonFullScreenPageMode;
     this.PageLayout            = PageLayout;
     this.PageMode              = PageMode;
 }
コード例 #14
0
        /// <summary>
        /// Analyses a publishing page
        /// </summary>
        /// <returns>Information about the analyzed publishing page</returns>
        public override Tuple <PageLayout, List <WebPartEntity> > Analyze(Publishing.PageLayout publishingPageTransformationModel)
        {
            List <WebPartEntity> webparts = new List <WebPartEntity>();

            //Load the page
            var publishingPageUrl = page[Constants.FileRefField].ToString();
            var publishingPage    = cc.Web.GetFileByServerRelativeUrl(publishingPageUrl);

            // Load relevant model data for the used page layout in case not already provided - safetynet for calls from modernization scanner
            string usedPageLayout = System.IO.Path.GetFileNameWithoutExtension(page.PageLayoutFile());

            if (publishingPageTransformationModel == null)
            {
                publishingPageTransformationModel = new PageLayoutManager(this.RegisteredLogObservers).GetPageLayoutMappingModel(this.publishingPageTransformation, page);
            }

            // Still no layout...can't continue...
            if (publishingPageTransformationModel == null)
            {
                LogError(string.Format(LogStrings.Error_NoPageLayoutTransformationModel, usedPageLayout), LogStrings.Heading_PublishingPage);
                throw new Exception(string.Format(LogStrings.Error_NoPageLayoutTransformationModel, usedPageLayout));
            }

            // Map layout
            PageLayout layout = MapToLayout(publishingPageTransformationModel.PageLayoutTemplate);

            #region Process fields that become web parts
            if (publishingPageTransformationModel.WebParts != null)
            {
                #region Publishing Html column processing
                // Converting to WikiTextPart is a special case as we'll need to process the html
                var wikiTextWebParts = publishingPageTransformationModel.WebParts.Where(p => p.TargetWebPart.Equals(WebParts.WikiText, StringComparison.InvariantCultureIgnoreCase));
                List <WebPartPlaceHolder> webPartsToRetrieve = new List <WebPartPlaceHolder>();
                foreach (var wikiTextPart in wikiTextWebParts)
                {
                    string pageContents = page.GetFieldValueAs <string>(wikiTextPart.Name);

                    if (wikiTextPart.Property.Count() > 0)
                    {
                        foreach (var fieldWebPartProperty in wikiTextPart.Property)
                        {
                            if (fieldWebPartProperty.Name.Equals("Text", StringComparison.InvariantCultureIgnoreCase) && !string.IsNullOrEmpty(fieldWebPartProperty.Functions))
                            {
                                // execute function
                                var evaluatedField = this.functionProcessor.Process(fieldWebPartProperty.Functions, fieldWebPartProperty.Name, MapToFunctionProcessorFieldType(fieldWebPartProperty.Type));
                                if (!string.IsNullOrEmpty(evaluatedField.Item1))
                                {
                                    pageContents = evaluatedField.Item2;
                                }
                            }
                        }
                    }

                    if (pageContents != null && !string.IsNullOrEmpty(pageContents))
                    {
                        var htmlDoc = parser.Parse(pageContents);

                        // Analyze the html block (which is a wiki block)
                        var content = htmlDoc.FirstElementChild.LastElementChild;
                        AnalyzeWikiContentBlock(webparts, htmlDoc, webPartsToRetrieve, wikiTextPart.Row, wikiTextPart.Column, GetNextOrder(wikiTextPart.Row, wikiTextPart.Column, wikiTextPart.Order, webparts), content);
                    }
                    else
                    {
                        LogWarning(LogStrings.Warning_CannotRetrieveFieldValue, LogStrings.Heading_PublishingPage);
                    }
                }

                // Bulk load the needed web part information
                if (webPartsToRetrieve.Count > 0)
                {
                    LoadWebPartsInWikiContentFromOnPremisesServer(webparts, publishingPage, webPartsToRetrieve);
                }
                #endregion

                #region Generic processing of the other 'webpart' fields
                var fieldWebParts = publishingPageTransformationModel.WebParts.Where(p => !p.TargetWebPart.Equals(WebParts.WikiText, StringComparison.InvariantCultureIgnoreCase));
                foreach (var fieldWebPart in fieldWebParts.OrderBy(p => p.Row).OrderBy(p => p.Column))
                {
                    // In publishing scenarios it's common to not have all fields defined in the page layout mapping filled. By default we'll not map empty fields as that will result in empty web parts
                    // which impact the page look and feel. Using the RemoveEmptySectionsAndColumns flag this behaviour can be turned off.
                    if (this.baseTransformationInformation.RemoveEmptySectionsAndColumns)
                    {
                        var fieldContents = page.GetFieldValueAs <string>(fieldWebPart.Name);

                        if (string.IsNullOrEmpty(fieldContents))
                        {
                            LogWarning(String.Format(LogStrings.Warning_SkippedWebPartDueToEmptyInSourcee, fieldWebPart.TargetWebPart, fieldWebPart.Name), LogStrings.Heading_PublishingPage);
                            continue;
                        }
                    }

                    Dictionary <string, string> properties = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);

                    foreach (var fieldWebPartProperty in fieldWebPart.Property)
                    {
                        if (!string.IsNullOrEmpty(fieldWebPartProperty.Functions))
                        {
                            // execute function
                            var evaluatedField = this.functionProcessor.Process(fieldWebPartProperty.Functions, fieldWebPartProperty.Name, MapToFunctionProcessorFieldType(fieldWebPartProperty.Type));
                            if (!string.IsNullOrEmpty(evaluatedField.Item1) && !properties.ContainsKey(evaluatedField.Item1))
                            {
                                properties.Add(evaluatedField.Item1, evaluatedField.Item2);
                            }
                        }
                        else
                        {
                            var webPartName = page.FieldValues[fieldWebPart.Name]?.ToString().Trim();
                            if (webPartName != null)
                            {
                                properties.Add(fieldWebPartProperty.Name, page.FieldValues[fieldWebPart.Name].ToString().Trim());
                            }
                        }
                    }

                    var wpEntity = new WebPartEntity()
                    {
                        Title      = fieldWebPart.Name,
                        Type       = fieldWebPart.TargetWebPart,
                        Id         = Guid.Empty,
                        Row        = fieldWebPart.Row,
                        Column     = fieldWebPart.Column,
                        Order      = GetNextOrder(fieldWebPart.Row, fieldWebPart.Column, fieldWebPart.Order, webparts),
                        Properties = properties,
                    };

                    webparts.Add(wpEntity);
                }
            }
            #endregion
            #endregion

            #region Process fields that become metadata as they might result in the creation of page properties web part
            if (publishingPageTransformationModel.MetaData != null && publishingPageTransformationModel.MetaData.ShowPageProperties)
            {
                List <string> pagePropertiesFields = new List <string>();

                var fieldsToProcess = publishingPageTransformationModel.MetaData.Field.Where(p => p.ShowInPageProperties == true && !string.IsNullOrEmpty(p.TargetFieldName));

                if (fieldsToProcess.Any())
                {
                    // Loop over the fields that are defined to be shown in the page properties and that have a target field name set
                    foreach (var fieldToProcess in fieldsToProcess)
                    {
                        var targetFieldInstance = targetContext.Web.GetFieldByInternalName(fieldToProcess.TargetFieldName, true);
                        if (targetFieldInstance != null)
                        {
                            if (!pagePropertiesFields.Contains(targetFieldInstance.Id.ToString()))
                            {
                                pagePropertiesFields.Add(targetFieldInstance.Id.ToString());
                            }
                        }
                    }

                    if (pagePropertiesFields.Count > 0)
                    {
                        string propertyString = "";
                        foreach (var propertyField in pagePropertiesFields)
                        {
                            if (!string.IsNullOrEmpty(propertyField))
                            {
                                propertyString = $"{propertyString},\"{propertyField.ToString()}\"";
                            }
                        }

                        if (!string.IsNullOrEmpty(propertyString))
                        {
                            propertyString = propertyString.TrimStart(new char[] { ',' });
                        }

                        if (!string.IsNullOrEmpty(propertyString))
                        {
                            Dictionary <string, string> properties = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase)
                            {
                                { "SelectedFields", propertyString }
                            };

                            var wpEntity = new WebPartEntity()
                            {
                                Type       = WebParts.PageProperties,
                                Id         = Guid.Empty,
                                Row        = publishingPageTransformationModel.MetaData.PagePropertiesRow,
                                Column     = publishingPageTransformationModel.MetaData.PagePropertiesColumn,
                                Order      = GetNextOrder(publishingPageTransformationModel.MetaData.PagePropertiesRow, publishingPageTransformationModel.MetaData.PagePropertiesColumn, publishingPageTransformationModel.MetaData.PagePropertiesOrder, webparts),
                                Properties = properties,
                            };

                            webparts.Add(wpEntity);
                        }
                    }
                }
            }
            #endregion

            #region Web Parts in webpart zone handling
            // Load web parts put in web part zones on the publishing page
            // Note: Web parts placed outside of a web part zone using SPD are not picked up by the web part manager.
            var limitedWPManager = publishingPage.GetLimitedWebPartManager(PersonalizationScope.Shared);
            cc.Load(limitedWPManager);

            IEnumerable <WebPartDefinition> webPartsViaManager        = null;
            List <WebServiceWebPartEntity>  webServiceWebPartEntities = null;

            //Properties, ExportMode and ZoneId - not Supported in 2010, Web Services are used to compensate for the missing properties
            webPartsViaManager = cc.LoadQuery(limitedWPManager.WebParts.IncludeWithDefaultProperties(wp => wp.Id, wp => wp.WebPart.Title, wp => wp.WebPart.ZoneIndex, wp => wp.WebPart.IsClosed, wp => wp.WebPart.Hidden));
            cc.ExecuteQueryRetry();

            LogInfo(LogStrings.TransformUsesWebServicesFallback, LogStrings.Heading_Summary, LogEntrySignificance.WebServiceFallback);
            webServiceWebPartEntities = LoadPublishingPageFromWebServices(publishingPage.EnsureProperty(p => p.ServerRelativeUrl));


            if (webPartsViaManager.Count() > 0)
            {
                List <WebPartPlaceHolder> webPartsToRetrieve = new List <WebPartPlaceHolder>();

                foreach (var foundWebPart in webPartsViaManager)
                {
                    // Remove the web parts which we've already picked up by analyzing the wiki content block
                    if (webparts.Where(p => p.Id.Equals(foundWebPart.Id)).FirstOrDefault() != null)
                    {
                        continue;
                    }

                    webPartsToRetrieve.Add(new WebPartPlaceHolder()
                    {
                        WebPartDefinition = foundWebPart,
                        WebPartXml        = null,
                        WebPartType       = "",
                    });
                }

                foreach (var foundWebPart in webPartsToRetrieve)
                {
                    // If the web service call includes the export mode value then set the export options
                    var wsWp         = webServiceWebPartEntities.FirstOrDefault(o => o.Id == foundWebPart.WebPartDefinition.Id);
                    var wsExportMode = wsWp.Properties.FirstOrDefault(o => o.Key.Equals("exportmode", StringComparison.InvariantCultureIgnoreCase));
                    if (!string.IsNullOrEmpty(wsExportMode.Value) && wsExportMode.Value.Equals("all", StringComparison.InvariantCultureIgnoreCase))
                    {
                        var webPartXml = base.ExportWebPartXmlWorkaround(publishingPageUrl, foundWebPart.WebPartDefinition.Id.ToString());
                        foundWebPart.WebPartXmlOnPremises = webPartXml;
                    }
                }

                List <WebPartZoneLayoutMap> webPartZoneLayoutMap = new List <WebPartZoneLayoutMap>();
                foreach (var foundWebPart in webPartsToRetrieve.OrderBy(p => p.WebPartDefinition.WebPart.ZoneIndex))
                {
                    bool isExportable = false;

                    Dictionary <string, object> webPartProperties = null;

                    // If the web service call includes the export mode value then set the export options
                    var wsWp = webServiceWebPartEntities.FirstOrDefault(o => o.Id == foundWebPart.WebPartDefinition.Id);
                    webPartProperties = wsWp.PropertiesAsStringObjectDictionary();

                    var wsExportMode = wsWp.Properties.FirstOrDefault(o => o.Key.Equals("exportmode", StringComparison.InvariantCultureIgnoreCase));
                    if (!string.IsNullOrEmpty(wsExportMode.Value) && wsExportMode.Value.ToString().Equals("all", StringComparison.InvariantCultureIgnoreCase))
                    {
                        isExportable = true;
                    }

                    if (!isExportable)
                    {
                        // Use different approach to determine type as we can't export the web part XML without indroducing a change
                        foundWebPart.WebPartType = GetTypeFromProperties(webPartProperties, true);
                    }
                    else
                    {
                        foundWebPart.WebPartType = GetType(foundWebPart.WebPartXmlOnPremises);
                    }

                    string zoneId   = string.Empty;
                    var    wsZoneId = wsWp.Properties.FirstOrDefault(o => o.Key.Equals("zoneid", StringComparison.InvariantCultureIgnoreCase));
                    if (!string.IsNullOrEmpty(wsZoneId.Value))
                    {
                        zoneId = wsZoneId.Value;
                    }

                    int wpInZoneRow  = 1;
                    int wpInZoneCol  = 1;
                    int wpStartOrder = 0;
                    // Determine location based upon the location given to the web part zone in the mapping
                    if (publishingPageTransformationModel.WebPartZones != null)
                    {
                        var wpZoneFromTemplate = publishingPageTransformationModel.WebPartZones.Where(p => p.ZoneId.Equals(zoneId, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

                        if (wpZoneFromTemplate != null)
                        {
                            // Was there a webpart zone layout specified? If so then use that information to correctly position the webparts on the target page
                            if (wpZoneFromTemplate.WebPartZoneLayout != null && wpZoneFromTemplate.WebPartZoneLayout.Count() > 0)
                            {
                                // Did we already map a web part of this type?
                                var webPartZoneLayoutMapEntry = webPartZoneLayoutMap.Where(p => p.ZoneId.Equals(wpZoneFromTemplate.ZoneId, StringComparison.InvariantCultureIgnoreCase) &&
                                                                                           p.Type.Equals(foundWebPart.WebPartType, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

                                // What's the expected occurance for this web part in the mapping?
                                int webPartOccuranceInZoneLayout = 1;
                                if (webPartZoneLayoutMapEntry != null)
                                {
                                    webPartOccuranceInZoneLayout += webPartZoneLayoutMapEntry.Occurances;
                                }

                                // Get the webpart from the webpart zone layout mapping
                                int  occuranceCounter = 0;
                                bool occuranceFound   = false;
                                foreach (var wpInWebPartZoneLayout in wpZoneFromTemplate.WebPartZoneLayout.Where(p => p.Type.Equals(foundWebPart.WebPartType, StringComparison.InvariantCultureIgnoreCase)))
                                {
                                    occuranceCounter++;

                                    if (occuranceCounter == webPartOccuranceInZoneLayout)
                                    {
                                        occuranceFound = true;
                                        wpInZoneRow    = wpInWebPartZoneLayout.Row;
                                        wpInZoneCol    = wpInWebPartZoneLayout.Column;
                                        wpStartOrder   = wpInWebPartZoneLayout.Order;
                                        break;
                                    }
                                }

                                if (occuranceFound)
                                {
                                    // Update the WebPartZoneLayoutMap
                                    if (webPartZoneLayoutMapEntry != null)
                                    {
                                        webPartZoneLayoutMapEntry.Occurances = webPartOccuranceInZoneLayout;
                                    }
                                    else
                                    {
                                        webPartZoneLayoutMap.Add(new WebPartZoneLayoutMap()
                                        {
                                            ZoneId = wpZoneFromTemplate.ZoneId, Type = foundWebPart.WebPartType, Occurances = webPartOccuranceInZoneLayout
                                        });
                                    }
                                }
                                else
                                {
                                    // fall back to the defaults from the zone definition
                                    wpInZoneRow  = wpZoneFromTemplate.Row;
                                    wpInZoneCol  = wpZoneFromTemplate.Column;
                                    wpStartOrder = wpZoneFromTemplate.Order;
                                }
                            }
                            else
                            {
                                wpInZoneRow  = wpZoneFromTemplate.Row;
                                wpInZoneCol  = wpZoneFromTemplate.Column;
                                wpStartOrder = wpZoneFromTemplate.Order;
                            }
                        }
                    }

                    // Determine order already taken
                    int wpInZoneOrderUsed = GetNextOrder(wpInZoneRow, wpInZoneCol, wpStartOrder, webparts);

                    string webPartXmlForPropertiesMethod = null;
                    webPartXmlForPropertiesMethod = foundWebPart.WebPartXmlOnPremises;

                    LogInfo(string.Format(LogStrings.ContentTransformFoundSourceWebParts,
                                          foundWebPart.WebPartDefinition.WebPart.Title, foundWebPart.WebPartType.GetTypeShort()), LogStrings.Heading_ContentTransform);

                    webparts.Add(new WebPartEntity()
                    {
                        Title           = foundWebPart.WebPartDefinition.WebPart.Title,
                        Type            = foundWebPart.WebPartType,
                        Id              = foundWebPart.WebPartDefinition.Id,
                        ServerControlId = foundWebPart.WebPartDefinition.Id.ToString(),
                        Row             = wpInZoneRow,
                        Column          = wpInZoneCol,
                        Order           = wpInZoneOrderUsed + foundWebPart.WebPartDefinition.WebPart.ZoneIndex,
                        ZoneId          = zoneId,
                        ZoneIndex       = (uint)foundWebPart.WebPartDefinition.WebPart.ZoneIndex,
                        IsClosed        = foundWebPart.WebPartDefinition.WebPart.IsClosed,
                        Hidden          = foundWebPart.WebPartDefinition.WebPart.Hidden,
                        Properties      = Properties(webPartProperties, foundWebPart.WebPartType, webPartXmlForPropertiesMethod),
                    });
                }
            }
            else
            {
                LogInfo(LogStrings.AnalysingNoWebPartsFound, LogStrings.Heading_ArticlePageHandling);
            }
            #endregion

            #region Fixed webparts mapping
            if (publishingPageTransformationModel.FixedWebParts != null)
            {
                foreach (var fixedWebpart in publishingPageTransformationModel.FixedWebParts)
                {
                    int wpFixedOrderUsed = GetNextOrder(fixedWebpart.Row, fixedWebpart.Column, fixedWebpart.Order, webparts);

                    webparts.Add(new WebPartEntity()
                    {
                        Title      = GetFixedWebPartProperty <string>(fixedWebpart, "Title", ""),
                        Type       = fixedWebpart.Type,
                        Id         = Guid.NewGuid(),
                        Row        = fixedWebpart.Row,
                        Column     = fixedWebpart.Column,
                        Order      = wpFixedOrderUsed,
                        ZoneId     = "",
                        ZoneIndex  = 0,
                        IsClosed   = GetFixedWebPartProperty <bool>(fixedWebpart, "__designer:IsClosed", false),
                        Hidden     = false,
                        Properties = CastAsPropertiesDictionary(fixedWebpart),
                    });
                }
            }
            #endregion

            return(new Tuple <PageLayout, List <WebPartEntity> >(layout, webparts));
        }
コード例 #15
0
        private static PageLayout CreateMessageWithButtonLayout()
        {
            var customMessageWrappedTextBlock = new WrappedTextBlock()
            {
                ElementId = PageElementKind.CustomMessageText2,
                Rect = new PageRect(0, 0, 258, 102),
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Top
            };

            var customMessageButton = new TextButton()
            {
                ElementId = PageElementKind.CustomMessageButton,
                Margins = new Margins(25, 10, 25, 10),
                Rect = new PageRect(0, 0, 170, 45),
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center
            };

            var customMessageWithAckButtonPanel = new ScrollFlowPanel(customMessageWrappedTextBlock, customMessageButton)
            {
                Orientation = FlowPanelOrientation.Vertical,
                Rect = new PageRect(0, 0, 258, 102),
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Top,
            };

            var customMessageWithAckButtonLayout = new PageLayout(customMessageWithAckButtonPanel);
            return customMessageWithAckButtonLayout;
        }
コード例 #16
0
        public void Save()
        {
            if (EpubMode)
            {
                try
                {
                    SaveAsEpub();
                }
                catch (Exception err)
                {
                    SIL.Reporting.ErrorReport.NotifyUserOfProblem("Bloom was not able to save the ePUB.  {0}", err.Message);
                }
                return;
            }
            try
            {
                // Give a slight preference to USB keys, though if they used a different directory last time, we favor that.

                if (string.IsNullOrEmpty(_lastDirectory) || !Directory.Exists(_lastDirectory))
                {
                    var drives = SIL.UsbDrive.UsbDriveInfo.GetDrives();
                    if (drives != null && drives.Count > 0)
                    {
                        _lastDirectory = drives[0].RootDirectory.FullName;
                    }
                }

                using (var dlg = new SaveFileDialog())
                {
                    if (!string.IsNullOrEmpty(_lastDirectory) && Directory.Exists(_lastDirectory))
                    {
                        dlg.InitialDirectory = _lastDirectory;
                    }
                    var portion = "";
                    switch (BookletPortion)
                    {
                    case BookletPortions.None:
                        Debug.Fail("Save should not be enabled");
                        return;

                    case BookletPortions.AllPagesNoBooklet:
                        portion = "Pages";
                        break;

                    case BookletPortions.BookletCover:
                        portion = "Cover";
                        break;

                    case BookletPortions.BookletPages:
                        portion = "Inside";
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                    string suggestedName = string.Format("{0}-{1}-{2}.pdf", Path.GetFileName(_currentlyLoadedBook.FolderPath),
                                                         _collectionSettings.GetLanguage1Name("en"), portion);
                    dlg.FileName = suggestedName;
                    dlg.Filter   = "PDF|*.pdf";
                    if (DialogResult.OK == dlg.ShowDialog())
                    {
                        _lastDirectory = Path.GetDirectoryName(dlg.FileName);
                        RobustFile.Copy(PdfFilePath, dlg.FileName, true);
                        Analytics.Track("Save PDF", new Dictionary <string, string>()
                        {
                            { "Portion", Enum.GetName(typeof(BookletPortions), BookletPortion) },
                            { "Layout", PageLayout.ToString() },
                            { "BookId", BookSelection.CurrentSelection.ID },
                            { "Country", _collectionSettings.Country }
                        });
                    }
                }
            }
            catch (Exception err)
            {
                SIL.Reporting.ErrorReport.NotifyUserOfProblem("Bloom was not able to save the PDF.  {0}", err.Message);
            }
        }
コード例 #17
0
 public void AddLayout(PageLayout layout)
 {
     _layoutRepo.Add(layout);
     _layoutRepo.Save();
 }
コード例 #18
0
        public DesignedBandTileLayout()
        {
            LoadIconMethod  = LoadIcon;
            AdjustUriMethod = (uri) => uri;

            panel = new ScrollFlowPanel();
            panel.ScrollBarColorSource = ElementColorSource.Custom;
            panel.ScrollBarColor       = new BandColor(255, 255, 255);
            panel.Orientation          = FlowPanelOrientation.Vertical;
            panel.Rect                = new PageRect(-1, 0, 259, 128);
            panel.ElementId           = 1;
            panel.Margins             = new Margins(0, 0, 0, 0);
            panel.HorizontalAlignment = HorizontalAlignment.Left;
            panel.VerticalAlignment   = VerticalAlignment.Top;

            panel2                     = new FlowPanel();
            panel2.Orientation         = FlowPanelOrientation.Vertical;
            panel2.Rect                = new PageRect(0, 0, 78, 128);
            panel2.ElementId           = 2;
            panel2.Margins             = new Margins(0, 0, 0, 0);
            panel2.HorizontalAlignment = HorizontalAlignment.Left;
            panel2.VerticalAlignment   = VerticalAlignment.Top;

            textBlock                     = new TextBlock();
            textBlock.Font                = TextBlockFont.Small;
            textBlock.Baseline            = 0;
            textBlock.BaselineAlignment   = TextBlockBaselineAlignment.Automatic;
            textBlock.AutoWidth           = true;
            textBlock.ColorSource         = ElementColorSource.Custom;
            textBlock.Color               = new BandColor(255, 255, 255);
            textBlock.Rect                = new PageRect(0, 0, 32, 32);
            textBlock.ElementId           = 3;
            textBlock.Margins             = new Margins(0, 0, 0, 0);
            textBlock.HorizontalAlignment = HorizontalAlignment.Left;
            textBlock.VerticalAlignment   = VerticalAlignment.Top;

            panel2.Elements.Add(textBlock);

            textBlock2                     = new TextBlock();
            textBlock2.Font                = TextBlockFont.Small;
            textBlock2.Baseline            = 0;
            textBlock2.BaselineAlignment   = TextBlockBaselineAlignment.Automatic;
            textBlock2.AutoWidth           = true;
            textBlock2.ColorSource         = ElementColorSource.Custom;
            textBlock2.Color               = new BandColor(255, 255, 255);
            textBlock2.Rect                = new PageRect(0, 0, 32, 32);
            textBlock2.ElementId           = 4;
            textBlock2.Margins             = new Margins(0, 0, 0, 0);
            textBlock2.HorizontalAlignment = HorizontalAlignment.Left;
            textBlock2.VerticalAlignment   = VerticalAlignment.Top;

            panel2.Elements.Add(textBlock2);

            textBlock3                     = new TextBlock();
            textBlock3.Font                = TextBlockFont.Small;
            textBlock3.Baseline            = 0;
            textBlock3.BaselineAlignment   = TextBlockBaselineAlignment.Automatic;
            textBlock3.AutoWidth           = true;
            textBlock3.ColorSource         = ElementColorSource.Custom;
            textBlock3.Color               = new BandColor(255, 255, 255);
            textBlock3.Rect                = new PageRect(0, 0, 32, 32);
            textBlock3.ElementId           = 5;
            textBlock3.Margins             = new Margins(0, 0, 0, 0);
            textBlock3.HorizontalAlignment = HorizontalAlignment.Left;
            textBlock3.VerticalAlignment   = VerticalAlignment.Top;

            panel2.Elements.Add(textBlock3);

            textBlock4                     = new TextBlock();
            textBlock4.Font                = TextBlockFont.Small;
            textBlock4.Baseline            = 0;
            textBlock4.BaselineAlignment   = TextBlockBaselineAlignment.Automatic;
            textBlock4.AutoWidth           = true;
            textBlock4.ColorSource         = ElementColorSource.Custom;
            textBlock4.Color               = new BandColor(255, 255, 255);
            textBlock4.Rect                = new PageRect(0, 0, 32, 32);
            textBlock4.ElementId           = 6;
            textBlock4.Margins             = new Margins(0, 0, 0, 0);
            textBlock4.HorizontalAlignment = HorizontalAlignment.Left;
            textBlock4.VerticalAlignment   = VerticalAlignment.Top;

            panel2.Elements.Add(textBlock4);

            panel.Elements.Add(panel2);

            panel3                     = new FlowPanel();
            panel3.Orientation         = FlowPanelOrientation.Vertical;
            panel3.Rect                = new PageRect(0, 0, 47, 128);
            panel3.ElementId           = 7;
            panel3.Margins             = new Margins(86, -128, 0, 0);
            panel3.HorizontalAlignment = HorizontalAlignment.Left;
            panel3.VerticalAlignment   = VerticalAlignment.Top;

            txtCoffee                     = new TextBlock();
            txtCoffee.Font                = TextBlockFont.Small;
            txtCoffee.Baseline            = 0;
            txtCoffee.BaselineAlignment   = TextBlockBaselineAlignment.Automatic;
            txtCoffee.AutoWidth           = true;
            txtCoffee.ColorSource         = ElementColorSource.BandHighlight;
            txtCoffee.Rect                = new PageRect(0, 0, 32, 32);
            txtCoffee.ElementId           = 8;
            txtCoffee.Margins             = new Margins(0, 0, 0, 0);
            txtCoffee.HorizontalAlignment = HorizontalAlignment.Left;
            txtCoffee.VerticalAlignment   = VerticalAlignment.Top;

            panel3.Elements.Add(txtCoffee);

            txtTea                     = new TextBlock();
            txtTea.Font                = TextBlockFont.Small;
            txtTea.Baseline            = 0;
            txtTea.BaselineAlignment   = TextBlockBaselineAlignment.Automatic;
            txtTea.AutoWidth           = true;
            txtTea.ColorSource         = ElementColorSource.BandHighlight;
            txtTea.Rect                = new PageRect(0, 0, 32, 32);
            txtTea.ElementId           = 9;
            txtTea.Margins             = new Margins(0, 0, 0, 0);
            txtTea.HorizontalAlignment = HorizontalAlignment.Left;
            txtTea.VerticalAlignment   = VerticalAlignment.Top;

            panel3.Elements.Add(txtTea);

            txtBeer                     = new TextBlock();
            txtBeer.Font                = TextBlockFont.Small;
            txtBeer.Baseline            = 0;
            txtBeer.BaselineAlignment   = TextBlockBaselineAlignment.Automatic;
            txtBeer.AutoWidth           = true;
            txtBeer.ColorSource         = ElementColorSource.BandHighlight;
            txtBeer.Rect                = new PageRect(0, 0, 32, 32);
            txtBeer.ElementId           = 10;
            txtBeer.Margins             = new Margins(0, 0, 0, 0);
            txtBeer.HorizontalAlignment = HorizontalAlignment.Left;
            txtBeer.VerticalAlignment   = VerticalAlignment.Top;

            panel3.Elements.Add(txtBeer);

            txtWine                     = new TextBlock();
            txtWine.Font                = TextBlockFont.Small;
            txtWine.Baseline            = 0;
            txtWine.BaselineAlignment   = TextBlockBaselineAlignment.Automatic;
            txtWine.AutoWidth           = true;
            txtWine.ColorSource         = ElementColorSource.BandHighlight;
            txtWine.Rect                = new PageRect(0, 0, 32, 32);
            txtWine.ElementId           = 11;
            txtWine.Margins             = new Margins(0, 0, 0, 0);
            txtWine.HorizontalAlignment = HorizontalAlignment.Left;
            txtWine.VerticalAlignment   = VerticalAlignment.Top;

            panel3.Elements.Add(txtWine);

            panel.Elements.Add(panel3);

            panel4                     = new FlowPanel();
            panel4.Orientation         = FlowPanelOrientation.Vertical;
            panel4.Rect                = new PageRect(0, 0, 90, 130);
            panel4.ElementId           = 12;
            panel4.Margins             = new Margins(157, -128, 0, 0);
            panel4.HorizontalAlignment = HorizontalAlignment.Left;
            panel4.VerticalAlignment   = VerticalAlignment.Top;

            btnCoffee = new TextButton();
            btnCoffee.PressedColor        = new BandColor(32, 32, 32);
            btnCoffee.Rect                = new PageRect(0, 0, 90, 32);
            btnCoffee.ElementId           = 13;
            btnCoffee.Margins             = new Margins(0, 0, 0, 0);
            btnCoffee.HorizontalAlignment = HorizontalAlignment.Center;
            btnCoffee.VerticalAlignment   = VerticalAlignment.Top;

            panel4.Elements.Add(btnCoffee);

            btnTea = new TextButton();
            btnTea.PressedColor        = new BandColor(32, 32, 32);
            btnTea.Rect                = new PageRect(0, 0, 90, 32);
            btnTea.ElementId           = 14;
            btnTea.Margins             = new Margins(0, 0, 0, 0);
            btnTea.HorizontalAlignment = HorizontalAlignment.Center;
            btnTea.VerticalAlignment   = VerticalAlignment.Top;

            panel4.Elements.Add(btnTea);

            btnBeer = new TextButton();
            btnBeer.PressedColor        = new BandColor(32, 32, 32);
            btnBeer.Rect                = new PageRect(0, 0, 90, 32);
            btnBeer.ElementId           = 15;
            btnBeer.Margins             = new Margins(0, 0, 0, 0);
            btnBeer.HorizontalAlignment = HorizontalAlignment.Center;
            btnBeer.VerticalAlignment   = VerticalAlignment.Top;

            panel4.Elements.Add(btnBeer);

            btnWine = new TextButton();
            btnWine.PressedColor        = new BandColor(32, 32, 32);
            btnWine.Rect                = new PageRect(0, 0, 90, 32);
            btnWine.ElementId           = 16;
            btnWine.Margins             = new Margins(0, 0, 0, 0);
            btnWine.HorizontalAlignment = HorizontalAlignment.Center;
            btnWine.VerticalAlignment   = VerticalAlignment.Top;

            panel4.Elements.Add(btnWine);

            panel.Elements.Add(panel4);
            pageLayout = new PageLayout(panel);

            PageElementData[] pageElementDataArray = new PageElementData[12];
            pageElementDataArray[0]  = textBlockData;
            pageElementDataArray[1]  = textBlock2Data;
            pageElementDataArray[2]  = textBlock3Data;
            pageElementDataArray[3]  = textBlock4Data;
            pageElementDataArray[4]  = txtCoffeeData;
            pageElementDataArray[5]  = txtTeaData;
            pageElementDataArray[6]  = txtBeerData;
            pageElementDataArray[7]  = txtWineData;
            pageElementDataArray[8]  = btnCoffeeData;
            pageElementDataArray[9]  = btnTeaData;
            pageElementDataArray[10] = btnBeerData;
            pageElementDataArray[11] = btnWineData;

            pageLayoutData = new PageLayoutData(pageElementDataArray);
        }
コード例 #19
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (CurrentPage == null)
            {
                output.Content.SetHtmlContent("Page object (sde-page) cannot be null");
                return;
            }

            if (ModuleViewResults == null)
            {
                output.Content.SetHtmlContent("Module action results  (sde-module-results) cannot be null");
                return;
            }

            if (CurrentPage.Layout == null)
            {
                output.Content.SetHtmlContent("Layout is not configured, choose a layout");
                return;
            }


            ((HtmlHelper)_htmlHelper).Contextualize(ViewContext);

            var pageLayout = new PageLayout {
                Name = CurrentPage.Layout.Name
            };

            var properties = _propertyRepository.GetProperties();

            pageLayout.PlaceHolders = JsonConvert.DeserializeObject <List <PlaceHolder> >(CurrentPage.Layout.Config);

            GetPropertyValue(pageLayout.PlaceHolders, properties);

            PageContents = _mapper.Map <ICollection <PageContent> >(CurrentPage.PageContent);

            //Copy property options from master data
            if (PageContents != null && PageContents.Count > 0)
            {
                foreach (var pageContent in PageContents)
                {
                    if (pageContent.ContentType.Properties != null && pageContent.ContentType.Properties.Count > 0)
                    {
                        foreach (var prop in pageContent.ContentType.Properties)
                        {
                            var propValue = pageContent.Properties.FirstOrDefault(p => p.Id == prop.Id);
                            if (propValue != null)
                            {
                                propValue.OptionListId = prop.OptionListId;
                                propValue.OptionList   = prop.OptionList;
                            }
                        }
                    }
                }
            }

            if (pageLayout.PlaceHolders == null || pageLayout.PlaceHolders.Count <= 0)
            {
                return;
            }
            var result = RenderContentItems(pageLayout.PlaceHolders);

            if (ModuleViewResults.Count > 0)
            {
                //One or more modules are not added in containers
                foreach (var moduleViewResult in ModuleViewResults)
                {
                    if (moduleViewResult.Value != null && moduleViewResult.Value.Count > 0)
                    {
                        foreach (var contentResult in moduleViewResult.Value)
                        {
                            //result += contentResult.HtmlResult;
                            result.AppendHtml(contentResult.HtmlResult);
                        }
                    }
                }
            }
            output.Content.SetHtmlContent(result);

            //Release all resources
            pageLayout.RegisterForDispose(ViewContext.HttpContext);
            PageContents.GetEnumerator().RegisterForDispose(ViewContext.HttpContext);
            ModuleViewResults.GetEnumerator().RegisterForDispose(ViewContext.HttpContext);
            pageLayout.RegisterForDispose(ViewContext.HttpContext);
        }
コード例 #20
0
ファイル: GroupTile.cs プロジェクト: jorisdg/wink
        public GroupTile()
        {
            LoadIconMethod  = LoadIcon;
            AdjustUriMethod = (uri) => uri;

            panel = new FilledPanel();
            panel.BackgroundColorSource = ElementColorSource.Custom;
            panel.BackgroundColor       = new BandColor(0, 0, 0);
            panel.Rect                = new PageRect(0, 0, 248, 128);
            panel.ElementId           = 1;
            panel.Margins             = new Margins(0, 0, 0, 0);
            panel.HorizontalAlignment = HorizontalAlignment.Left;
            panel.VerticalAlignment   = VerticalAlignment.Top;
            panel.Visible             = true;

            textBlock                     = new TextBlock();
            textBlock.Font                = TextBlockFont.Small;
            textBlock.Baseline            = 0;
            textBlock.BaselineAlignment   = TextBlockBaselineAlignment.Automatic;
            textBlock.AutoWidth           = false;
            textBlock.ColorSource         = ElementColorSource.BandHighlight;
            textBlock.Rect                = new PageRect(15, 0, 243, 30);
            textBlock.ElementId           = 2;
            textBlock.Margins             = new Margins(0, 0, 0, 0);
            textBlock.HorizontalAlignment = HorizontalAlignment.Left;
            textBlock.VerticalAlignment   = VerticalAlignment.Bottom;
            textBlock.Visible             = true;

            panel.Elements.Add(textBlock);

            textBlock2                     = new TextBlock();
            textBlock2.Font                = TextBlockFont.Large;
            textBlock2.Baseline            = 0;
            textBlock2.BaselineAlignment   = TextBlockBaselineAlignment.Automatic;
            textBlock2.AutoWidth           = false;
            textBlock2.ColorSource         = ElementColorSource.Custom;
            textBlock2.Color               = new BandColor(255, 255, 255);
            textBlock2.Rect                = new PageRect(73, 65, 185, 48);
            textBlock2.ElementId           = 4;
            textBlock2.Margins             = new Margins(0, 0, 0, 0);
            textBlock2.HorizontalAlignment = HorizontalAlignment.Left;
            textBlock2.VerticalAlignment   = VerticalAlignment.Top;
            textBlock2.Visible             = true;

            panel.Elements.Add(textBlock2);

            icon                     = new Icon();
            icon.ColorSource         = ElementColorSource.BandHighlight;
            icon.Rect                = new PageRect(15, 65, 48, 48);
            icon.ElementId           = 3;
            icon.Margins             = new Margins(0, 0, 0, 0);
            icon.HorizontalAlignment = HorizontalAlignment.Left;
            icon.VerticalAlignment   = VerticalAlignment.Top;
            icon.Visible             = true;

            panel.Elements.Add(icon);
            pageLayout = new PageLayout(panel);

            PageElementData[] pageElementDataArray = new PageElementData[3];
            pageElementDataArray[0] = textBlockData;
            pageElementDataArray[1] = textBlock2Data;
            pageElementDataArray[2] = iconData;

            pageLayoutData = new PageLayoutData(pageElementDataArray);
        }
コード例 #21
0
 public static void Update(this Shop shop, ShopViewModel model, PageStyle style, PageLayout layout)
 {
     shop.Address = model.Address;
     shop.Email   = model.Email;
     shop.Name    = model.Name;
     shop.Phone   = model.Phone;
     if (style != null)
     {
         shop.PageStyle = style;
     }
     if (layout != null)
     {
         shop.PageLayout = layout;
     }
 }
コード例 #22
0
        /// <summary>
        /// Analyses a publishing page
        /// </summary>
        /// <returns>Information about the analyzed publishing page</returns>
        public Tuple <PageLayout, List <WebPartEntity> > Analyze(Publishing.PageLayout publishingPageTransformationModel)
        {
            List <WebPartEntity> webparts = new List <WebPartEntity>();

            //Load the page
            var publishingPageUrl = page[Constants.FileRefField].ToString();
            var publishingPage    = cc.Web.GetFileByServerRelativeUrl(publishingPageUrl);

            // Load relevant model data for the used page layout in case not already provided - safetynet for calls from modernization scanner
            string usedPageLayout = System.IO.Path.GetFileNameWithoutExtension(page.PageLayoutFile());

            if (publishingPageTransformationModel == null)
            {
                publishingPageTransformationModel = this.publishingPageTransformation.PageLayouts.Where(p => p.Name.Equals(usedPageLayout, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

                // No layout provided via either the default mapping or custom mapping file provided
                if (publishingPageTransformationModel == null)
                {
                    publishingPageTransformationModel = CacheManager.Instance.GetPageLayoutMapping(page);
                }
            }

            // Still no layout...can't continue...
            if (publishingPageTransformationModel == null)
            {
                LogError(string.Format(LogStrings.Error_NoPageLayoutTransformationModel, usedPageLayout), LogStrings.Heading_PublishingPage);
                throw new Exception(string.Format(LogStrings.Error_NoPageLayoutTransformationModel, usedPageLayout));
            }

            // Map layout
            PageLayout layout = MapToLayout(publishingPageTransformationModel.PageLayoutTemplate);

            #region Process fields that become web parts
            if (publishingPageTransformationModel.WebParts != null)
            {
                #region Publishing Html column processing
                // Converting to WikiTextPart is a special case as we'll need to process the html
                var wikiTextWebParts = publishingPageTransformationModel.WebParts.Where(p => p.TargetWebPart.Equals(WebParts.WikiText, StringComparison.InvariantCultureIgnoreCase));
                List <WebPartPlaceHolder> webPartsToRetrieve = new List <WebPartPlaceHolder>();
                foreach (var wikiTextPart in wikiTextWebParts)
                {
                    var pageContents = page.GetFieldValueAs <string>(wikiTextPart.Name);
                    if (pageContents != null && !string.IsNullOrEmpty(pageContents))
                    {
                        var htmlDoc = parser.Parse(pageContents);

                        // Analyze the html block (which is a wiki block)
                        var content = htmlDoc.FirstElementChild.LastElementChild;
                        AnalyzeWikiContentBlock(webparts, htmlDoc, webPartsToRetrieve, wikiTextPart.Row, wikiTextPart.Column, GetNextOrder(wikiTextPart.Row, wikiTextPart.Column, wikiTextPart.Order, webparts), content);
                    }
                    else
                    {
                        LogWarning(LogStrings.Warning_CannotRetrieveFieldValue, LogStrings.Heading_PublishingPage);
                    }
                }

                // Bulk load the needed web part information
                if (webPartsToRetrieve.Count > 0)
                {
                    LoadWebPartsInWikiContentFromServer(webparts, publishingPage, webPartsToRetrieve);
                }
                #endregion

                #region Generic processing of the other 'webpart' fields
                var fieldWebParts = publishingPageTransformationModel.WebParts.Where(p => !p.TargetWebPart.Equals(WebParts.WikiText, StringComparison.InvariantCultureIgnoreCase));
                foreach (var fieldWebPart in fieldWebParts.OrderBy(p => p.Row).OrderBy(p => p.Column))
                {
                    // In publishing scenarios it's common to not have all fields defined in the page layout mapping filled. By default we'll not map empty fields as that will result in empty web parts
                    // which impact the page look and feel. Using the RemoveEmptySectionsAndColumns flag this behaviour can be turned off.
                    if (this.baseTransformationInformation.RemoveEmptySectionsAndColumns)
                    {
                        var fieldContents = page.GetFieldValueAs <string>(fieldWebPart.Name);

                        if (string.IsNullOrEmpty(fieldContents))
                        {
                            LogWarning(String.Format(LogStrings.Warning_SkippedWebPartDueToEmptyInSourcee, fieldWebPart.TargetWebPart, fieldWebPart.Name), LogStrings.Heading_PublishingPage);
                            continue;
                        }
                    }

                    Dictionary <string, string> properties = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);

                    foreach (var fieldWebPartProperty in fieldWebPart.Property)
                    {
                        if (!string.IsNullOrEmpty(fieldWebPartProperty.Functions))
                        {
                            // execute function
                            var evaluatedField = this.functionProcessor.Process(fieldWebPartProperty.Functions, fieldWebPartProperty.Name, MapToFunctionProcessorFieldType(fieldWebPartProperty.Type));
                            if (!string.IsNullOrEmpty(evaluatedField.Item1) && !properties.ContainsKey(evaluatedField.Item1))
                            {
                                properties.Add(evaluatedField.Item1, evaluatedField.Item2);
                            }
                        }
                        else
                        {
                            var webPartName = page.FieldValues[fieldWebPart.Name]?.ToString().Trim();
                            if (webPartName != null)
                            {
                                properties.Add(fieldWebPartProperty.Name, page.FieldValues[fieldWebPart.Name].ToString().Trim());
                            }
                        }
                    }

                    var wpEntity = new WebPartEntity()
                    {
                        Title      = fieldWebPart.Name,
                        Type       = fieldWebPart.TargetWebPart,
                        Id         = Guid.Empty,
                        Row        = fieldWebPart.Row,
                        Column     = fieldWebPart.Column,
                        Order      = GetNextOrder(fieldWebPart.Row, fieldWebPart.Column, fieldWebPart.Order, webparts),
                        Properties = properties,
                    };

                    webparts.Add(wpEntity);
                }
            }
            #endregion
            #endregion

            #region Process fields that become metadata as they might result in the creation of page properties web part
            if (publishingPageTransformationModel.MetaData.ShowPageProperties)
            {
                List <string> pagePropertiesFields = new List <string>();

                var fieldsToProcess = publishingPageTransformationModel.MetaData.Field.Where(p => p.ShowInPageProperties == true && !string.IsNullOrEmpty(p.TargetFieldName));

                if (fieldsToProcess.Any())
                {
                    // Loop over the fields that are defined to be shown in the page properties and that have a target field name set
                    foreach (var fieldToProcess in fieldsToProcess)
                    {
                        var targetFieldInstance = targetContext.Web.GetFieldByInternalName(fieldToProcess.TargetFieldName, true);
                        if (targetFieldInstance != null)
                        {
                            if (!pagePropertiesFields.Contains(targetFieldInstance.Id.ToString()))
                            {
                                pagePropertiesFields.Add(targetFieldInstance.Id.ToString());
                            }
                        }
                    }

                    if (pagePropertiesFields.Count > 0)
                    {
                        string propertyString = "";
                        foreach (var propertyField in pagePropertiesFields)
                        {
                            if (!string.IsNullOrEmpty(propertyField))
                            {
                                propertyString = $"{propertyString},\"{propertyField.ToString()}\"";
                            }
                        }

                        if (!string.IsNullOrEmpty(propertyString))
                        {
                            propertyString = propertyString.TrimStart(new char[] { ',' });
                        }

                        if (!string.IsNullOrEmpty(propertyString))
                        {
                            Dictionary <string, string> properties = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase)
                            {
                                { "SelectedFields", propertyString }
                            };

                            var wpEntity = new WebPartEntity()
                            {
                                Type       = WebParts.PageProperties,
                                Id         = Guid.Empty,
                                Row        = publishingPageTransformationModel.MetaData.PagePropertiesRow,
                                Column     = publishingPageTransformationModel.MetaData.PagePropertiesColumn,
                                Order      = GetNextOrder(publishingPageTransformationModel.MetaData.PagePropertiesRow, publishingPageTransformationModel.MetaData.PagePropertiesColumn, publishingPageTransformationModel.MetaData.PagePropertiesOrder, webparts),
                                Properties = properties,
                            };

                            webparts.Add(wpEntity);
                        }
                    }
                }
            }
            #endregion

            #region Web Parts in webpart zone handling
            // Load web parts put in web part zones on the publishing page
            // Note: Web parts placed outside of a web part zone using SPD are not picked up by the web part manager.
            var limitedWPManager = publishingPage.GetLimitedWebPartManager(PersonalizationScope.Shared);
            cc.Load(limitedWPManager);

            IEnumerable <WebPartDefinition> webPartsViaManager = cc.LoadQuery(limitedWPManager.WebParts.IncludeWithDefaultProperties(wp => wp.Id, wp => wp.ZoneId, wp => wp.WebPart.ExportMode, wp => wp.WebPart.Title, wp => wp.WebPart.ZoneIndex, wp => wp.WebPart.IsClosed, wp => wp.WebPart.Hidden, wp => wp.WebPart.Properties));
            cc.ExecuteQueryRetry();

            if (webPartsViaManager.Count() > 0)
            {
                List <WebPartPlaceHolder> webPartsToRetrieve = new List <WebPartPlaceHolder>();

                foreach (var foundWebPart in webPartsViaManager)
                {
                    // Remove the web parts which we've already picked up by analyzing the wiki content block
                    if (webparts.Where(p => p.Id.Equals(foundWebPart.Id)).FirstOrDefault() != null)
                    {
                        continue;
                    }

                    webPartsToRetrieve.Add(new WebPartPlaceHolder()
                    {
                        WebPartDefinition = foundWebPart,
                        WebPartXml        = null,
                        WebPartType       = "",
                    });
                }

                bool isDirty = false;
                foreach (var foundWebPart in webPartsToRetrieve)
                {
                    if (foundWebPart.WebPartDefinition.WebPart.ExportMode == WebPartExportMode.All)
                    {
                        foundWebPart.WebPartXml = limitedWPManager.ExportWebPart(foundWebPart.WebPartDefinition.Id);
                        isDirty = true;
                    }
                }
                if (isDirty)
                {
                    cc.ExecuteQueryRetry();
                }

                foreach (var foundWebPart in webPartsToRetrieve.OrderBy(p => p.WebPartDefinition.WebPart.ZoneIndex))
                {
                    if (foundWebPart.WebPartDefinition.WebPart.ExportMode != WebPartExportMode.All)
                    {
                        // Use different approach to determine type as we can't export the web part XML without indroducing a change
                        foundWebPart.WebPartType = GetTypeFromProperties(foundWebPart.WebPartDefinition.WebPart.Properties);
                    }
                    else
                    {
                        foundWebPart.WebPartType = GetType(foundWebPart.WebPartXml.Value);
                    }

                    int wpInZoneRow  = 1;
                    int wpInZoneCol  = 1;
                    int wpStartOrder = 0;
                    // Determine location based upon the location given to the web part zone in the mapping
                    if (publishingPageTransformationModel.WebPartZones != null)
                    {
                        var wpZoneFromTemplate = publishingPageTransformationModel.WebPartZones.Where(p => p.ZoneId.Equals(foundWebPart.WebPartDefinition.ZoneId, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                        if (wpZoneFromTemplate != null)
                        {
                            wpInZoneRow  = wpZoneFromTemplate.Row;
                            wpInZoneCol  = wpZoneFromTemplate.Column;
                            wpStartOrder = wpZoneFromTemplate.Order;
                        }
                    }

                    // Determine order already taken
                    int wpInZoneOrderUsed = GetNextOrder(wpInZoneRow, wpInZoneCol, wpStartOrder, webparts);

                    webparts.Add(new WebPartEntity()
                    {
                        Title           = foundWebPart.WebPartDefinition.WebPart.Title,
                        Type            = foundWebPart.WebPartType,
                        Id              = foundWebPart.WebPartDefinition.Id,
                        ServerControlId = foundWebPart.WebPartDefinition.Id.ToString(),
                        Row             = wpInZoneRow,
                        Column          = wpInZoneCol,
                        Order           = wpInZoneOrderUsed + foundWebPart.WebPartDefinition.WebPart.ZoneIndex,
                        ZoneId          = foundWebPart.WebPartDefinition.ZoneId,
                        ZoneIndex       = (uint)foundWebPart.WebPartDefinition.WebPart.ZoneIndex,
                        IsClosed        = foundWebPart.WebPartDefinition.WebPart.IsClosed,
                        Hidden          = foundWebPart.WebPartDefinition.WebPart.Hidden,
                        Properties      = Properties(foundWebPart.WebPartDefinition.WebPart.Properties, foundWebPart.WebPartType, foundWebPart.WebPartXml == null ? "" : foundWebPart.WebPartXml.Value),
                    });
                }
            }
            #endregion

            #region Fixed webparts mapping
            if (publishingPageTransformationModel.FixedWebParts != null)
            {
                foreach (var fixedWebpart in publishingPageTransformationModel.FixedWebParts)
                {
                    int wpFixedOrderUsed = GetNextOrder(fixedWebpart.Row, fixedWebpart.Column, fixedWebpart.Order, webparts);

                    webparts.Add(new WebPartEntity()
                    {
                        Title      = GetFixedWebPartProperty <string>(fixedWebpart, "Title", ""),
                        Type       = fixedWebpart.Type,
                        Id         = Guid.NewGuid(),
                        Row        = fixedWebpart.Row,
                        Column     = fixedWebpart.Column,
                        Order      = wpFixedOrderUsed,
                        ZoneId     = "",
                        ZoneIndex  = 0,
                        IsClosed   = GetFixedWebPartProperty <bool>(fixedWebpart, "__designer:IsClosed", false),
                        Hidden     = false,
                        Properties = CastAsPropertiesDictionary(fixedWebpart),
                    });
                }
            }
            #endregion

            return(new Tuple <PageLayout, List <WebPartEntity> >(layout, webparts));
        }
コード例 #23
0
ファイル: MainPage.xaml.cs プロジェクト: farukc/IoTHelpers
        private async Task CreateJukeboxTileAsync()
        {
            // create the small and tile icons from writable bitmaps.
            // Small icons are 24x24 pixels.
            var writeableSmallBmp = BitmapFactory.New(24, 24);

            using (writeableSmallBmp.GetBitmapContext())
            {
                // Load an image from the calling Assembly's resources via the relative path
                writeableSmallBmp = await BitmapFactory.New(1, 1).FromContent(new Uri("ms-appx:///Assets/Sensor24x24.png"));
            }
            var smallIcon = writeableSmallBmp.ToBandIcon();

            // Tile icons are 46x46 pixels for Microsoft Band 1, and 48x48 pixels for Microsoft
            // Band 2.
            var writeableBmp = BitmapFactory.New(46, 46);

            using (writeableBmp.GetBitmapContext())
            {
                // Load an image from the calling Assembly's resources via the relative path
                writeableBmp = await BitmapFactory.New(1, 1).FromContent(new Uri("ms-appx:///Assets/Sensor46x46.png"));
            }
            var tileIcon = writeableBmp.ToBandIcon();

            // create a new Guid for the tile
            var tileGuid = Guid.NewGuid();

            // create a new tile with a new Guid
            var tile = new BandTile(tileGuid)
            {
                IsBadgingEnabled = true,
                Name             = "Sensor Manager",
                SmallIcon        = smallIcon,
                TileIcon         = tileIcon
            };

            // create a filled rectangle to provide the background for a button
            var panel = new FilledPanel
            {
                Rect = new PageRect(0, 0, 245, 102)
            };

            // add buttons to our layout
            panel.Elements.Add(new TextButton
            {
                ElementId    = (short)TilePageElementId.Jukebox_PlayRandom,
                Rect         = new PageRect(20, 0, 70, 102),
                PressedColor = Colors.Blue.ToBandColor()
            });

            panel.Elements.Add(new TextButton
            {
                ElementId    = (short)TilePageElementId.Jukebox_Pause,
                Rect         = new PageRect(120, 0, 100, 45),
                PressedColor = Colors.Blue.ToBandColor()
            });

            panel.Elements.Add(new TextButton
            {
                ElementId    = (short)TilePageElementId.Jukebox_Stop,
                Rect         = new PageRect(120, 55, 100, 45),
                PressedColor = Colors.Blue.ToBandColor()
            });

            // create the page layout
            var layout = new PageLayout(panel);

            // add the tile to the Band
            tile.PageLayouts.Add(layout);
            if (await bandClient.TileManager.AddTileAsync(tile))
            {
                // create the content to assign to the page
                var pageContent = new PageData(Guid.NewGuid(),
                                               0, // index of our (only) layout
                                               new TextButtonData((short)TilePageElementId.Jukebox_PlayRandom, "Play"),
                                               new TextButtonData((short)TilePageElementId.Jukebox_Pause, "Pause"),
                                               new TextButtonData((short)TilePageElementId.Jukebox_Stop, "Stop"));

                await bandClient.TileManager.SetPagesAsync(tileGuid, pageContent);
            }
        }
コード例 #24
0
        private async void OnAddButtonTileClick(object sender, EventArgs e)
        {
            try
            {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.InScaled = false;
                BandIcon tileIcon = BandIcon.ToBandIcon(BitmapFactory.DecodeResource(Resources, Resource.Raw.tile, options));

                BandIcon badgeIcon = BandIcon.ToBandIcon(BitmapFactory.DecodeResource(Resources, Resource.Raw.badge, options));

                FilledButton button = new FilledButton(0, 5, 210, 45);
                button.BackgroundColor = Color.Red;
                button.Margins         = new Margins(0, 5, 0, 0);
                button.ElementId       = 12;

                TextButton button2 = new TextButton(0, 0, 210, 45);
                button2.PressedColor = Color.Blue;
                button2.Margins      = new Margins(0, 5, 0, 0);
                button2.ElementId    = 21;

                FlowPanel flowPanel = new FlowPanel(15, 0, 260, 105, FlowPanelOrientation.Vertical);
                flowPanel.AddElements(button);
                flowPanel.AddElements(button2);

                PageLayout pageLayout = new PageLayout(flowPanel);

                BandTile.Builder builder = new BandTile.Builder(Java.Util.UUID.RandomUUID(), mEditTileName.Text, tileIcon);
                if (mCheckboxBadging.Checked)
                {
                    builder.SetTileSmallIcon(badgeIcon);
                }
                if (mCheckboxCustomTheme.Checked)
                {
                    builder.SetTheme(mThemeView.Theme);
                }
                builder.SetPageLayouts(pageLayout);
                BandTile tile = builder.Build();

                try
                {
                    var result = await Model.Instance.Client.TileManager.AddTileTaskAsync(Activity, tile);

                    if (result)
                    {
                        Toast.MakeText(Activity, "Tile added", ToastLength.Short).Show();
                    }
                    else
                    {
                        Toast.MakeText(Activity, "Unable to add tile", ToastLength.Short).Show();
                    }
                }
                catch (Exception ex)
                {
                    Util.ShowExceptionAlert(Activity, "Add tile", ex);
                }

                PageData pageData = new PageData(Java.Util.UUID.RandomUUID(), 0);
                pageData.Update(new FilledButtonData(12, Color.Yellow));
                pageData.Update(new TextButtonData(21, "Text Button"));
                await Model.Instance.Client.TileManager.SetPagesTaskAsync(tile.TileId, pageData);

                Toast.MakeText(Activity, "Page updated", ToastLength.Short).Show();

                // Refresh our tile list and count
                await RefreshData();

                RefreshControls();
            }
            catch (Exception ex)
            {
                Util.ShowExceptionAlert(Activity, "Add tile", ex);
            }
        }
コード例 #25
0
        private void MakeDoc1(C1PrintDocument doc)
        {
            doc.Style.Font = new Font("Verdana", 14);

            // create the title of the document
            RenderParagraph title = new RenderParagraph();

            title.Content.AddText("The new version of C1PrintDocumet provides the ");
            title.Content.AddText("PageLayouts", Color.Blue);
            title.Content.AddText(" property allowing to define separate page layouts for the first page, even pages, and odd pages.");
            title.Style.TextAlignHorz  = AlignHorzEnum.Justify;
            title.Style.Borders.Bottom = new LineDef("1mm", Color.Black);
            doc.Body.Children.Add(title);

            // define PageLayout for the first page
            PageLayout pl = new PageLayout();

            pl.PageSettings           = new C1PageSettings();
            pl.PageSettings.PaperKind = PaperKind.Legal;
            doc.PageLayouts.FirstPage = pl;

            // define PageLayout for even pages
            pl = new PageLayout();
            pl.PageSettings           = new C1PageSettings();
            pl.PageSettings.PaperKind = PaperKind.Letter;
            // create the page header
            RenderText ph = new RenderText();

            ph.Text = "Even page. [PageNo] / [PageCount]";
            ph.Style.Borders.All = LineDef.Default;
            ph.Style.BackColor   = Color.Beige;
            pl.PageHeader        = ph;
            // even pages will have no page footer, set it to an empty object
            pl.PageFooter             = new RenderEmpty();
            doc.PageLayouts.EvenPages = pl;

            // define PageLayout for odd pages
            pl = new PageLayout();
            // odd pages will have 2 columns
            pl.Columns.Add();
            pl.Columns.Add();
            pl.PageSettings           = new C1PageSettings();
            pl.PageSettings.PaperKind = PaperKind.Letter;
            pl.PageSettings.Landscape = true;
            // create the page header
            ph      = new RenderText();
            ph.Text = "Odd page. [PageNo] / [PageCount]";
            ph.Style.Borders.All = LineDef.DefaultBold;
            ph.Style.BackColor   = Color.LightSeaGreen;
            pl.PageHeader        = ph;
            // create the page footer
            RenderText pf = new RenderText();

            pf.Text = "Footer of odd page. [PageNo] / [PageCount]";
            pf.Style.Borders.All     = LineDef.DefaultBold;
            pf.Style.BackColor       = Color.SlateGray;
            pl.PageFooter            = pf;
            doc.PageLayouts.OddPages = pl;

            // generate the content of document
            RenderText ro = new RenderText("This is the first page of the document. It has no page header or footer, and has Legal size.");

            ro.BreakAfter = BreakEnum.Page;
            doc.Body.Children.Add(ro);

            //
            string text = "This is the house  that Jack  built.  " +
                          "This is the carrot,  " +
                          "That lay in the house  that Jack  built.  " +
                          "This is the rat,  " +
                          "That ate the carrot,  " +
                          "That lay in the house  that Jack  built.  " +
                          "This is the cat,  " +
                          "That chased the rat , that ate the carrot,  " +
                          "That lay in the house  that Jack  built.  " +
                          "This is the dog  that worried the cat,  " +
                          "That chased the rat , that ate the carrot,  " +
                          "That lay in the house  that Jack  built.  " +
                          "This is the cow  with the crumbled horn, " +
                          "That tossed the dog , that worried the cat,  " +
                          "That chased the rat , that ate the carrot,  " +
                          "That lay in the house  that Jack  built.  " +
                          "This is the maiden  all forlorn,  " +
                          "That milked  the cow  with the crumbled horn, " +
                          "That tossed the dog , that worried the cat,  " +
                          "That chased the rat , that ate the carrot,  " +
                          "That lay in the house  that Jack  built.   " +
                          "This is the man  all tattered and torn, " +
                          "That kissed  the maiden  all forlorn,  " +
                          "That milked  the cow  with the crumbled horn, " +
                          "That tossed the dog , that worried the cat,  " +
                          "That chased the rat , that ate the carrot,  " +
                          "That lay in the house  that Jack  built.  " +
                          "This is the priest  all shaven and shorn, " +
                          "That married the man  all tattered and torn, " +
                          "That kissed  the maiden  all forlorn,  " +
                          "That milked  the cow  with the crumbled horn, " +
                          "That tossed the dog , that worried the cat,  " +
                          "That chased the rat , that ate the carrot,  " +
                          "That lay in the house  that Jack  built.  " +
                          "This is the c**k  that crowed  in the morn,  " +
                          "That waked the priest  all shaven and shorn, " +
                          "That married the man  all tattered and torn, " +
                          "That kissed  the maiden  all forlorn,  " +
                          "That milked  the cow  with the crumbled horn, " +
                          "That tossed the dog , that worried the cat,  " +
                          "That chased the rat , that ate the carrot,  " +
                          "That lay in the house  that Jack  built.  " +
                          "This is the farmer  sowing the corn,   " +
                          "That kept the c**k  that crowed  in the morn,   " +
                          "That waked the priest  all shaven and shorn, " +
                          "That married the man  all tattered and torn, " +
                          "That kissed  the maiden  all forlorn,  " +
                          "That milked  the cow  with the crumbled horn, " +
                          "That tossed the dog , that worried the cat,  " +
                          "That chased the rat , that ate the carrot,  " +
                          "That lay in the house  that Jack  built.  ";

            for (int i = 0; i < 5; ++i)
            {
                doc.Body.Children.Add(new RenderText(text, AlignHorzEnum.Justify));
            }
        }
コード例 #26
0
        protected override void Seed(CmsContext context)
        {
            string adName = HttpContext.Current.User.Identity.Name.ToLower();

            var currentUser = new
            {
                AdName = adName,
                Name   = adName.Split('\\')[1]
            };

            var NOW = DateTime.Now;

            #region create Content Types
            ContentType t1 = new ContentType
            {
                Title = "PAGE"
            };

            context.Set <ContentType>().Add(t1);
            context.SaveChanges();
            #endregion

            #region create navi nodes
            NaviNode n = new NaviNode
            {
                NodeName      = "Home",
                CreatedBy     = currentUser.AdName,
                Created       = NOW,
                ModifiedBy    = currentUser.AdName,
                Modified      = NOW,
                DefaultPageId = 1,
            };

            NaviNode n0 = new NaviNode
            {
                NodeName   = "Explore",
                Parent     = n,
                MenuOrder  = 1,
                CreatedBy  = currentUser.AdName,
                Created    = NOW,
                ModifiedBy = currentUser.AdName,
                Modified   = NOW,
            };

            NaviNode n1 = new NaviNode
            {
                NodeName   = "Improve",
                Parent     = n,
                MenuOrder  = 1,
                CreatedBy  = currentUser.AdName,
                Created    = NOW,
                ModifiedBy = currentUser.AdName,
                Modified   = NOW,
            };

            NaviNode n2 = new NaviNode
            {
                NodeName   = "Balance",
                Parent     = n,
                MenuOrder  = 2,
                CreatedBy  = currentUser.AdName,
                Created    = NOW,
                ModifiedBy = currentUser.AdName,
                Modified   = NOW,
            };

            NaviNode n3 = new NaviNode
            {
                NodeName   = "Screen Yourself",
                Parent     = n,
                MenuOrder  = 3,
                CreatedBy  = currentUser.AdName,
                Created    = NOW,
                ModifiedBy = currentUser.AdName,
                Modified   = NOW,
            };

            var naviNodes = new List <NaviNode> {
                n,
                n0,
                n1,
                n2,
                n3,
            };

            naviNodes.ForEach(s =>
            {
                s.Type = t1;
                context.Set <NaviNode>().Add(s);
            });
            context.SaveChanges();

            #endregion

            #region create layouts
            var level1 = new PageLayout
            {
                Style    = @"
#cms-region-1 { 
    width: 100%; 
    min-height: 400px; 
    float: left; 
} 
#contentWrapper article{ 
    width: 100%; 
}
.image-group{
    border-top:1px solid grey;
    background-color: #EFF0F2;
    width: 100%; 
    height: 100%;
  }
.col.col-3-1, .col.col-3-2, .col.col-3-3{
    width: 33.3%;
    padding: 15px;
    box-sizing: border-box;
    float: left;
}",
                Title    = "LEVEL 1",
                Template = @"
<div class=""main wrapper clearfix"">
    <article class=""clearfix"">
        [$webpart(breadcrumb)$]
        [$webpart(title)$]
        <div class=""cms-editable"" data-region=""region1"">
            {region1}
        </div>
    </article>
</div>
<div class=""cms-editable"" data-region=""region2"">
    <div class=""image-group clearfix"">
        <div class=""wrapper"">
            <div class=""col col-3-1""><img src=""""></div>
            <div class=""col col-3-2""><img src=""""></div>
            <div class=""col col-3-3""><img src=""""></div>
        </div>
    </div>
</div>"
            };
            var level2 = new PageLayout
            {
                Style    = @"
#cms-region-1 { 
    width: 100%; 
} 
#cms-region-1 .cms-editable-container { 
    min-height: 400px; 
}",
                Title    = "LEVEL 2",
                Template = @"
<div class=""main wrapper clearfix"">
    <article class=""clearfix"">
        [$webpart(breadcrumb)$]
        [$webpart(title)$]
        <div class=""cms-editable"" data-region=""region1"">
            {region1}
        </div>
    </article>
    [$webpart(sidemenu)$]
</div>"
            };
            var home = new PageLayout
            {
                Style    = @"
#cms-region-1 { 
    min-height: 400px; 
    float: left; 
    width: 100%;
}
.main article{
    width: 100%;
}
",
                Title    = "HOME",
                Template = @"
[$webpart(carousel)$]
<div class=""main wrapper clearfix"">
    <article class=""clearfix"">
        <div class=""cms-editable"" data-region=""region1"">
            {region1}
        </div>
    </article>
</div>
"
            };

            var layouts = new List <PageLayout> {
                level1,
                level2,
                home,
            };
            layouts.ForEach(s =>
            {
                s.Type = t1;
                context.Set <PageLayout>().Add(s);
            });
            context.SaveChanges();
            #endregion

            #region create pages
            var pages = new List <CmsPage> {
                new CmsPage {
                    Title = "Home",
                    Html  = new CmsPageHtml {
                        Content = home.Template, Sidebar = ""
                    },
                    NaviNode    = n,
                    IsPublished = true,
                    Layout      = home.Id,
                    CreatedBy   = currentUser.AdName,
                    Status      = CmsPage.STATUS_NORMAL,
                    Created     = NOW,
                    ModifiedBy  = currentUser.AdName,
                    Modified    = NOW,
                },

                new CmsPage {
                    Title    = "Overview",
                    NaviNode = n0,
                    Html     = new CmsPageHtml {
                        Content = level1.Template, Sidebar = ""
                    },
                    IsPublished = true,
                    MenuOrder   = 0,
                    Status      = CmsPage.STATUS_NORMAL,
                    CreatedBy   = currentUser.AdName,
                    Created     = NOW,
                    ModifiedBy  = currentUser.AdName,
                    Modified    = NOW,
                    Layout      = level1.Id,
                },

                new CmsPage {
                    Title    = "Overview",
                    NaviNode = n1,
                    Html     = new CmsPageHtml {
                        Content = level1.Template, Sidebar = ""
                    },
                    IsPublished = true,
                    MenuOrder   = 0,
                    Status      = CmsPage.STATUS_NORMAL,
                    CreatedBy   = currentUser.AdName,
                    Created     = NOW,
                    ModifiedBy  = currentUser.AdName,
                    Modified    = NOW,
                    Layout      = level1.Id,
                },

                new CmsPage {
                    Title    = "Overview",
                    NaviNode = n2,

                    Html = new CmsPageHtml {
                        Content = level1.Template, Sidebar = ""
                    },
                    IsPublished = true,
                    Status      = CmsPage.STATUS_NORMAL,
                    CreatedBy   = currentUser.AdName,
                    Created     = NOW,
                    ModifiedBy  = currentUser.AdName,
                    Modified    = NOW,
                    Layout      = level1.Id,
                },

                new CmsPage {
                    Title    = "Overview",
                    NaviNode = n3,

                    Html = new CmsPageHtml {
                        Content = level1.Template, Sidebar = ""
                    },
                    IsPublished = true,
                    Status      = CmsPage.STATUS_NORMAL,
                    CreatedBy   = currentUser.AdName,
                    Created     = NOW,
                    ModifiedBy  = currentUser.AdName,
                    Modified    = NOW,
                    Layout      = level1.Id,
                },
            };
            IPageUrlHelper helper = new PageBasedUrlHelper();
            pages.ForEach(p => helper.UpdatePageUrl(p));
            pages.ForEach(s =>
            {
                s.Type = t1;
                context.Set <CmsPage>().Add(s);
            });
            context.SaveChanges();

            #endregion

            #region Cms Users

            var users = new List <CmsUser> {
                new CmsUser {
                    AdName   = currentUser.AdName,
                    UserName = currentUser.Name,
                    RoleId   = RoleType.Admin
                }
            };

            users.ForEach(s => context.Set <CmsUser>().Add(s));
            #endregion

            #region Footer
            var s1 = new FooterSection
            {
                Title  = "CONTACT US",
                Column = 1,
                Order  = 1,
            };
            var s2 = new FooterSection
            {
                Title  = "CONNECT WITH US",
                Column = 2,
                Order  = 1,
            };
            var s3 = new FooterSection
            {
                Title  = "OPPORTUNITIES",
                Column = 3,
                Order  = 1,
            };
            var s4 = new FooterSection
            {
                Title  = "READERS & VIEWERS",
                Column = 4,
                Order  = 1,
            };

            var sections = new List <FooterSection>
            {
                s1, s2, s3, s4,
            };
            var items = new List <FooterItem> {
                new FooterItem {
                    Section     = s1,
                    Title       = "Federal Railroad Administration<br />1200 New Jersey Avenue, SE<br />Washington, DC 20590",
                    Link        = null,
                    Target      = null,
                    CreatedBy   = currentUser.AdName,
                    Created     = NOW,
                    ModifiedBy  = currentUser.AdName,
                    Modified    = NOW,
                    IsPublished = true,
                    Index       = 0
                },
                new FooterItem {
                    Section     = s2,
                    Title       = "Facebook",
                    Link        = "http://www.facebook.com/USDOTFRA",
                    Target      = "_blank",
                    CreatedBy   = currentUser.AdName,
                    Created     = NOW,
                    ModifiedBy  = currentUser.AdName,
                    Modified    = NOW,
                    IsPublished = true,
                    Index       = 0
                },
                new FooterItem {
                    Section     = s3,
                    Title       = "Jobs",
                    Link        = "#",
                    Target      = "_self",
                    CreatedBy   = currentUser.AdName,
                    Created     = NOW,
                    ModifiedBy  = currentUser.AdName,
                    Modified    = NOW,
                    IsPublished = true,
                    Index       = 0
                },
                new FooterItem {
                    Section     = s4,
                    Title       = "Adobe Acrobat Reader",
                    Link        = "http://get.adobe.com/reader/",
                    Target      = "_blank",
                    CreatedBy   = currentUser.AdName,
                    Created     = NOW,
                    ModifiedBy  = currentUser.AdName,
                    Modified    = NOW,
                    IsPublished = true,
                    Index       = 0
                },
            };

            items.ForEach(s => context.Set <FooterItem>().Add(s));
            context.SaveChanges();

            #endregion

            foreach (CmsPage page in pages)
            {
                PublishDraft(page, context);
            }

            context.SaveChanges();
        }
コード例 #27
0
ファイル: Page.cs プロジェクト: forki/OwinFramework.Pages
        public virtual void Initialize()
        {
            var data = new PageData(_dependencies, this);

            var elementDependencies = new PageElementDependencies
            {
                DictionaryFactory     = _dependencies.DictionaryFactory,
                DataDependencyFactory = _dependencies.DataDependencyFactory
            };

            if (Layout != null)
            {
                var regionElements = new List <Tuple <string, IRegion, IElement> >();
                foreach (var regionName in Layout.GetRegionNames())
                {
                    var region  = Layout.GetRegion(regionName);
                    var element = _regions != null && _regions.ContainsKey(regionName)
                        ? _regions[regionName]
                        : Layout.GetElement(regionName);
                    regionElements.Add(new Tuple <string, IRegion, IElement>(regionName, region, element));
                }
                _layout = new PageLayout(elementDependencies, null, Layout, regionElements, data);
            }

            if (_components == null)
            {
                _pageComponents = new PageComponent[0];
            }
            else
            {
                _pageComponents = _components.Select(c => new PageComponent(elementDependencies, null, c, data)).ToArray();

                foreach (var component in _components)
                {
                    data.BeginAddElement(component, null);
                    data.EndAddElement(component);
                }
            }

            _dataContextBuilder = data.RootDataContextBuilder;
            _dataContextBuilder.ResolveSupplies();

            _referencedModules = new List <IModule>();
            var styles    = _dependencies.CssWriterFactory.Create();
            var functions = _dependencies.JavascriptWriterFactory.Create();

#if TRACE
            System.Diagnostics.Trace.WriteLine("Page '" + Name + "' asset deployment");
#endif
            foreach (var element in data.Elements)
            {
                var name = string.IsNullOrEmpty(element.Element.Name)
                    ? element.Element.GetType().Name
                    : element.Element.Name;

                string deployment;
                switch (element.AssetDeployment)
                {
                case AssetDeployment.PerWebsite:
                    deployment = "website assets";
                    _dependencies.AssetManager.AddWebsiteAssets(element.Element);
                    break;

                case AssetDeployment.PerModule:
                    deployment = element.Module.Name + " module";
                    _dependencies.AssetManager.AddModuleAssets(element.Element, element.Module);
                    if (_referencedModules.All(m => m.Name != element.Module.Name))
                    {
                        _referencedModules.Add(element.Module);
                    }
                    break;

                case AssetDeployment.PerPage:
                    deployment = "page assets";
                    _dependencies.AssetManager.AddPageAssets(element.Element, this);
                    break;

                case AssetDeployment.InPage:
                    deployment = "page head";
                    element.Element.WriteStaticCss(styles);
                    element.Element.WriteStaticJavascript(functions);
                    break;

                default:
                    deployment = element.AssetDeployment.ToString().ToLower();
                    break;
                }

#if TRACE
                System.Diagnostics.Trace.WriteLine("   " + name + " deployed to " + deployment);
#endif
            }

            _inPageCssLines    = styles.ToLines();
            _inPageScriptLines = functions.ToLines();
        }
コード例 #28
0
ファイル: Report.cs プロジェクト: saveenr/saveenr
 public Report()
 {
     this.PageLayout = new PageLayout();
     this.DocumentProperties = new DocumentProperties();
 }
コード例 #29
0
 public PublishingPageDesignFieldValue(PageLayout layout) : base(3)
 {
     base[0] = layout.UniqueId.ToString();
     base[1] = layout.Title;
     base[2] = layout.Url;
 }
コード例 #30
0
 public void Transform(PageLayout layout)
 {
     throw new NotImplementedException();
 }
コード例 #31
0
		/// <summary>
		///		Changes the layout of the user control to match the preferred
		///		format
		/// </summary>
		/// <param name="layout">The layout to change to</param>
		protected virtual void UpdateLayout(PageLayout layout)
		{
			if( layout == PageLayout.None )
				return;

			switch(layout)
			{
				case PageLayout.ExteriorPage:
					BackColor = Color.White;
					Description.Visible = true;
					break;
				case PageLayout.InteriorPage:
					BackColor = SystemColors.Control;
					Description.Visible = false;
					break;
			}
		}
コード例 #32
0
        public void RaisePostBackEvent(string eventArgument)
        {
            SPContext.Current.Web.AllowUnsafeUpdates = true;
            Guid uniqueId = Guid.Empty;

            try
            {
                string[] eventArg = eventArgument.Split(new string[1] {
                    "#;"
                }, StringSplitOptions.None);

                SPWeb      rootWeb = SPContext.Current.Site.RootWeb;
                SPListItem item    = SPContext.Current.ListItem;

                if (!string.IsNullOrEmpty(eventArg[1]))
                {
                    PageLayout layout = servicePageLayouts.GetPageLayout(new Guid(eventArg[1]));

                    if (item != null && layout != null)
                    {
                        SPFile currentFile = item.File;
                        bool   checkout    = false;
                        if (currentFile != null && currentFile.Exists)
                        {
                            if (currentFile.CheckOutType == SPFile.SPCheckOutType.None && currentFile.RequiresCheckout)
                            {
                                currentFile.CheckOut();
                                checkout = true;
                            }
                        }

                        SPUser            suser     = null;
                        SPListItemVersion spversion = null;

                        SPListItemVersionCollection versions = item.Versions;
                        if (versions.Count > 0)
                        {
                            foreach (SPListItemVersion version in versions)
                            {
                                if (version.IsCurrentVersion)
                                {
                                    suser     = version.CreatedBy.User;
                                    spversion = version;
                                    item      = version.ListItem;
                                    break;
                                }
                            }
                        }

                        /*
                         * else
                         * {
                         *  listItem = file.ListItemAllFields;
                         * }
                         */

                        using (SPSite site = new SPSite(SPContext.Current.Web.Url, suser.UserToken))
                        {
                            SPWeb      spweb  = site.OpenWeb();
                            SPFile     spfile = spweb.GetFile(currentFile.UniqueId);
                            SPListItem spitem = spfile.Item.Versions.GetVersionFromLabel(spversion.VersionLabel).ListItem;


                            PublishingPageDesignFieldValue value = spitem[BuildFieldId.PublishingPageDesign] as PublishingPageDesignFieldValue;
                            value.Id    = layout.UniqueId;
                            value.Title = layout.Title;
                            value.Url   = layout.Url;

                            spitem[BuildFieldId.PublishingPageDesign] = value;

                            try
                            {
                                spitem.Fields[BuildFieldId.PublishingPageDesign].Update(true);
                            }
                            catch (Exception)
                            {
                            }

                            try
                            {
                                spitem.Update();
                            }
                            catch (Exception)
                            {
                            }

                            try
                            {
                                spitem.SystemUpdate(false);
                            }
                            catch (Exception)
                            {
                            }

                            try
                            {
                                spfile.Update();
                            }
                            catch (Exception)
                            {
                            }
                        }

                        uniqueId = layout.UniqueId;

                        //currentFile.Update();

                        if (checkout)
                        {
                            currentFile.CheckIn("Layout Changed", SPCheckinType.OverwriteCheckIn);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
                //result = ex;
            }
            SPContext.Current.Web.AllowUnsafeUpdates = false;

            url = base.parentStateControl.ContextUri;


            if (IsEditMode(this.Page))
            {
                url = WebPageStateControl.AddQueryStringParameter(WebPageStateControl.AddQueryStringParameter(url, "ControlMode", "Edit"), "DisplayMode", "Design");
            }

            url = WebPageStateControl.AddQueryStringParameter(url, "PageLayout", DateTime.Now.Ticks.ToString());

            base.parentStateControl.EnsureItemSavedIfEditMode(true);
            this.RefreshPageState();
            this.OnPageStateChanged();

            //base.ClearChildControlState();


            HtmlMeta refresh = new HtmlMeta();

            refresh.HttpEquiv = "refresh";
            refresh.Content   = "0;URL=" + url + "";
            this.Page.Header.Controls.Add(refresh);
            this.Page.Header.Controls.Add(new LiteralControl(Environment.NewLine));

            /*
             * if (IsEditMode(this.Page))
             * {
             *  SPUtility.Redirect("~/" + url, SPRedirectFlags.Trusted,HttpContext.Current);
             * }
             * else
             * {
             *  SPUtility.Redirect("~/" + base.parentStateControl.ContextUri, SPRedirectFlags.Trusted, HttpContext.Current);
             * }
             */
        }
コード例 #33
0
        /// <summary>
        /// Translates the given zone value and page layout to a row number
        /// </summary>
        /// <param name="zoneId">Web part zone id</param>
        /// <param name="layout">Layout of the web part page</param>
        /// <returns>Row value</returns>
        internal int GetRow(string zoneId, PageLayout layout)
        {
            switch (layout)
            {
            case PageLayout.WebPart_HeaderFooterThreeColumns:
            {
                if (zoneId.Equals("Header", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(1);
                }
                else if (zoneId.Equals("LeftColumn", StringComparison.InvariantCultureIgnoreCase) ||
                         zoneId.Equals("MiddleColumn", StringComparison.InvariantCultureIgnoreCase) ||
                         zoneId.Equals("RightColumn", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(2);
                }
                else if (zoneId.Equals("Footer", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(3);
                }
                break;
            }

            case PageLayout.WebPart_FullPageVertical:
            case PageLayout.WebPart_2010_TwoColumnsLeft:
            {
                return(1);
            }

            case PageLayout.WebPart_HeaderLeftColumnBody:
            {
                if (zoneId.Equals("Header", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(1);
                }
                else if (zoneId.Equals("LeftColumn", StringComparison.InvariantCultureIgnoreCase) ||
                         zoneId.Equals("Body", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(2);
                }
                break;
            }

            case PageLayout.WebPart_HeaderRightColumnBody:
            {
                if (zoneId.Equals("Header", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(1);
                }
                else if (zoneId.Equals("RightColumn", StringComparison.InvariantCultureIgnoreCase) ||
                         zoneId.Equals("Body", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(2);
                }
                break;
            }

            case PageLayout.WebPart_HeaderFooter2Columns4Rows:
            {
                if (zoneId.Equals("Header", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(1);
                }
                else if (zoneId.Equals("LeftColumn", StringComparison.InvariantCultureIgnoreCase) ||
                         zoneId.Equals("Row1", StringComparison.InvariantCultureIgnoreCase) ||
                         zoneId.Equals("RightColumn", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(2);
                }
                else if (zoneId.Equals("Row2", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(3);
                }
                else if (zoneId.Equals("Row3", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(4);
                }
                else if (zoneId.Equals("Row4", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(5);
                }
                else if (zoneId.Equals("Footer", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(6);
                }
                break;
            }

            case PageLayout.WebPart_HeaderFooter4ColumnsTopRow:
            {
                if (zoneId.Equals("Header", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(1);
                }
                else if (zoneId.Equals("LeftColumn", StringComparison.InvariantCultureIgnoreCase) ||
                         zoneId.Equals("TopRow", StringComparison.InvariantCultureIgnoreCase) ||
                         zoneId.Equals("RightColumn", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(2);
                }
                else if (zoneId.Equals("CenterLeftColumn", StringComparison.InvariantCultureIgnoreCase) ||
                         zoneId.Equals("CenterRightColumn", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(3);
                }
                else if (zoneId.Equals("Footer", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(4);
                }
                break;
            }

            case PageLayout.WebPart_LeftColumnHeaderFooterTopRow3Columns:
            {
                if (zoneId.Equals("Header", StringComparison.InvariantCultureIgnoreCase) ||
                    zoneId.Equals("LeftColumn", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(1);
                }
                else if (zoneId.Equals("TopRow", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(2);
                }
                else if (zoneId.Equals("CenterLeftColumn", StringComparison.InvariantCultureIgnoreCase) ||
                         zoneId.Equals("CenterColumn", StringComparison.InvariantCultureIgnoreCase) ||
                         zoneId.Equals("CenterRightColumn", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(3);
                }
                else if (zoneId.Equals("Footer", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(4);
                }
                break;
            }

            case PageLayout.WebPart_RightColumnHeaderFooterTopRow3Columns:
            {
                if (zoneId.Equals("Header", StringComparison.InvariantCultureIgnoreCase) ||
                    zoneId.Equals("RightColumn", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(1);
                }
                else if (zoneId.Equals("TopRow", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(2);
                }
                else if (zoneId.Equals("CenterLeftColumn", StringComparison.InvariantCultureIgnoreCase) ||
                         zoneId.Equals("CenterColumn", StringComparison.InvariantCultureIgnoreCase) ||
                         zoneId.Equals("CenterRightColumn", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(3);
                }
                else if (zoneId.Equals("Footer", StringComparison.InvariantCultureIgnoreCase))
                {
                    return(4);
                }
                break;
            }

            case PageLayout.WebPart_Custom:
            {
                return(1);
            }

            default:
                return(1);
            }

            return(1);
        }
コード例 #34
0
        /// <summary>
        /// Analyses a publishing page for scanner usage
        /// </summary>
        /// <returns>Information about the analyzed publishing page</returns>
        public Tuple <PageLayout, List <WebPartEntity> > GetWebPartsForScanner()
        {
            //TODO: Upgrade this new code for SharePoint 2010 support

            List <WebPartEntity> webparts = new List <WebPartEntity>();

            //Load the page
            var publishingPageUrl = page[Constants.FileRefField].ToString();
            var publishingPage    = cc.Web.GetFileByServerRelativeUrl(publishingPageUrl);

            // Load relevant model data for the used page layout in case not already provided - safetynet for calls from modernization scanner
            string usedPageLayout = System.IO.Path.GetFileNameWithoutExtension(page.PageLayoutFile());

            // Map layout
            PageLayout layout = PageLayout.PublishingPage_AutoDetect;

            // Load web parts put in web part zones on the publishing page
            // Note: Web parts placed outside of a web part zone using SPD are not picked up by the web part manager.
            var limitedWPManager = publishingPage.GetLimitedWebPartManager(PersonalizationScope.Shared);

            cc.Load(limitedWPManager);

            IEnumerable <WebPartDefinition> webPartsViaManager = cc.LoadQuery(limitedWPManager.WebParts.IncludeWithDefaultProperties(wp => wp.Id, wp => wp.ZoneId, wp => wp.WebPart.ExportMode, wp => wp.WebPart.Title, wp => wp.WebPart.ZoneIndex, wp => wp.WebPart.IsClosed, wp => wp.WebPart.Hidden, wp => wp.WebPart.Properties));

            cc.ExecuteQueryRetry();

            if (webPartsViaManager.Any())
            {
                List <WebPartPlaceHolder> webPartsToRetrieve = new List <WebPartPlaceHolder>();

                foreach (var foundWebPart in webPartsViaManager)
                {
                    webPartsToRetrieve.Add(new WebPartPlaceHolder()
                    {
                        WebPartDefinition = foundWebPart,
                        WebPartXml        = null,
                        WebPartType       = "",
                    });
                }

                bool isDirty = false;
                foreach (var foundWebPart in webPartsToRetrieve)
                {
                    if (foundWebPart.WebPartDefinition.WebPart.ExportMode == WebPartExportMode.All)
                    {
                        foundWebPart.WebPartXml = limitedWPManager.ExportWebPart(foundWebPart.WebPartDefinition.Id);
                        isDirty = true;
                    }
                }
                if (isDirty)
                {
                    cc.ExecuteQueryRetry();
                }

                foreach (var foundWebPart in webPartsToRetrieve.OrderBy(p => p.WebPartDefinition.WebPart.ZoneIndex))
                {
                    if (foundWebPart.WebPartDefinition.WebPart.ExportMode != WebPartExportMode.All)
                    {
                        // Use different approach to determine type as we can't export the web part XML without indroducing a change
                        foundWebPart.WebPartType = GetTypeFromProperties(foundWebPart.WebPartDefinition.WebPart.Properties.FieldValues);
                    }
                    else
                    {
                        foundWebPart.WebPartType = GetType(foundWebPart.WebPartXml.Value);
                    }

                    webparts.Add(new WebPartEntity()
                    {
                        Title           = foundWebPart.WebPartDefinition.WebPart.Title,
                        Type            = foundWebPart.WebPartType,
                        Id              = foundWebPart.WebPartDefinition.Id,
                        ServerControlId = foundWebPart.WebPartDefinition.Id.ToString(),
                        ZoneId          = foundWebPart.WebPartDefinition.ZoneId,
                        ZoneIndex       = (uint)foundWebPart.WebPartDefinition.WebPart.ZoneIndex,
                        IsClosed        = foundWebPart.WebPartDefinition.WebPart.IsClosed,
                        Hidden          = foundWebPart.WebPartDefinition.WebPart.Hidden,
                        Properties      = Properties(foundWebPart.WebPartDefinition.WebPart.Properties.FieldValues, foundWebPart.WebPartType, foundWebPart.WebPartXml == null ? "" : foundWebPart.WebPartXml.Value),
                    });
                }
            }

            return(new Tuple <PageLayout, List <WebPartEntity> >(layout, webparts));
        }
コード例 #35
0
        public GarageDoorStatusLayout()
        {
            LoadIconMethod  = LoadIcon;
            AdjustUriMethod = (uri) => uri;

            GaragePage                     = new FlowPanel();
            GaragePage.Orientation         = FlowPanelOrientation.Vertical;
            GaragePage.Rect                = new PageRect(0, 0, 248, 128);
            GaragePage.ElementId           = 1;
            GaragePage.Margins             = new Margins(0, 0, 0, 0);
            GaragePage.HorizontalAlignment = HorizontalAlignment.Left;
            GaragePage.VerticalAlignment   = VerticalAlignment.Top;
            GaragePage.Visible             = true;

            Title                     = new TextBlock();
            Title.Font                = TextBlockFont.Small;
            Title.Baseline            = 0;
            Title.BaselineAlignment   = TextBlockBaselineAlignment.Automatic;
            Title.AutoWidth           = true;
            Title.ColorSource         = ElementColorSource.Custom;
            Title.Color               = new BandColor(255, 255, 255);
            Title.Rect                = new PageRect(0, 0, 32, 32);
            Title.ElementId           = 2;
            Title.Margins             = new Margins(0, 0, 0, 0);
            Title.HorizontalAlignment = HorizontalAlignment.Left;
            Title.VerticalAlignment   = VerticalAlignment.Top;
            Title.Visible             = true;

            GaragePage.Elements.Add(Title);

            OpenTime                     = new TextBlock();
            OpenTime.Font                = TextBlockFont.Small;
            OpenTime.Baseline            = 0;
            OpenTime.BaselineAlignment   = TextBlockBaselineAlignment.Automatic;
            OpenTime.AutoWidth           = true;
            OpenTime.ColorSource         = ElementColorSource.Custom;
            OpenTime.Color               = new BandColor(255, 255, 255);
            OpenTime.Rect                = new PageRect(0, 0, 32, 32);
            OpenTime.ElementId           = 3;
            OpenTime.Margins             = new Margins(0, 0, 0, 0);
            OpenTime.HorizontalAlignment = HorizontalAlignment.Left;
            OpenTime.VerticalAlignment   = VerticalAlignment.Top;
            OpenTime.Visible             = true;

            GaragePage.Elements.Add(OpenTime);

            CloseTime                     = new TextBlock();
            CloseTime.Font                = TextBlockFont.Small;
            CloseTime.Baseline            = 0;
            CloseTime.BaselineAlignment   = TextBlockBaselineAlignment.Automatic;
            CloseTime.AutoWidth           = true;
            CloseTime.ColorSource         = ElementColorSource.Custom;
            CloseTime.Color               = new BandColor(255, 255, 255);
            CloseTime.Rect                = new PageRect(0, 0, 32, 32);
            CloseTime.ElementId           = 4;
            CloseTime.Margins             = new Margins(0, 0, 0, 0);
            CloseTime.HorizontalAlignment = HorizontalAlignment.Left;
            CloseTime.VerticalAlignment   = VerticalAlignment.Top;
            CloseTime.Visible             = true;

            GaragePage.Elements.Add(CloseTime);
            pageLayout = new PageLayout(GaragePage);

            PageElementData[] pageElementDataArray = new PageElementData[3];
            pageElementDataArray[0] = TitleData;
            pageElementDataArray[1] = OpenTimeData;
            pageElementDataArray[2] = CloseTimeData;

            pageLayoutData = new PageLayoutData(pageElementDataArray);
        }
コード例 #36
0
        async partial void AddButtonPageClick(UIButton sender)
        {
            if (client != null && client.IsConnected)
            {
                Output("Creating tile...");

                // remove an old tile
                try {
                    var tiles = await client.TileManager.GetTilesTaskAsync();

                    if (tiles.Any(x => x.TileId.AsString() == tileId.AsString()))
                    {
                        // a tile exists, so remove it
                        await client.TileManager.RemoveTileTaskAsync(tileId);

                        Output("Removed tile!");
                    }
                } catch (BandException ex) {
                    Output("Error: " + ex.Message);
                }

                // create the tile
                NSError operationError;
                var     tileName  = "iOS Sample";
                var     tileIcon  = BandIcon.FromUIImage(UIImage.FromBundle("tile.png"), out operationError);
                var     smallIcon = BandIcon.FromUIImage(UIImage.FromBundle("badge.png"), out operationError);
                var     tile      = BandTile.Create(tileId, tileName, tileIcon, smallIcon, out operationError);
                tile.BadgingEnabled = true;

                // create the button page
                var textBlock = new TextBlock(PageRect.Create(0, 0, 200, 40), TextBlockFont.Small);
                textBlock.ElementId           = 10;
                textBlock.Baseline            = 25;
                textBlock.HorizontalAlignment = HorizontalAlignment.Center;
                textBlock.BaselineAlignment   = TextBlockBaselineAlignment.Relative;
                textBlock.AutoWidth           = false;
                textBlock.Color   = BandColor.FromUIColor(UIColor.Red, out operationError);
                textBlock.Margins = Margins.Create(5, 2, 5, 2);

                var button = new TextButton(PageRect.Create(0, 0, 200, 40));
                button.ElementId           = 11;
                button.HorizontalAlignment = HorizontalAlignment.Center;
                button.PressedColor        = BandColor.FromUIColor(UIColor.Purple, out operationError);
                button.Margins             = Margins.Create(5, 2, 5, 2);

                var flowPanel = new FlowPanel(PageRect.Create(15, 0, 260, 105));
                flowPanel.AddElement(textBlock);
                flowPanel.AddElement(button);

                var pageLayout = new PageLayout();
                pageLayout.Root = flowPanel;
                tile.PageLayouts.Add(pageLayout);

                // add the tile to the band
                try {
                    Output("Adding tile...");
                    await client.TileManager.AddTileTaskAsync(tile);
                } catch (BandException ex) {
                    Output("Error: " + ex.Message);
                }

                // set the page data
                try {
                    Output("Creating page data...");
                    var pageValues = new PageElementData [] {
                        TextBlockData.Create(textBlock.ElementId, "TextButton sample", out operationError),
                        TextButtonData.Create(button.ElementId, "Press Me", out operationError)
                    };
                    var page = PageData.Create(barcodePageId, 0, pageValues);

                    await client.TileManager.SetPagesTaskAsync(new[] { page }, tileId);

                    Output("Completed custom page!");
                } catch (BandException ex) {
                    Output("Error: " + ex.Message);
                }
            }
            else
            {
                Output("Band is not connected. Please wait....");
            }
        }
コード例 #37
0
 public void ApplyLayout(PageLayout layout)
 {
     throw new NotImplementedException();
 }
コード例 #38
0
ファイル: DocxDocument.cs プロジェクト: moayyaed/ReportDotNet
 public void SetDefaultPageLayout(PageLayout pageLayout)
 {
     defaultPageLayout = pageLayout;
 }
コード例 #39
0
		async partial void AddButtonPageClick (UIButton sender)
		{
			if (client != null && client.IsConnected) {
				Output ("Creating tile...");

				// remove an old tile
				try {
					var tiles = await client.TileManager.GetTilesTaskAsync ();
					if (tiles.Any (x => x.TileId.AsString () == tileId.AsString ())) {
						// a tile exists, so remove it
						await client.TileManager.RemoveTileTaskAsync (tileId);
						Output ("Removed tile!");
					}
				} catch (BandException ex) {
					Output ("Error: " + ex.Message);
				}

				// create the tile
				NSError operationError;
				var tileName = "iOS Sample";
				var tileIcon = BandIcon.FromUIImage (UIImage.FromBundle ("tile.png"), out operationError);
				var smallIcon = BandIcon.FromUIImage (UIImage.FromBundle ("badge.png"), out operationError);
				var tile = BandTile.Create (tileId, tileName, tileIcon, smallIcon, out operationError);
				tile.BadgingEnabled = true;

				// create the button page
				var textBlock = new TextBlock (PageRect.Create (0, 0, 200, 40), TextBlockFont.Small);
				textBlock.ElementId = 10;
				textBlock.Baseline = 25;
				textBlock.HorizontalAlignment = HorizontalAlignment.Center;
				textBlock.BaselineAlignment = TextBlockBaselineAlignment.Relative;
				textBlock.AutoWidth = false;
				textBlock.Color = BandColor.FromUIColor (UIColor.Red, out operationError);
				textBlock.Margins = Margins.Create (5, 2, 5, 2);

				var button = new TextButton (PageRect.Create (0, 0, 200, 40));
				button.ElementId = 11;
				button.HorizontalAlignment = HorizontalAlignment.Center;
				button.PressedColor = BandColor.FromUIColor (UIColor.Purple, out operationError);
				button.Margins = Margins.Create (5, 2, 5, 2);

				var flowPanel = new FlowPanel (PageRect.Create (15, 0, 260, 105));
				flowPanel.AddElement (textBlock);
				flowPanel.AddElement (button);

				var pageLayout = new PageLayout ();
				pageLayout.Root = flowPanel;
				tile.PageLayouts.Add (pageLayout);

				// add the tile to the band
				try {
					Output ("Adding tile...");
					await client.TileManager.AddTileTaskAsync (tile);
				} catch (BandException ex) {
					Output ("Error: " + ex.Message);
				}

				// set the page data
				try {
					Output ("Creating page data...");
					var pageValues = new PageElementData [] {
						TextBlockData.Create (textBlock.ElementId, "TextButton sample", out operationError),
						TextButtonData.Create (button.ElementId, "Press Me", out operationError)
					};
					var page = PageData.Create (barcodePageId, 0, pageValues);

					await client.TileManager.SetPagesTaskAsync (new[]{ page }, tileId);
					Output ("Completed custom page!");
				} catch (BandException ex) {
					Output ("Error: " + ex.Message);
				}
			} else {
				Output ("Band is not connected. Please wait....");
			}
		}
コード例 #40
0
        private void DefaultPageLayoutProcess(SPWebEventProperties properties)
        {
            PageLayout _pageLayout;

            try
            {
                using (SPSite site = new SPSite(properties.SiteId))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        PublishingSite pubSiteCollection = new PublishingSite(site);
                        PublishingWeb  publishingWeb     = PublishingWeb.GetPublishingWeb(properties.Web);

                        //check if pagelayout to be defaulted already exists in AvailablePageLayouts
                        _pageLayout = (from _pl in publishingWeb.GetAvailablePageLayouts()
                                       where _pl.Name == defaultPageLayout
                                       select _pl).FirstOrDefault();

                        //if exists
                        if (_pageLayout != null)
                        {
                            publishingWeb.SetDefaultPageLayout(_pageLayout, true);
                            publishingWeb.Update();
                        }
                        else  //if does not exist
                        {
                            //get all AvailablePageLayouts
                            PageLayout[] _allpageLayout = publishingWeb.GetAvailablePageLayouts();
                            PageLayout[] plarray        = new PageLayout[_allpageLayout.Length + 1];
                            int          ipl            = -1;
                            //transfer existing pagelayouts in AvailablePageLayouts to PageLayout[]
                            foreach (PageLayout _itempl in _allpageLayout)
                            {
                                ipl++;
                                plarray[ipl] = _itempl;
                            }

                            //PageLayout to be defaulted to
                            _pageLayout = pubSiteCollection.PageLayouts["/_catalogs/masterpage/" + defaultPageLayout];
                            ipl++;
                            //add to the PageLayout array
                            plarray[ipl] = _pageLayout;
                            //reset AvailablePageLayouts
                            publishingWeb.SetAvailablePageLayouts(plarray, true);
                            publishingWeb.Update();
                            //set DefaultPageLayout
                            publishingWeb.SetDefaultPageLayout(_pageLayout, true);

                            publishingWeb.Update();
                            web.Update();
                        }

                        //Swap the page layout of the default.aspx page
                        SwapPageLayout(publishingWeb, _pageLayout, web.Site.RootWeb.ContentTypes[_pageLayout.AssociatedContentType.Id]);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog("WebProvisioning.cs - DefaultPageLayoutProcess: " + ex.Message + " " + ex.StackTrace);
            }
        }
コード例 #41
0
        private async void OnAddButtonTileClick(object sender, EventArgs e)
        {
            try
            {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.InScaled = false;
                BandIcon tileIcon = BandIcon.ToBandIcon(BitmapFactory.DecodeResource(Resources, Resource.Raw.tile, options));

                BandIcon badgeIcon = BandIcon.ToBandIcon(BitmapFactory.DecodeResource(Resources, Resource.Raw.badge, options));

                FilledButton button = new FilledButton(0, 5, 210, 45);
                button.BackgroundColor = Color.Red;
                button.Margins = new Margins(0, 5, 0, 0);
                button.ElementId = 12;

                TextButton button2 = new TextButton(0, 0, 210, 45);
                button2.PressedColor = Color.Blue;
                button2.Margins = new Margins(0, 5, 0, 0);
                button2.ElementId = 21;

                FlowPanel flowPanel = new FlowPanel(15, 0, 260, 105, FlowPanelOrientation.Vertical);
                flowPanel.AddElements(button);
                flowPanel.AddElements(button2);

                PageLayout pageLayout = new PageLayout(flowPanel);

                BandTile.Builder builder = new BandTile.Builder(Java.Util.UUID.RandomUUID(), mEditTileName.Text, tileIcon);
                if (mCheckboxBadging.Checked)
                {
                    builder.SetTileSmallIcon(badgeIcon);
                }
                if (mCheckboxCustomTheme.Checked)
                {
                    builder.SetTheme(mThemeView.Theme);
                }
                builder.SetPageLayouts(pageLayout);
                BandTile tile = builder.Build();

                try
                {
                    var result = await Model.Instance.Client.TileManager.AddTileTaskAsync(Activity, tile);
                    if (result)
                    {
                        Toast.MakeText(Activity, "Tile added", ToastLength.Short).Show();
                    }
                    else
                    {
                        Toast.MakeText(Activity, "Unable to add tile", ToastLength.Short).Show();
                    }
                }
                catch (Exception ex)
                {
                    Util.ShowExceptionAlert(Activity, "Add tile", ex);
                }

                PageData pageData = new PageData(Java.Util.UUID.RandomUUID(), 0);
                pageData.Update(new FilledButtonData(12, Color.Yellow));
                pageData.Update(new TextButtonData(21, "Text Button"));
                await Model.Instance.Client.TileManager.SetPagesTaskAsync(tile.TileId, pageData);

                Toast.MakeText(Activity, "Page updated", ToastLength.Short).Show();

                // Refresh our tile list and count
                await RefreshData();
                RefreshControls();
            }
            catch (Exception ex)
            {
                Util.ShowExceptionAlert(Activity, "Add tile", ex);
            }
        }
コード例 #42
0
ファイル: Tile.cs プロジェクト: Theojim92/SCP-with-O365
 private void Message()
 {
     TextBlock nameTextBlock = new TextBlock() { Color = Colors.Blue.ToBandColor(), ElementId = 1, Rect = new PageRect(0, 0, 200, 30) };
     WrappedTextBlock questionBlock = new WrappedTextBlock() { ElementId = 2, Rect = new PageRect(0, 0, 200, 60) };
     ScrollFlowPanel panelRate = new ScrollFlowPanel(nameTextBlock, questionBlock)
     {
         Orientation = FlowPanelOrientation.Vertical,
         Rect = new PageRect(0, 0, 200, 102),
         ScrollBarColorSource = ElementColorSource.BandBase
     };
     PageLayout pageLayout = new PageLayout(panelRate);
     PageLayouts.Add(pageLayout);
 }
コード例 #43
0
 public PageTypeLayoutContext SetLayout(PageLayout.LayoutDisplayProperties layout)
 {
     Page.Layout.DisplayProperties = layout;
     return this;
 }
コード例 #44
0
ファイル: MainPage.xaml.cs プロジェクト: ctrexler/BandOfLove
        async private void Click_AddTile(object sender, RoutedEventArgs e)
        {
            AppBarButton_Pin.IsEnabled = false;
            try
            {
                // determine the number of available tile slots on the Band
                int tileCapacity = await bandClient.TileManager.GetRemainingTileCapacityAsync();
                if (tileCapacity < 1)
                {
                    return;
                }
            }
            catch (BandException ex)
            {
                // handle a Band connection exception }
            }
            
            // Create the small and tile icons from writable bitmaps.
            // Small icons are 24x24 pixels.
            BandIcon smallIcon;
            StorageFile imageFile_small = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Band_SmallIcon.png"));
            using (IRandomAccessStream fileStream = await imageFile_small.OpenAsync(FileAccessMode.Read))
            {
                WriteableBitmap bitmap = new WriteableBitmap(24, 24);
                await bitmap.SetSourceAsync(fileStream);
                smallIcon = bitmap.ToBandIcon();
            }

            // Tile icons are 46x46 pixels for Microsoft Band 1, and 48x48 pixels
            // for Microsoft Band 2.
            BandIcon tileIcon;
            StorageFile imageFile_large = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Band_LargeIcon.png"));
            using (IRandomAccessStream fileStream = await imageFile_large.OpenAsync(FileAccessMode.Read))
            {
                WriteableBitmap bitmap = new WriteableBitmap(48, 48);
                await bitmap.SetSourceAsync(fileStream);
                tileIcon = bitmap.ToBandIcon();
            }

            // create a new Guid for the tile
            Guid newGuid = Guid.NewGuid();
            var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            localSettings.Values["BOLGuid"] = tileGuid = newGuid;
            // create a new tile with a new Guid
            tile = new BandTile(tileGuid)
            {
                // enable badging (the count of unread messages)
                IsBadgingEnabled = true,
                // set the name
                Name = "Band of Love",
                // set the icons
                SmallIcon = smallIcon,
                TileIcon = tileIcon
            };

            // Create a scrollable vertical panel that will hold 2 text messages.
            ScrollFlowPanel panel = new ScrollFlowPanel
            {
                Rect = new PageRect(0, 0, 245, 102),
                Orientation = FlowPanelOrientation.Vertical,
                ScrollBarColorSource = ElementColorSource.BandBase
            };

            // add the text block to contain the first message
            panel.Elements.Add(
                new WrappedTextBlock
                {
                    ElementId = (short)TileMessagesLayoutElementId.Message1,
                    Rect = new PageRect(0, 0, 245, 102),
                    // left, top, right, bottom margins
                    Margins = new Margins(15, 0, 15, 0),
                    Color = new BandColor(0xFF, 0xFF, 0xFF),
                    Font = WrappedTextBlockFont.Small
                }
            );

            // add the text block to contain the second message
            panel.Elements.Add(
                new WrappedTextBlock
                {
                    ElementId = (short)TileMessagesLayoutElementId.Message2,
                    Rect = new PageRect(0, 0, 245, 102),
                    // left, top, right, bottom margins
                    Margins = new Margins(15, 0, 15, 0),
                    Color = new BandColor(0xFF, 0xFF, 0xFF),
                    Font = WrappedTextBlockFont.Small
                }
            );
            // create the page layout
            PageLayout layout = new PageLayout(panel);

            try
            {     // add the layout to the tile
                tile.PageLayouts.Add(layout);
            }
            catch (BandException ex)
            {
                // handle an error adding the layout
            }

            try
            {
                // add the tile to the Band
                if (await bandClient.TileManager.AddTileAsync(tile))
                {
                    // tile was successfully added
                    AppBarButton_Pin.Visibility = Visibility.Collapsed;
                    AppBarButton_UnPin.Visibility = Visibility.Visible;
                    AppBarButton_UnPin.IsEnabled = true;

                    // can proceed to set tile content with SetPagesAsync
                }
                else
                {
                    // tile failed to be added, handle error
                }
            }
            catch (BandException ex)
            {
                // handle a Band connection exception }
            }

            // create a new Guid for the messages page
            Guid messagesPageGuid = Guid.NewGuid();
            // create the object that contains the page content to be set
            PageData pageContent = new PageData(
                messagesPageGuid,
                // specify which layout to use for this page
                (int)TileLayoutIndex.MessagesLayout,
                new WrappedTextBlockData(
                    (Int16)TileMessagesLayoutElementId.Message1,
                    "This is the text of the first message"
                ),
                new WrappedTextBlockData(
                    (Int16)TileMessagesLayoutElementId.Message2,
                    "This is the text of the second message"
                )
            );
            try
            {
                // set the page content on the Band
                if (await bandClient.TileManager.SetPagesAsync(tileGuid, pageContent))
                {
                    // page content successfully set on Band
                }
                else
                {
                    // unable to set content to the Band
                }
            }
            catch (BandException ex)
            {
                // handle a Band connection exception
            }
        }
コード例 #45
0
        /// <summary>
        /// Builds the layout (sections) of the modern page
        /// </summary>
        /// <param name="pageLayout">The publishing page layout mapping to the current page</param>
        /// <param name="layout">Information about the source page</param>
        /// <param name="webPartsToProcess">Web Parts to process</param>
        public List <Section> Transform(PublishingMapping.PageLayout pageLayout, PageLayout layout, List <WebPartEntity> webPartsToProcess)
        {
            List <Column> GetColumns(int size)
            {
                return((from n in Enumerable.Range(0, size) select new Column()).ToList());
            }

            var result = new List <Section>();

            bool includeVerticalColumn  = false;
            int  verticalColumnEmphasis = 0;

            if (layout == Model.PageLayout.PublishingPage_AutoDetectWithVerticalColumn)
            {
                includeVerticalColumn  = true;
                verticalColumnEmphasis = GetVerticalColumnBackgroundEmphasis(pageLayout);
            }

            // Should not occur, but to be on the safe side...
            if (webPartsToProcess.Count == 0)
            {
                result.Add(
                    new Section
                {
                    CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.OneColumn,
                    Columns        = GetColumns(1),
                    ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, 1),
                });

                return(result);
            }

            var firstRow = webPartsToProcess.OrderBy(p => p.Row).First().Row;
            var lastRow  = webPartsToProcess.OrderBy(p => p.Row).Last().Row;

            // Loop over the possible rows...will take in account possible row gaps
            // Each row means a new section
            int sectionOrder = 1;

            for (int rowIterator = firstRow; rowIterator <= lastRow; rowIterator++)
            {
                var webpartsInRow = webPartsToProcess.Where(p => p.Row == rowIterator);
                if (webpartsInRow.Any())
                {
                    // Determine max column number
                    int maxColumns = 1;

                    foreach (var wpInRow in webpartsInRow)
                    {
                        if (wpInRow.Column > maxColumns)
                        {
                            maxColumns = wpInRow.Column;
                        }
                    }

                    // Deduct the vertical column
                    if (includeVerticalColumn && rowIterator == firstRow)
                    {
                        maxColumns--;
                    }

                    if (maxColumns > 3)
                    {
                        this.logger.LogError(
                            SharePointTransformationResources.Error_Maximum3ColumnsAllowed);
                        throw new Exception(SharePointTransformationResources.Error_Maximum3ColumnsAllowed);
                    }
                    else
                    {
                        if (maxColumns == 1)
                        {
                            if (includeVerticalColumn && rowIterator == firstRow)
                            {
                                result.Add(
                                    new Section
                                {
                                    CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.OneColumnVerticalSection,
                                    Order          = sectionOrder,
                                    Columns        = GetColumns(1),
                                    ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                    VerticalSectionZoneEmphasis = verticalColumnEmphasis,
                                });
                            }
                            else
                            {
                                result.Add(
                                    new Section
                                {
                                    CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.OneColumn,
                                    Order          = sectionOrder,
                                    Columns        = GetColumns(1),
                                    ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                });
                            }
                        }
                        else if (maxColumns == 2)
                        {
                            // if we've only an image in one of the columns then make that one the 'small' column
                            var imageWebPartsInRow = webpartsInRow.Where(p => p.Type == WebParts.WikiImage);
                            if (imageWebPartsInRow.Any())
                            {
                                Dictionary <int, int> imageWebPartsPerColumn = new Dictionary <int, int>();
                                foreach (var imageWebPart in imageWebPartsInRow.OrderBy(p => p.Column))
                                {
                                    if (imageWebPartsPerColumn.TryGetValue(imageWebPart.Column, out int wpCount))
                                    {
                                        imageWebPartsPerColumn[imageWebPart.Column] = wpCount + 1;
                                    }
                                    else
                                    {
                                        imageWebPartsPerColumn.Add(imageWebPart.Column, 1);
                                    }
                                }

                                var firstImageColumn  = imageWebPartsPerColumn.First();
                                var secondImageColumn = imageWebPartsPerColumn.Last();

                                if (firstImageColumn.Key == secondImageColumn.Key)
                                {
                                    // there was only one column with images
                                    var firstImageColumnOtherWebParts = webpartsInRow.Where(p => p.Column == firstImageColumn.Key && p.Type != WebParts.WikiImage);
                                    if (!firstImageColumnOtherWebParts.Any())
                                    {
                                        // no other web parts in this column
                                        var orderedList = webpartsInRow.OrderBy(p => p.Column).First();

                                        if (orderedList.Column == firstImageColumn.Key)
                                        {
                                            // image left
                                            if (includeVerticalColumn && rowIterator == firstRow)
                                            {
                                                result.Add(
                                                    new Section
                                                {
                                                    CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.TwoColumnRightVerticalSection,
                                                    Order          = sectionOrder,
                                                    Columns        = GetColumns(2),
                                                    ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                                    VerticalSectionZoneEmphasis = verticalColumnEmphasis,
                                                });
                                            }
                                            else
                                            {
                                                result.Add(
                                                    new Section
                                                {
                                                    CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.TwoColumnRight,
                                                    Order          = sectionOrder,
                                                    Columns        = GetColumns(2),
                                                    ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                                });
                                            }
                                        }
                                        else
                                        {
                                            // image right
                                            if (includeVerticalColumn && rowIterator == firstRow)
                                            {
                                                result.Add(
                                                    new Section
                                                {
                                                    CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.TwoColumnLeftVerticalSection,
                                                    Order          = sectionOrder,
                                                    Columns        = GetColumns(2),
                                                    ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                                    VerticalSectionZoneEmphasis = verticalColumnEmphasis,
                                                });
                                            }
                                            else
                                            {
                                                result.Add(
                                                    new Section
                                                {
                                                    CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.TwoColumnLeft,
                                                    Order          = sectionOrder,
                                                    Columns        = GetColumns(2),
                                                    ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                                });
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (includeVerticalColumn && rowIterator == firstRow)
                                        {
                                            result.Add(
                                                new Section
                                            {
                                                CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.TwoColumnVerticalSection,
                                                Order          = sectionOrder,
                                                Columns        = GetColumns(2),
                                                ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                                VerticalSectionZoneEmphasis = verticalColumnEmphasis,
                                            });
                                        }
                                        else
                                        {
                                            result.Add(
                                                new Section
                                            {
                                                CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.TwoColumn,
                                                Order          = sectionOrder,
                                                Columns        = GetColumns(2),
                                                ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                            });
                                        }
                                    }
                                }
                                else
                                {
                                    if (firstImageColumn.Value == 1 || secondImageColumn.Value == 1)
                                    {
                                        // does one of the two columns have anything else besides image web parts
                                        var firstImageColumnOtherWebParts  = webpartsInRow.Where(p => p.Column == firstImageColumn.Key && p.Type != WebParts.WikiImage);
                                        var secondImageColumnOtherWebParts = webpartsInRow.Where(p => p.Column == secondImageColumn.Key && p.Type != WebParts.WikiImage);

                                        if (!firstImageColumnOtherWebParts.Any() && !secondImageColumnOtherWebParts.Any())
                                        {
                                            // two columns with each only one image...
                                            if (includeVerticalColumn && rowIterator == firstRow)
                                            {
                                                result.Add(
                                                    new Section
                                                {
                                                    CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.TwoColumnVerticalSection,
                                                    Order          = sectionOrder,
                                                    Columns        = GetColumns(2),
                                                    ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                                    VerticalSectionZoneEmphasis = verticalColumnEmphasis,
                                                });
                                            }
                                            else
                                            {
                                                result.Add(
                                                    new Section
                                                {
                                                    CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.TwoColumn,
                                                    Order          = sectionOrder,
                                                    Columns        = GetColumns(2),
                                                    ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                                });
                                            }
                                        }
                                        else if (!firstImageColumnOtherWebParts.Any() && secondImageColumnOtherWebParts.Any())
                                        {
                                            if (includeVerticalColumn && rowIterator == firstRow)
                                            {
                                                result.Add(
                                                    new Section
                                                {
                                                    CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.TwoColumnRightVerticalSection,
                                                    Order          = sectionOrder,
                                                    Columns        = GetColumns(2),
                                                    ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                                    VerticalSectionZoneEmphasis = verticalColumnEmphasis,
                                                });
                                            }
                                            else
                                            {
                                                result.Add(
                                                    new Section
                                                {
                                                    CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.TwoColumnRight,
                                                    Order          = sectionOrder,
                                                    Columns        = GetColumns(2),
                                                    ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                                });
                                            }
                                        }
                                        else if (firstImageColumnOtherWebParts.Any() && !secondImageColumnOtherWebParts.Any())
                                        {
                                            if (includeVerticalColumn && rowIterator == firstRow)
                                            {
                                                result.Add(
                                                    new Section
                                                {
                                                    CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.TwoColumnLeftVerticalSection,
                                                    Order          = sectionOrder,
                                                    Columns        = GetColumns(2),
                                                    ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                                    VerticalSectionZoneEmphasis = verticalColumnEmphasis,
                                                });
                                            }
                                            else
                                            {
                                                result.Add(
                                                    new Section
                                                {
                                                    CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.TwoColumnLeft,
                                                    Order          = sectionOrder,
                                                    Columns        = GetColumns(2),
                                                    ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                                });
                                            }
                                        }
                                        else
                                        {
                                            if (includeVerticalColumn && rowIterator == firstRow)
                                            {
                                                result.Add(
                                                    new Section
                                                {
                                                    CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.TwoColumnVerticalSection,
                                                    Order          = sectionOrder,
                                                    Columns        = GetColumns(2),
                                                    ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                                    VerticalSectionZoneEmphasis = verticalColumnEmphasis,
                                                });
                                            }
                                            else
                                            {
                                                result.Add(
                                                    new Section
                                                {
                                                    CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.TwoColumn,
                                                    Order          = sectionOrder,
                                                    Columns        = GetColumns(2),
                                                    ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                                });
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (includeVerticalColumn && rowIterator == firstRow)
                                        {
                                            result.Add(
                                                new Section
                                            {
                                                CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.TwoColumnVerticalSection,
                                                Order          = sectionOrder,
                                                Columns        = GetColumns(2),
                                                ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                                VerticalSectionZoneEmphasis = verticalColumnEmphasis,
                                            });
                                        }
                                        else
                                        {
                                            result.Add(
                                                new Section
                                            {
                                                CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.TwoColumn,
                                                Order          = sectionOrder,
                                                Columns        = GetColumns(2),
                                                ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                            });
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (includeVerticalColumn && rowIterator == firstRow)
                                {
                                    result.Add(
                                        new Section
                                    {
                                        CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.TwoColumnVerticalSection,
                                        Order          = sectionOrder,
                                        Columns        = GetColumns(2),
                                        ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                        VerticalSectionZoneEmphasis = verticalColumnEmphasis,
                                    });
                                }
                                else
                                {
                                    result.Add(
                                        new Section
                                    {
                                        CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.TwoColumn,
                                        Order          = sectionOrder,
                                        Columns        = GetColumns(2),
                                        ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                    });
                                }
                            }
                        }
                        else if (maxColumns == 3)
                        {
                            if (includeVerticalColumn && rowIterator == firstRow)
                            {
                                result.Add(
                                    new Section
                                {
                                    CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.ThreeColumnVerticalSection,
                                    Order          = sectionOrder,
                                    Columns        = GetColumns(3),
                                    ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                    VerticalSectionZoneEmphasis = verticalColumnEmphasis,
                                });
                            }
                            else
                            {
                                result.Add(
                                    new Section
                                {
                                    CanvasTemplate = Core.Model.SharePoint.CanvasSectionTemplate.ThreeColumn,
                                    Order          = sectionOrder,
                                    Columns        = GetColumns(3),
                                    ZoneEmphasis   = GetBackgroundEmphasis(pageLayout, rowIterator),
                                });
                            }
                        }

                        sectionOrder++;
                    }
                }
                else
                {
                    // non used row...ignore
                }
            }

            return(result);
        }
コード例 #46
0
        public async Task SyncToBand()
        {
            // Get the list of Microsoft Bands paired to the phone/tablet/PC.
            pairedBands = await BandClientManager.Instance.GetBandsAsync();

            if (pairedBands.Count() == 0)
            {
                BandStatusTxt = "You are not paired to a Microsoft Band";
                return;
            }

            BandStatusTxt = "Connecting to Microsoft Band...";
            try
            {
                // Connect to Microsoft Band.
                using (IBandClient bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]))
                {
                    BandStatusTxt = "Connected...preparing to update";
                    Guid TileGuid = App.APP_SETTINGS.BandID;

                    BandTile RewardsTile = new BandTile(TileGuid)
                    {
                        Name = "Rewards Wallet",
                        SmallIcon = await LoadIcon("ms-appx:///Assets/BandTileIcon_sm.png"),
                        TileIcon = await LoadIcon("ms-appx:///Assets/BandTileIcon.png")
                    };


                    // CODE_39 Page
                    TextBlock myCardTextBlock = new TextBlock()
                    {
                        ColorSource = ElementColorSource.BandHighlight,
                        ElementId = 1, // the Id of the TextBlock element; we'll use it later to set its text to "MY CARD"
                        Rect = new PageRect(0, 0, 250, 30),
                        Margins = new Margins(15, 0, 15, 15)
                    };
                    Barcode barcode = new Barcode(BarcodeType.Code39)
                    {
                        ElementId = 2, // the Id of the Barcode element; we'll use it later to set its barcode value to be rendered
                        Rect = new PageRect(0, 0, 250, 100)
                    };
                    FlowPanel panel = new FlowPanel(myCardTextBlock, barcode)
                    {
                        Orientation = FlowPanelOrientation.Vertical,
                        Rect = new PageRect(0, 0, 250, 145)
                    };

                    PageLayout layout_CODE_39 = new PageLayout(panel);

                    // PDF_417 Page
                    TextBlock myCardTextBlock2 = new TextBlock()
                    {
                        ColorSource = ElementColorSource.BandHighlight,
                        ElementId = 1, // the Id of the TextBlock element; we'll use it later to set its text to "MY CARD"
                        Rect = new PageRect(0, 0, 250, 30),
                        Margins = new Margins(15, 0, 15, 15)
                    };
                    Barcode barcode2 = new Barcode(BarcodeType.Pdf417)
                    {
                        ElementId = 2, // the Id of the Barcode element; we'll use it later to set its barcode value to be rendered
                        Rect = new PageRect(0, 0, 250, 100)
                    };
                    FlowPanel panel2 = new FlowPanel(myCardTextBlock2, barcode2)
                    {
                        Orientation = FlowPanelOrientation.Vertical,
                        Rect = new PageRect(0, 0, 250, 145)
                    };

                    PageLayout layout_PDF_417 = new PageLayout(panel2);

                    try
                    {
                        // add the layout to the tile
                        RewardsTile.PageLayouts.Add(layout_CODE_39);
                        RewardsTile.PageLayouts.Add(layout_PDF_417);
                    }
                    catch (BandException ex)
                    {
                        // handle an error adding the layout
                    }

                    try
                    {
                        // Add tile only if it doesn't already exist
                        IEnumerable<BandTile> currTiles = await bandClient.TileManager.GetTilesAsync();
                        if (currTiles.Where(t => t.TileId == TileGuid).Count() == 0)
                        {
                            BandStatusTxt = "Updating Rewards Wallet Tile...";
                            await bandClient.TileManager.RemoveTileAsync(RewardsTile);
                            // add the tile to the Band
                            if (await bandClient.TileManager.AddTileAsync(RewardsTile))
                            {
                                // tile was successfully added
                                // can proceed to set tile content with SetPagesAsync
                            }
                            else
                            {
                                // tile failed to be added, handle error
                                BandStatusTxt = "Error adding Rewards Wallet Tile to the Band";
                            }
                        }
                    }
                    catch (BandException ex)
                    {
                        // handle a Band connection exception
                        BandStatusTxt = "Error adding Rewards Wallet Tile to the Band";
                        return;
                    }

                    await bandClient.TileManager.RemovePagesAsync(TileGuid);

                    int PagesAdded = 0;
                    for (var idx = 0; idx < App.APP_SETTINGS.RewardCards.Count && PagesAdded < 8; idx++)
                    {
                        BarcodeType pageBarcodeType = BarcodeType.Code39;

                        if (CanBeRenderedOnBand(App.APP_SETTINGS.RewardCards[idx]))
                        {                            
                            Guid messagesPageGuid = Guid.NewGuid();
                            string cardNumber = App.APP_SETTINGS.RewardCards[idx].Number;

                            // we're going from native UPC encoding to UPC39...some cases require the dropping of a check digit
                            switch(App.APP_SETTINGS.RewardCards[idx].Format)
                            {
                                case ZXing.BarcodeFormat.EAN_13:
                                case ZXing.BarcodeFormat.EAN_8:
                                case ZXing.BarcodeFormat.UPC_EAN_EXTENSION:
                                case ZXing.BarcodeFormat.UPC_A:
                                    pageBarcodeType = BarcodeType.Code39;
                                    cardNumber = App.APP_SETTINGS.RewardCards[idx].Number.Substring(0, App.APP_SETTINGS.RewardCards[idx].Number.Length - 1);
                                    break;
                                case ZXing.BarcodeFormat.PDF_417:
                                    pageBarcodeType = BarcodeType.Pdf417;
                                    cardNumber = App.APP_SETTINGS.RewardCards[idx].Number; ;
                                    break;
                                case ZXing.BarcodeFormat.CODE_128:
                                    pageBarcodeType = BarcodeType.Code39;
                                    cardNumber = App.APP_SETTINGS.RewardCards[idx].Number; ;
                                    break;
                            }

                            PageData pageContent;
                            if (pageBarcodeType == BarcodeType.Code39)
                            {
                                pageContent = new PageData(
                                    messagesPageGuid,
                                    0,
                                    new TextBlockData(1, App.APP_SETTINGS.RewardCards[idx].Name.Trim()),
                                    new BarcodeData(pageBarcodeType, barcode.ElementId.Value, cardNumber)
                                    );
                            }
                            else
                            {
                                pageContent = new PageData(
                                    messagesPageGuid,
                                    1,
                                    new TextBlockData(1, App.APP_SETTINGS.RewardCards[idx].Name.Trim()),
                                    new BarcodeData(pageBarcodeType, barcode.ElementId.Value, cardNumber)
                                    );
                            }

                            try
                            {
                                // set the page content on the Band
                                if (await bandClient.TileManager.SetPagesAsync(TileGuid, pageContent))
                                {
                                    // page content successfully set on Band
                                    BandStatusTxt = "Updating " + App.APP_SETTINGS.RewardCards[idx].Name.Trim() + " card";
                                    PagesAdded++;
                                }
                                else
                                {
                                    // unable to set content to the Band
                                    BandStatusTxt = "Failed to add " + App.APP_SETTINGS.RewardCards[idx].Name.Trim() + " card to the Band";
                                }
                            }
                            catch (BandException ex)
                            {
                                // handle a Band connection exception
                                BandStatusTxt = "Failed to add cards to the Band";
                            }
                        }
                    }
                    BandStatusTxt = "Sync to Band Complete!";
                    DispatcherTimer timer = new DispatcherTimer();
                    timer.Tick += (object sender, object e) => {
                        timer.Stop();
                        BandStatusTxt = string.Empty;
                    };
                    timer.Interval = new TimeSpan(0, 0, 3);
                    timer.Start();
                }
            }
            catch(Exception e)
            {
                BandStatusTxt = "Failed to connect to the Microsoft Band";
                
            }
        }
コード例 #47
0
        private async void CreateTileWithButton_Click(object sender, EventArgs e)
        {
            // add the layout to the tile
            if (BandHelper.Instance.BandClient == null)
            {
                await BandHelper.Instance.Connect();
            }

            var tile = await BandHelper.CreateTile("Step 7 Tile");

            // create a filled rectangle to provide the background for a button
            var panel = new FilledPanel
            {
                Rect = new PageRect(0, 0, 245, 102),
                BackgroundColorSource = ElementColorSource.BandBase
            };

            // add a button to our layout
            panel.Elements.Add(
                new TextButton
            {
                ElementId    = (short)TilePageElementId.Button_PushMe,
                Rect         = new PageRect(60, 25, 100, 50),
                PressedColor = new Microsoft.Band.Portable.BandColor(0xFF, 0x00, 0x00),
            });

            // create the page layout
            var layout = new PageLayout(panel);

            // add the layout to the tile, and add the tile to the Band
            try
            {
                tile.PageLayouts.Add(layout);
                if (await BandHelper.Instance.BandClient.TileManager.AddTileAsync(tile))
                {
                    // layout and tile added successfully
                }
                else
                {
                    // tile failed to be added, handle error
                }
            }
            catch (Exception ex)
            {
                // handle an error adding the layout
            }

            var pageGuid = Guid.NewGuid();

            // create the content to assign to the page
            var textButtonData = new TextButtonData
            {
                ElementId = (int)TilePageElementId.Button_PushMe,
                Text      = "Push Me!"
            };

            var pageContent = new PageData
            {
                PageId          = pageGuid,
                PageLayoutIndex = 0,
                Data            =
                {
                    textButtonData
                }
            };


            // set the page content to the Band
            try
            {
                await BandHelper.Instance.BandClient.TileManager
                .SetTilePageDataAsync(tile.Id, pageContent);
            }
            catch (Exception ex)
            {
                // handle a Band connection exception
            }
        }
コード例 #48
0
        private void CreateLayout(BandTile tile)
        {
            ScrollFlowPanel panel = new ScrollFlowPanel()
            {
                Rect = new PageRect(0, 0, 245, 102),
                Orientation = FlowPanelOrientation.Vertical
            };

            Icon icon = new Icon()
            {
                ElementId = 3,
                Rect = new PageRect(0, 0, 245, 102),
                Margins = new Margins(15, 0, 15, 0),
                VerticalAlignment = VerticalAlignment.Top,
            };

            var nombre = new WrappedTextBlock
            {
                ElementId = 1,
                Rect = new PageRect(0, 0, 245, 102),
                Margins = new Margins(15, 0, 15, 0),
                Color = new BandColor(0xFF, 0xFF, 0xFF),
                Font = WrappedTextBlockFont.Small,
                VerticalAlignment = VerticalAlignment.Top
            };

            var motto = new WrappedTextBlock
            {
                ElementId = 2,
                Rect = new PageRect(0, 0, 245, 102),
                Margins = new Margins(15, 0, 15, 0),
                Color = new BandColor(0xFF, 0xFF, 0xFF),
                Font = WrappedTextBlockFont.Small,
                VerticalAlignment = VerticalAlignment.Top
            };

            panel.Elements.Add(icon); 
            panel.Elements.Add(nombre);
            panel.Elements.Add(motto);

            PageLayout layout = new PageLayout(panel);
            tile.PageLayouts.Add(layout);
        }
コード例 #49
0
ファイル: MainActivity.cs プロジェクト: jalvareh/Altitude
        async void AddTileButton_Click(object sender, EventArgs e)
        {
            if (0 == String.Compare(addTileButton.Text, AddTileString))
            {             // add tile
                try
                {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.InScaled = false;
                    var tile = new BandTile(tileId)
                    {
                        Icon      = BandImage.FromBitmap(BitmapFactory.DecodeResource(Resources, Resource.Raw.tile, options)),
                        Name      = "Altitude",
                        SmallIcon = BandImage.FromBitmap(BitmapFactory.DecodeResource(Resources, Resource.Raw.badge, options)),
                        IsScreenTimeoutDisabled = true
                    };
                    // define the page layout
                    var pageLayout = new PageLayout {
                        Root = new FlowPanel {
                            Orientation = FlowPanelOrientation.Vertical,
                            Rect        = new PageRect(0, 0, 258, 128),
                        }
                    };

                    // Page1 line1
                    var line1 = new FlowPanel {
                        Orientation = FlowPanelOrientation.Horizontal,
                        Rect        = new PageRect(0, 0, 258, 30),
                        Elements    =
                        {
                            new TextBlock {
                                ElementId         = 1,
                                Rect              = new PageRect(0, 0, 258, 30),
                                Margins           = new Margins(15, 0, 0, 0),
                                VerticalAlignment = VerticalAlignment.Bottom,
                                Font              = TextBlockFont.Small,
                                ColorSource       = ElementColorSource.BandHighlight,
                            },
                            new TextBlock {
                                ElementId         = 2,
                                Rect              = new PageRect(0, 0, 258, 30),
                                Margins           = new Margins(10, 0, 0, 0),
                                VerticalAlignment = VerticalAlignment.Bottom,
                                Font              = TextBlockFont.Small
                            }
                        }
                    };

                    // Page1 Line2
                    var line2 = new FlowPanel {
                        Orientation = FlowPanelOrientation.Horizontal,
                        Rect        = new PageRect(0, 38, 280, 90),
                        Elements    =
                        {
                            new Icon      {
                                ElementId         = 10,
                                Rect              = new PageRect(0, 0, 24, 24),
                                Margins           = new Margins(15, 35, 0, 0),
                                VerticalAlignment = VerticalAlignment.Top,
                                ColorSource       = ElementColorSource.BandBase
                            },
                            new Icon      {
                                ElementId         = 11,
                                Rect              = new PageRect(0, 0, 24, 24),
                                Margins           = new Margins(-24, 35, 0, 0),
                                VerticalAlignment = VerticalAlignment.Top,
                                Color             = new BandColor(0xff, 0, 0)                           //red
                            },
                            new Icon      {
                                ElementId         = 12,
                                Rect              = new PageRect(0, 0, 24, 24),
                                Margins           = new Margins(-24, 35, 0, 0),
                                VerticalAlignment = VerticalAlignment.Bottom,
                                Color             = new BandColor(0xff, 0xff, 0)                        //yellow
                            },
                            new Icon      {
                                ElementId         = 13,
                                Rect              = new PageRect(0, 0, 24, 24),
                                Margins           = new Margins(-24, 35, 0, 0),
                                VerticalAlignment = VerticalAlignment.Bottom,
                                Color             = new BandColor(0, 0xff, 0)                           //green
                            },
                            new TextBlock {
                                ElementId         = 5,
                                Rect              = new PageRect(0, 0, 228, 90),
                                Margins           = new Margins(10, 0, 0, 15),
                                VerticalAlignment = VerticalAlignment.Bottom,
                                Font              = TextBlockFont.ExtraLargeNumbersBold
                            }
                        }
                    };



                    pageLayout.Root.Elements.Add(line1);
                    pageLayout.Root.Elements.Add(line2);

                    // add the page layout to the tile
                    tile.PageLayouts.Add(pageLayout);
                    // add the tile to the Band
                    await Model.Instance.Client.TileManager.AddTileAsync(tile);

                    addTileButton.Text = RemoveTileString;
                }
                catch (Exception ex)
                {
                    Util.ShowExceptionAlert(this, "Add Tile", ex);
                }
            }
            else
            {             // remove tile
                try
                {
                    await Model.Instance.Client.TileManager.RemoveTileAsync(tileId);

                    addTileButton.Text = AddTileString;
                }
                catch (Exception ex)
                {
                    Util.ShowExceptionAlert(this, "Remove Tile", ex);
                }
            }
        }
コード例 #50
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            View rootView = inflater.Inflate(Resource.Layout.fragment_tiles, container, false);
            mListTiles = rootView.FindViewById<ListView>(Resource.Id.listTiles);

            RelativeLayout header = (RelativeLayout)inflater.Inflate(Resource.Layout.fragment_tiles_header, null);

			mTextRemainingCapacity = header.FindViewById<TextView>(Resource.Id.textAvailableCapacity);
			mButtonAddButtonTile = header.FindViewById<Button>(Resource.Id.buttonAddButtonTile);
			mButtonAddButtonTile.Click += async delegate
			{
				try
				{
					//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
					//ORIGINAL LINE: final android.graphics.BitmapFactory.Options options = new android.graphics.BitmapFactory.Options();
					BitmapFactory.Options options = new BitmapFactory.Options();
					options.InScaled = false;
					BandIcon tileIcon = BandIcon.ToBandIcon(BitmapFactory.DecodeResource(Resources, Resource.Raw.tile, options));

					BandIcon badgeIcon = BandIcon.ToBandIcon(BitmapFactory.DecodeResource(Resources, Resource.Raw.badge, options));

					FilledButton button = new FilledButton(0, 5, 210, 45);
                    button.BackgroundColor = Color.Red;
					button.Margins = new Margins(0, 5, 0 ,0);
					button.ElementId = 12;

					TextButton button2 = new TextButton(0, 0, 210, 45);
                    button2.PressedColor = Color.Blue;
					button2.Margins = new Margins(0, 5, 0 ,0);
					button2.ElementId = 21;

					FlowPanel flowPanel = new FlowPanel(15, 0, 260, 105, FlowPanelOrientation.Vertical);
					flowPanel.AddElements(button);
					flowPanel.AddElements(button2);

					PageLayout pageLayout = new PageLayout(flowPanel);

					BandTile.Builder builder = new BandTile.Builder(Java.Util.UUID.RandomUUID(), mEditTileName.Text, tileIcon);
					if (mCheckboxBadging.Checked)
					{
						builder.SetTileSmallIcon(badgeIcon);
					}
					if (mCheckboxCustomTheme.Checked)
					{
						builder.SetTheme(mThemeView.Theme);
					}
					builder.SetPageLayouts(pageLayout);
					BandTile tile = builder.Build();

					try
					{
						var result = await Model.Instance.Client.TileManager.AddTileTaskAsync(Activity, tile);
						if (result)
						{
							Toast.MakeText(Activity, "Tile added", ToastLength.Short).Show();
						}
						else
						{
							Toast.MakeText(Activity, "Unable to add tile", ToastLength.Short).Show();
						}
					}
					catch (Exception ex)
					{
						Util.ShowExceptionAlert(Activity, "Add tile", ex);
					}

					PageData pageData = new PageData(Java.Util.UUID.RandomUUID(), 0);
					pageData.Update(new FilledButtonData(12, Color.Yellow));
					pageData.Update(new TextButtonData(21, "Text Button"));
					await Model.Instance.Client.TileManager.SetPagesTaskAsync(tile.TileId, pageData);

					Toast.MakeText(Activity, "Page updated", ToastLength.Short).Show();

					// Refresh our tile list and count
					await RefreshData();
					RefreshControls();
				}
				catch (Exception e)
				{
					Util.ShowExceptionAlert(Activity, "Add tile", e);
				}
			};
			mButtonAddBarcodeTile = header.FindViewById<Button>(Resource.Id.buttonAddBarcodeTile);
			mButtonAddBarcodeTile.Click += async delegate
			{
				try
				{
					//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
					//ORIGINAL LINE: final android.graphics.BitmapFactory.Options options = new android.graphics.BitmapFactory.Options();
					BitmapFactory.Options options = new BitmapFactory.Options();
					options.InScaled = false;
					BandIcon tileIcon = BandIcon.ToBandIcon(BitmapFactory.DecodeResource(Resources, Resource.Raw.tile, options));

					BandIcon badgeIcon = BandIcon.ToBandIcon(BitmapFactory.DecodeResource(Resources, Resource.Raw.badge, options));

					// create layout 1

					Barcode barcode1 = new Barcode(new PageRect(0, 0, 221, 70), BarcodeType.Code39);
					barcode1.Margins = new Margins(3, 0, 0, 0);
					barcode1.ElementId = 11;

					TextBlock textBlock1 = new TextBlock(new PageRect(0, 0, 230, 30), TextBlockFont.Small, 0);
					textBlock1.Color = Color.Red;
					textBlock1.ElementId = 21;

					FlowPanel flowPanel1 = new FlowPanel(new PageRect(15, 0, 245, 105), FlowPanelOrientation.Vertical);
					flowPanel1.AddElements(barcode1);
					flowPanel1.AddElements(textBlock1);

					PageLayout pageLayout1 = new PageLayout(flowPanel1);

					// create layout 2

					Barcode barcode2 = new Barcode(0, 0, 221, 70, BarcodeType.Pdf417);
					barcode2.Margins = new Margins(3, 0, 0, 0);
					barcode2.ElementId = 11;

					TextBlock textBlock2 = new TextBlock(0, 0, 230, 30, TextBlockFont.Small, 0);
					textBlock2.Color = Color.Red;
					textBlock2.ElementId = 21;

					FlowPanel flowPanel2 = new FlowPanel(15, 0, 245, 105, FlowPanelOrientation.Vertical);
					flowPanel2.AddElements(barcode2);
					flowPanel2.AddElements(textBlock2);

					PageLayout pageLayout2 = new PageLayout(flowPanel2);

					// create the tile

					BandTile.Builder builder = new BandTile.Builder(Java.Util.UUID.RandomUUID(), mEditTileName.Text, tileIcon);
					if (mCheckboxBadging.Checked)
					{
						builder.SetTileSmallIcon(badgeIcon);
					}
					if (mCheckboxCustomTheme.Checked)
					{
						builder.SetTheme(mThemeView.Theme);
					}
					builder.SetPageLayouts(pageLayout1, pageLayout2);
					BandTile tile = builder.Build();

					// add tile

					try
					{
						var result = await Model.Instance.Client.TileManager.AddTileTaskAsync(Activity, tile);
						if (result)
						{
							Toast.MakeText(Activity, "Tile added", ToastLength.Short).Show();
						}
						else
						{
							Toast.MakeText(Activity, "Unable to add tile", ToastLength.Short).Show();
						}
					}
					catch (Exception ex)
					{
						Util.ShowExceptionAlert(Activity, "Add tile", ex);
					}

					PageData pageData1 = new PageData(Java.Util.UUID.RandomUUID(), 0);
					pageData1.Update(new BarcodeData(11, "MK12345509", BarcodeType.Code39));
					pageData1.Update(new TextButtonData(21, "MK12345509"));

					PageData pageData2 = new PageData(Java.Util.UUID.RandomUUID(), 1);
					pageData2.Update(new BarcodeData(11, "901234567890123456", BarcodeType.Pdf417));
					pageData2.Update(new TextButtonData(21, "901234567890123456"));

					await Model.Instance.Client.TileManager.SetPagesTaskAsync(tile.TileId, pageData1, pageData2);

					Toast.MakeText(Activity, "Page updated", ToastLength.Short).Show();

					// Refresh our tile list and count
					await RefreshData();
					RefreshControls();
				}
				catch (Exception e)
				{
					Util.ShowExceptionAlert(Activity, "Add tile", e);
				}
			};
            mButtonAddTile = header.FindViewById<Button>(Resource.Id.buttonAddTile);
            mButtonAddTile.Click += async delegate
            {
                try
                {
                    //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
                    //ORIGINAL LINE: final android.graphics.BitmapFactory.Options options = new android.graphics.BitmapFactory.Options();
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.InScaled = false;
                    BandIcon tileIcon = BandIcon.ToBandIcon(BitmapFactory.DecodeResource(Resources, Resource.Raw.tile, options));
					BandIcon badgeIcon = BandIcon.ToBandIcon(BitmapFactory.DecodeResource(Resources, Resource.Raw.badge, options));

					BandTile.Builder builder = new BandTile.Builder(Java.Util.UUID.RandomUUID(), mEditTileName.Text, tileIcon);
					if (mCheckboxBadging.Checked)
					{
						builder.SetTileSmallIcon(badgeIcon);
					}
					if (mCheckboxCustomTheme.Checked)
					{
						builder.SetTheme(mThemeView.Theme);
					}
					BandTile tile = builder.Build();

                    try
                    {
                        var result = await Model.Instance.Client.TileManager.AddTileTaskAsync(Activity, tile);
                        if (result)
                        {
                            Toast.MakeText(Activity, "Tile added", ToastLength.Short).Show();
                        }
                        else
                        {
                            Toast.MakeText(Activity, "Unable to add tile", ToastLength.Short).Show();
                        }
                    }
                    catch (Exception ex)
                    {
                        Util.ShowExceptionAlert(Activity, "Add tile", ex);
                    }

                    // Refresh our tile list and count
                    await RefreshData();
                    RefreshControls();
                }
                catch (Exception e)
                {
                    Util.ShowExceptionAlert(Activity, "Add tile", e);
                }
            };
            mButtonRemoveTile = header.FindViewById<Button>(Resource.Id.buttonRemoveTile);
            mButtonRemoveTile.Click += async delegate
            {
                try
                {
                    await Model.Instance.Client.TileManager.RemoveTileTaskAsync(mSelectedTile.TileId);
                    mSelectedTile = null;
                    Toast.MakeText(Activity, "Tile removed", ToastLength.Short).Show();
                    await RefreshData();
                    RefreshControls();
                }
                catch (Exception e)
                {
                    Util.ShowExceptionAlert(Activity, "Remove tile", e);
                }
            };
            mCheckboxBadging = header.FindViewById<CheckBox>(Resource.Id.cbBadging);

            mThemeView = header.FindViewById<BandThemeView>(Resource.Id.viewCustomTheme);
            mCheckboxCustomTheme = header.FindViewById<CheckBox>(Resource.Id.cbCustomTheme);
            mCheckboxCustomTheme.CheckedChange += (sender, e) =>
            {
                    mThemeView.Visibility = e.IsChecked ? ViewStates.Visible : ViewStates.Gone;
            };

            mEditTileName = header.FindViewById<EditText>(Resource.Id.editTileName);
            mEditTileName.TextChanged += (sender, e) => RefreshControls();

            RelativeLayout footer = (RelativeLayout)inflater.Inflate(Resource.Layout.fragment_tiles_footer, null);

            mEditTitle = footer.FindViewById<EditText>(Resource.Id.editTitle);
            mEditBody = footer.FindViewById<EditText>(Resource.Id.editBody);
            mCheckboxWithDialog = footer.FindViewById<CheckBox>(Resource.Id.cbWithDialog);

            mButtonSendMessage = footer.FindViewById<Button>(Resource.Id.buttonSendMessage);
            mButtonSendMessage.Click += async delegate
            {
                try
                {
                    await Model.Instance.Client.NotificationManager.SendMessageTaskAsync(
                        mSelectedTile.TileId,
                        mEditTitle.Text,
                        mEditBody.Text,
                        DateTime.Now,
                        mCheckboxWithDialog.Checked);
                }
                catch (Exception e)
                {
                    Util.ShowExceptionAlert(Activity, "Send message", e);
                }
            };

            mButtonSendDialog = footer.FindViewById<Button>(Resource.Id.buttonSendDialog);
            mButtonSendDialog.Click += async delegate
            {
                try
                {
                    await Model.Instance.Client.NotificationManager.ShowDialogTaskAsync(mSelectedTile.TileId, mEditTitle.Text, mEditBody.Text);
                }
                catch (Exception e)
                {
                    Util.ShowExceptionAlert(Activity, "Show dialog", e);
                }
            };

            mListTiles.AddHeaderView(header);
            mListTiles.AddFooterView(footer);

            mTileListAdapter = new TileListAdapter(this);
            mListTiles.Adapter = mTileListAdapter;

            mListTiles.ItemClick += (sender, e) =>
            {
                var position = e.Position - 1; // ignore the header
                if (position >= 0 && position < mTileListAdapter.Count)
                {
                    mSelectedTile = (BandTile) mTileListAdapter.GetItem(position);
                    RefreshControls();
                }
            };

            return rootView;
        }
コード例 #51
0
        public void Save()
        {
            if (EpubMode)
            {
                try
                {
                    SaveAsEpub();
                }
                catch (Exception err)
                {
                    SIL.Reporting.ErrorReport.NotifyUserOfProblem("Bloom was not able to save the ePUB.  {0}", err.Message);
                }
                return;
            }
            try
            {
                // Give a slight preference to USB keys, though if they used a different directory last time, we favor that.

                if (string.IsNullOrEmpty(_lastDirectory) || !Directory.Exists(_lastDirectory))
                {
                    var drives = SIL.UsbDrive.UsbDriveInfo.GetDrives();
                    if (drives != null && drives.Count > 0)
                    {
                        _lastDirectory = drives[0].RootDirectory.FullName;
                    }
                }

                using (var dlg = new DialogAdapters.SaveFileDialogAdapter())
                {
                    if (!string.IsNullOrEmpty(_lastDirectory) && Directory.Exists(_lastDirectory))
                    {
                        dlg.InitialDirectory = _lastDirectory;
                    }
                    var portion = "";
                    switch (BookletPortion)
                    {
                    case BookletPortions.None:
                        Debug.Fail("Save should not be enabled");
                        return;

                    case BookletPortions.AllPagesNoBooklet:
                        portion = "Pages";
                        break;

                    case BookletPortions.BookletCover:
                        portion = "Cover";
                        break;

                    case BookletPortions.BookletPages:
                        portion = "Inside";
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                    string suggestedName = string.Format("{0}-{1}-{2}.pdf", Path.GetFileName(_currentlyLoadedBook.FolderPath),
                                                         _collectionSettings.GetFilesafeLanguage1Name("en"), portion);
                    dlg.FileName = suggestedName;
                    var rgb = L10NSharp.LocalizationManager.GetString(@"PublishTab.PdfMaker.PdfWithRGB",
                                                                      "PDF with RGB color",
                                                                      @"displayed as file type for Save File dialog. 'RGB' may not be translatable, it is a standard.");
                    var swopv2 = L10NSharp.LocalizationManager.GetString(@"PublishTab.PdfMaker.PdfWithCmykSwopV2",
                                                                         "PDF with CMYK color (U.S. Web Coated (SWOP) v2)",
                                                                         @"displayed as file type for Save File dialog, the content in parentheses may not be translatable. 'CMYK' may not be translatable, it is a print shop standard.");

                    rgb        = rgb.Replace("|", "");
                    swopv2     = swopv2.Replace("|", "");
                    dlg.Filter = String.Format("{0}|*.pdf|{1}|*.pdf", rgb, swopv2);
                    if (DialogResult.OK == dlg.ShowDialog())
                    {
                        _lastDirectory = Path.GetDirectoryName(dlg.FileName);
                        switch (dlg.FilterIndex)
                        {
                        case 1:                         // PDF for Desktop Printing
                            RobustFile.Copy(PdfFilePath, dlg.FileName, true);
                            break;

                        case 2:                         // PDF for Printshop (CMYK US Web Coated V2)
                            ProcessPdfFurtherAndSave(ProcessPdfWithGhostscript.OutputType.Printshop, dlg.FileName);
                            break;
                        }
                        Analytics.Track("Save PDF", new Dictionary <string, string>()
                        {
                            { "Portion", Enum.GetName(typeof(BookletPortions), BookletPortion) },
                            { "Layout", PageLayout.ToString() },
                            { "BookId", BookSelection.CurrentSelection.ID },
                            { "Country", _collectionSettings.Country }
                        });
                    }
                }
            }
            catch (Exception err)
            {
                SIL.Reporting.ErrorReport.NotifyUserOfProblem("Bloom was not able to save the PDF.  {0}", err.Message);
            }
        }
コード例 #52
0
        /// <summary>
        /// Обработчик события загрузки страницы.
        /// </summary>
        /// <param name="e">Аргументы события.</param>
        protected override void OnLoad(EventArgs e)
        {
            // При открытии окна в качестве редактора лукапа или в дочернем окне следует установить
            // соответствующий тип разметки страницы.
            string lookUpQueryString = Request[WebParamController.OpenedFromLookupParamName];
            bool openAsLookUp = !string.IsNullOrEmpty(lookUpQueryString) && lookUpQueryString.ToLower().Equals("true");

            string newWindowQueryString = Request[WebParamController.OpenedInNewWindowParamName];
            bool openAsNewWindow = !string.IsNullOrEmpty(newWindowQueryString) && newWindowQueryString.ToLower().Equals("true");

            if (openAsLookUp || openAsNewWindow)
            {
                _layout = PageLayout.MainColumn;
            }

            LoadCurrentTheme();
            ApplyTreeViewCookie();

            fio.Text = Context.User.Identity.Name;

            base.OnLoad(e);
        }
コード例 #53
0
 public PageLayout Update(PageLayout entity)
 {
     DomainObjectValidator.ThrowIfInvalid(entity);
     clearCachedItemByID(entity.PageLayoutID);
     return entity;
 }
コード例 #54
0
        private async void OnAddBarcodeButtonClick(object sender, EventArgs e)
        {
            try
            {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.InScaled = false;
                BandIcon tileIcon = BandIcon.ToBandIcon(BitmapFactory.DecodeResource(Resources, Resource.Raw.tile, options));

                BandIcon badgeIcon = BandIcon.ToBandIcon(BitmapFactory.DecodeResource(Resources, Resource.Raw.badge, options));

                // create layout 1

                Barcode barcode1 = new Barcode(new PageRect(0, 0, 221, 70), BarcodeType.Code39);
                barcode1.Margins = new Margins(3, 0, 0, 0);
                barcode1.ElementId = 11;

                TextBlock textBlock1 = new TextBlock(new PageRect(0, 0, 230, 30), TextBlockFont.Small, 0);
                textBlock1.Color = Color.Red;
                textBlock1.ElementId = 21;

                FlowPanel flowPanel1 = new FlowPanel(new PageRect(15, 0, 245, 105), FlowPanelOrientation.Vertical);
                flowPanel1.AddElements(barcode1);
                flowPanel1.AddElements(textBlock1);

                PageLayout pageLayout1 = new PageLayout(flowPanel1);

                // create layout 2

                Barcode barcode2 = new Barcode(0, 0, 221, 70, BarcodeType.Pdf417);
                barcode2.Margins = new Margins(3, 0, 0, 0);
                barcode2.ElementId = 11;

                TextBlock textBlock2 = new TextBlock(0, 0, 230, 30, TextBlockFont.Small, 0);
                textBlock2.Color = Color.Red;
                textBlock2.ElementId = 21;

                FlowPanel flowPanel2 = new FlowPanel(15, 0, 245, 105, FlowPanelOrientation.Vertical);
                flowPanel2.AddElements(barcode2);
                flowPanel2.AddElements(textBlock2);

                PageLayout pageLayout2 = new PageLayout(flowPanel2);

                // create the tile

                BandTile.Builder builder = new BandTile.Builder(Java.Util.UUID.RandomUUID(), mEditTileName.Text, tileIcon);
                if (mCheckboxBadging.Checked)
                {
                    builder.SetTileSmallIcon(badgeIcon);
                }
                if (mCheckboxCustomTheme.Checked)
                {
                    builder.SetTheme(mThemeView.Theme);
                }
                builder.SetPageLayouts(pageLayout1, pageLayout2);
                BandTile tile = builder.Build();

                // add tile

                try
                {
                    var result = await Model.Instance.Client.TileManager.AddTileTaskAsync(Activity, tile);
                    if (result)
                    {
                        Toast.MakeText(Activity, "Tile added", ToastLength.Short).Show();
                    }
                    else
                    {
                        Toast.MakeText(Activity, "Unable to add tile", ToastLength.Short).Show();
                    }
                }
                catch (Exception ex)
                {
                    Util.ShowExceptionAlert(Activity, "Add tile", ex);
                }

                PageData pageData1 = new PageData(Java.Util.UUID.RandomUUID(), 0);
                pageData1.Update(new BarcodeData(11, "MK12345509", BarcodeType.Code39));
                pageData1.Update(new TextButtonData(21, "MK12345509"));

                PageData pageData2 = new PageData(Java.Util.UUID.RandomUUID(), 1);
                pageData2.Update(new BarcodeData(11, "901234567890123456", BarcodeType.Pdf417));
                pageData2.Update(new TextButtonData(21, "901234567890123456"));

                await Model.Instance.Client.TileManager.SetPagesTaskAsync(tile.TileId, pageData1, pageData2);

                Toast.MakeText(Activity, "Page updated", ToastLength.Short).Show();

                // Refresh our tile list and count
                await RefreshData();
                RefreshControls();
            }
            catch (Exception ex)
            {
                Util.ShowExceptionAlert(Activity, "Add tile", ex);
            }
        }
コード例 #55
0
        public virtual void ApplyLayout(PageLayout layout)
        {
            switch (layout)
            {
            case PageLayout.Wiki_OneColumn:
            case PageLayout.WebPart_FullPageVertical:
            case PageLayout.Wiki_Custom:
            case PageLayout.WebPart_Custom:
            {
                page.AddSection(CanvasSectionTemplate.OneColumn, 1);
                return;
            }

            case PageLayout.Wiki_TwoColumns:
            {
                page.AddSection(CanvasSectionTemplate.TwoColumn, 1);
                return;
            }

            case PageLayout.Wiki_ThreeColumns:
            {
                page.AddSection(CanvasSectionTemplate.ThreeColumn, 1);
                return;
            }

            case PageLayout.Wiki_TwoColumnsWithSidebar:
            case PageLayout.WebPart_HeaderRightColumnBody:
            {
                page.AddSection(CanvasSectionTemplate.TwoColumnLeft, 1);
                return;
            }

            case PageLayout.WebPart_HeaderLeftColumnBody:
            {
                page.AddSection(CanvasSectionTemplate.TwoColumnRight, 1);
                return;
            }

            case PageLayout.Wiki_TwoColumnsWithHeader:
            {
                page.AddSection(CanvasSectionTemplate.OneColumn, 1);
                page.AddSection(CanvasSectionTemplate.TwoColumn, 2);
                return;
            }

            case PageLayout.Wiki_TwoColumnsWithHeaderAndFooter:
            {
                page.AddSection(CanvasSectionTemplate.OneColumn, 1);
                page.AddSection(CanvasSectionTemplate.TwoColumn, 2);
                page.AddSection(CanvasSectionTemplate.OneColumn, 3);
                return;
            }

            case PageLayout.Wiki_ThreeColumnsWithHeader:
            {
                page.AddSection(CanvasSectionTemplate.OneColumn, 1);
                page.AddSection(CanvasSectionTemplate.ThreeColumn, 2);
                return;
            }

            case PageLayout.Wiki_ThreeColumnsWithHeaderAndFooter:
            case PageLayout.WebPart_HeaderFooterThreeColumns:
            case PageLayout.WebPart_HeaderFooter4ColumnsTopRow:
            case PageLayout.WebPart_HeaderFooter2Columns4Rows:
            {
                page.AddSection(CanvasSectionTemplate.OneColumn, 1);
                page.AddSection(CanvasSectionTemplate.ThreeColumn, 2);
                page.AddSection(CanvasSectionTemplate.OneColumn, 3);
                return;
            }

            case PageLayout.WebPart_LeftColumnHeaderFooterTopRow3Columns:
            case PageLayout.WebPart_RightColumnHeaderFooterTopRow3Columns:
            {
                page.AddSection(CanvasSectionTemplate.OneColumn, 1);
                page.AddSection(CanvasSectionTemplate.OneColumn, 2);
                page.AddSection(CanvasSectionTemplate.ThreeColumn, 3);
                page.AddSection(CanvasSectionTemplate.OneColumn, 4);
                return;
            }

            default:
            {
                page.AddSection(CanvasSectionTemplate.OneColumn, 1);
                return;
            }
            }
        }
コード例 #56
0
        private void DefaultPageLayoutProcess(SPWebEventProperties properties)
        {
            PageLayout _pageLayout;
            try
            {
                using (SPSite site = new SPSite(properties.SiteId))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        PublishingSite pubSiteCollection = new PublishingSite(site);
                        PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(properties.Web);

                        //check if pagelayout to be defaulted already exists in AvailablePageLayouts
                        _pageLayout = (from _pl in publishingWeb.GetAvailablePageLayouts()
                                       where _pl.Name == defaultPageLayout
                                       select _pl).FirstOrDefault();

                        //if exists
                        if (_pageLayout != null)
                        {
                            publishingWeb.SetDefaultPageLayout(_pageLayout, true);
                            publishingWeb.Update();
                        }
                        else  //if does not exist
                        {
                            //get all AvailablePageLayouts
                            PageLayout[] _allpageLayout = publishingWeb.GetAvailablePageLayouts();
                            PageLayout[] plarray = new PageLayout[_allpageLayout.Length + 1];
                            int ipl = -1;
                            //transfer existing pagelayouts in AvailablePageLayouts to PageLayout[]
                            foreach (PageLayout _itempl in _allpageLayout)
                            {
                                ipl++;
                                plarray[ipl] = _itempl;
                            }

                            //PageLayout to be defaulted to
                            _pageLayout = pubSiteCollection.PageLayouts["/_catalogs/masterpage/" + defaultPageLayout];
                            ipl++;
                            //add to the PageLayout array
                            plarray[ipl] = _pageLayout;
                            //reset AvailablePageLayouts
                            publishingWeb.SetAvailablePageLayouts(plarray, true);
                            publishingWeb.Update();
                            //set DefaultPageLayout
                            publishingWeb.SetDefaultPageLayout(_pageLayout, true);

                            publishingWeb.Update();
                            web.Update();
                        }

                        //Swap the page layout of the default.aspx page
                        SwapPageLayout(publishingWeb, _pageLayout, web.Site.RootWeb.ContentTypes[_pageLayout.AssociatedContentType.Id]);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog("WebProvisioning.cs - DefaultPageLayoutProcess: " + ex.Message + " " + ex.StackTrace);
            }
        }
コード例 #57
0
        private async Task CreateJukeboxTileAsync()
        {
            // create the small and tile icons from writable bitmaps.
            // Small icons are 24x24 pixels.
            var writeableSmallBmp = BitmapFactory.New(24, 24);
            using (writeableSmallBmp.GetBitmapContext())
            {
                // Load an image from the calling Assembly's resources via the relative path
                writeableSmallBmp = await BitmapFactory.New(1, 1).FromContent(new Uri("ms-appx:///Assets/Sensor24x24.png"));
            }
            var smallIcon = writeableSmallBmp.ToBandIcon();

            // Tile icons are 46x46 pixels for Microsoft Band 1, and 48x48 pixels for Microsoft 
            // Band 2.
            var writeableBmp = BitmapFactory.New(46, 46);
            using (writeableBmp.GetBitmapContext())
            {
                // Load an image from the calling Assembly's resources via the relative path
                writeableBmp = await BitmapFactory.New(1, 1).FromContent(new Uri("ms-appx:///Assets/Sensor46x46.png"));
            }
            var tileIcon = writeableBmp.ToBandIcon();

            // create a new Guid for the tile
            var tileGuid = Guid.NewGuid();

            // create a new tile with a new Guid
            var tile = new BandTile(tileGuid)
            {
                IsBadgingEnabled = true,
                Name = "Sensor Manager",
                SmallIcon = smallIcon,
                TileIcon = tileIcon
            };

            // create a filled rectangle to provide the background for a button 
            var panel = new FilledPanel
            {
                Rect = new PageRect(0, 0, 245, 102)
            };

            // add buttons to our layout 
            panel.Elements.Add(new TextButton
            {
                ElementId = (short)TilePageElementId.Jukebox_PlayRandom,
                Rect = new PageRect(20, 0, 70, 102),
                PressedColor = Colors.Blue.ToBandColor()
            });

            panel.Elements.Add(new TextButton
            {
                ElementId = (short)TilePageElementId.Jukebox_Pause,
                Rect = new PageRect(120, 0, 100, 45),
                PressedColor = Colors.Blue.ToBandColor()
            });

            panel.Elements.Add(new TextButton
            {
                ElementId = (short)TilePageElementId.Jukebox_Stop,
                Rect = new PageRect(120, 55, 100, 45),
                PressedColor = Colors.Blue.ToBandColor()
            });

            // create the page layout 
            var layout = new PageLayout(panel);

            // add the tile to the Band
            tile.PageLayouts.Add(layout);
            if (await bandClient.TileManager.AddTileAsync(tile))
            {
                // create the content to assign to the page 
                var pageContent = new PageData(Guid.NewGuid(),
                    0, // index of our (only) layout                 
                    new TextButtonData((short)TilePageElementId.Jukebox_PlayRandom, "Play"),
                    new TextButtonData((short)TilePageElementId.Jukebox_Pause, "Pause"),
                    new TextButtonData((short)TilePageElementId.Jukebox_Stop, "Stop"));

                await bandClient.TileManager.SetPagesAsync(tileGuid, pageContent);
            }
        }