private void PersistFile(Web web, ProvisioningTemplateCreationInformation creationInfo, PnPMonitoredScope scope, string folderPath, string fileName) { if (creationInfo.FileConnector != null) { var fileConnector = creationInfo.FileConnector; SharePointConnector connector = new SharePointConnector(web.Context, web.Url, "dummy"); Uri u = new Uri(web.Url); if (u.PathAndQuery != "/") { if (folderPath.IndexOf(u.PathAndQuery, StringComparison.InvariantCultureIgnoreCase) > -1) { folderPath = folderPath.Replace(u.PathAndQuery, ""); } } folderPath = HttpUtility.UrlDecode(folderPath); String container = HttpUtility.UrlDecode(folderPath).Trim('/').Replace("/", "\\"); String persistenceFileName = HttpUtility.UrlDecode(fileName); if (fileConnector.Parameters.ContainsKey(FileConnectorBase.CONTAINER)) { container = string.Concat(fileConnector.GetContainer(), container); } using (Stream s = connector.GetFileStream(persistenceFileName, folderPath)) { if (s != null) { creationInfo.FileConnector.SaveFileStream( persistenceFileName, container, s); } } } else { scope.LogError("No connector present to persist homepage"); } }
public void SharePointConnectorDeleteFromWebRootFolder() { SharePointConnector spConnector = new SharePointConnector(); spConnector.Parameters.Add(SharePointConnector.CONNECTIONSTRING, TestCommon.DevSiteUrl); spConnector.Parameters.Add(SharePointConnector.CLIENTCONTEXT, TestCommon.CreateClientContext()); // upload file using (var fileStream = System.IO.File.OpenRead(@".\resources\testdefault.aspx")) { spConnector.SaveFileStream("blabla.aspx", string.Empty, fileStream); } // delete the file spConnector.DeleteFile("blabla.aspx"); // read the file using (var bytes = spConnector.GetFileStream("blabla.aspx")) { Assert.IsNull(bytes); } }
private void DownLoadFile(SharePointConnector reader, SharePointConnector readerRoot, FileConnectorBase writer, string webUrl, string asset) { // No file passed...leave if (String.IsNullOrEmpty(asset)) { return; } SharePointConnector readerToUse; Model.File f = GetComposedLookFile(asset); // Strip the /sites/root part from /sites/root/lib/folder structure Uri u = new Uri(webUrl); if (f.Folder.IndexOf(u.PathAndQuery, StringComparison.InvariantCultureIgnoreCase) > -1) { f.Folder = f.Folder.Replace(u.PathAndQuery, ""); } // in case of a theme catalog we need to use the root site reader as that list only exists on root site level if (f.Folder.IndexOf("/_catalogs/theme", StringComparison.InvariantCultureIgnoreCase) > -1) { readerToUse = readerRoot; } else { readerToUse = reader; } using (Stream s = readerToUse.GetFileStream(f.Src, f.Folder)) { if (s != null) { writer.SaveFileStream(f.Src, s); } } }
private string LoadPropertyImage() { string assetCode = this.Request.QueryString["AssetCode"]; List <FinancedEstateImage> financedEstateImageList = SharePointConnector.GetFinancedEstateImages(); FinancedEstateImage gifImage = financedEstateImageList.Find(gif => gif.Name.Equals(assetCode + GIF, StringComparison.CurrentCultureIgnoreCase)); string gifImageUrl = financedEstateImageList.Find(fei => fei.Name.Equals(DEFAULT_IMAGE)).Url; if (gifImage != null) { gifImageUrl = gifImage.Url; } string formatedResult = string.Format( "<img src='{0}' alt='' />", gifImageUrl); return(formatedResult); }
protected void btnSaveAndPrint_Click(object sender, EventArgs e) { try { lblMessage.Visible = true; btnPrint.Visible = true; btnSaveAndPrint.Visible = false; SharePointConnector.SaveRate( lblFisa.Text, lblExecutive.Text, lblBank.Text, lblClientName.Text, lblClientCode.Text, lblCpop.Text, lblBanx.Text, lblDisabled.Text, lblSector.Text, lblSegmentType.Text, lblIvc.Text, lblIrt.Text, lblProduct.Text, lblProductType.Text, lblWarranty.Text, lblTerm.Text, lblPeriodFixed.Text, lblCurrency.Text, lblMargin.Text, //System.Text.RegularExpressions.Regex.Replace(lblRate.Text, @"<[^>]+>| ", "").Trim(), lblRate.Text, lblCpopBenefit.Text, lblDisabledBenefit.Text); } catch (Exception ex) { System.Web.UI.LiteralControl errorMessage = new System.Web.UI.LiteralControl(); errorMessage.Text = ex.Message; this.Controls.Clear(); this.Controls.Add(errorMessage); } }
private void PopulateFilteredItems(string catId, string region, string brand, string orderBy, int[] range) { litCategoryItems.Text = ""; int number; int categoryId = Int32.TryParse(catId, out number) ? number : 0; List <CatalogItem> catalogItems = new List <CatalogItem>(); switch (orderBy) { case "PUNTOS_ASC": catalogItems = SharePointConnector.GetCatalog(0, "Puntos", true); break; case "PUNTOS_DES": catalogItems = SharePointConnector.GetCatalog(0, "Puntos", false); break; case "PRODUCTO": catalogItems = SharePointConnector.GetCatalog(0, "Title", true); break; } foreach (CatalogItem item in catalogItems) { if (item.CategoryId == categoryId && item.Region.Contains(region) && item.Brand == brand) { if (item.Points >= range[0] && item.Points <= range[1]) { litCategoryItems.Text += string.Format( @"<li><a href=""{0}""><img src=""{1}""/></a><p><span>{2}</span><br/>{3}</p></li>", item.Url(), item.Image, FormatedPoints(item.Points) + " puntos", item.Title); } } } }
protected void SetParameters() { List <ParameterItem> paramsLink = SharePointConnector.GetParameters("ENLACE"); List <ParameterItem> paramsDescription = SharePointConnector.GetParameters("DESCRIPCIÓN"); foreach (ParameterItem item in paramsLink) { litCatalogLinks.Text += string.Format( @"<a href=""{0}"" class=""doc"" title=""""><p>{1}</p><img src=""{2}"" alt="""" /></a>", item.Link, item.Title, item.Image); } foreach (ParameterItem item in paramsDescription) { if (item.Title.Trim().Equals("Qué es el Club de Puntos? - A")) { litFaqA.Text = item.Description; } else if (item.Title.Trim().Equals("Qué es el Club de Puntos? - B")) { litFaqB.Text = item.Description; } } }
private static async Task <SickLeaveModel> SickLeaveDialogCompleted(IBotContext context, SickLeaveModel model) { LeaveRequest request = new LeaveRequest() { StartTime = model.StartTime, EndTime = model.EndTime, Title = $"Leave Request" }; string token = await context.GetADALAccessToken(_resourceUriSharePoint); await SharePointConnector.CreateLeaveRequest(request, token, SharePointSettings.GetFromEnvironment()); var message = "Done! I've saved your sick leave in SharePoint."; if (model.StillSick) { message += " Get well soon!"; } await context.PostAsync(message); return(model); }
private ProvisioningTemplate DetectComposedLook(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo, PnPMonitoredScope scope, SharePointConnector spConnector, SharePointConnector spConnectorRoot) { var theme = web.GetCurrentComposedLook(); if (theme != null) { if (creationInfo != null) { // Don't exclude the DesignPreviewThemedCssFolderUrl property bag, if any creationInfo.PropertyBagPropertiesToPreserve.Add("DesignPreviewThemedCssFolderUrl"); } template.ComposedLook.Name = theme.Name != null ? theme.Name : String.Empty; if (theme.IsCustomComposedLook) { // Set the URL pointers to files template.ComposedLook.BackgroundFile = FixFileUrl(Tokenize(theme.BackgroundImage, web.Url)); template.ComposedLook.ColorFile = FixFileUrl(Tokenize(theme.Theme, web.Url)); template.ComposedLook.FontFile = FixFileUrl(Tokenize(theme.Font, web.Url)); // Download files if this is root site, since theme files are only stored there if (!web.IsSubSite() && creationInfo != null && creationInfo.PersistBrandingFiles && creationInfo.FileConnector != null) { scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ComposedLooks_ExtractObjects_Creating_SharePointConnector); // Let's create a SharePoint connector since our files anyhow are in SharePoint at this moment // Download the theme/branding specific files DownLoadFile(spConnector, spConnectorRoot, creationInfo.FileConnector, web.Url, theme.BackgroundImage, scope); DownLoadFile(spConnector, spConnectorRoot, creationInfo.FileConnector, web.Url, theme.Theme, scope); DownLoadFile(spConnector, spConnectorRoot, creationInfo.FileConnector, web.Url, theme.Font, scope); } // Create file entries for the custom theme files, but only if it's a root site // If it's root site we do not extract or set theme files, since those are in the root of the site collection if (!web.IsSubSite()) { if (!string.IsNullOrEmpty(template.ComposedLook.BackgroundFile)) { template.Files.Add(GetComposedLookFile(template.ComposedLook.BackgroundFile)); } if (!string.IsNullOrEmpty(template.ComposedLook.ColorFile)) { template.Files.Add(GetComposedLookFile(template.ComposedLook.ColorFile)); } if (!string.IsNullOrEmpty(template.ComposedLook.FontFile)) { template.Files.Add(GetComposedLookFile(template.ComposedLook.FontFile)); } } // If a base template is specified then use that one to "cleanup" the generated template model if (creationInfo != null && creationInfo.BaseTemplate != null) { template = CleanupEntities(template, creationInfo.BaseTemplate); } } else { template.ComposedLook.BackgroundFile = ""; template.ComposedLook.ColorFile = ""; template.ComposedLook.FontFile = ""; } } else { template.ComposedLook = null; } return(template); }
protected override void ExecuteCmdlet() { SelectedWeb.EnsureProperty(w => w.Url); bool templateFromFileSystem = !Path.ToLower().StartsWith("http"); FileConnectorBase fileConnector; string templateFileName = System.IO.Path.GetFileName(Path); if (templateFromFileSystem) { if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } if (!string.IsNullOrEmpty(ResourceFolder)) { if (!System.IO.Path.IsPathRooted(ResourceFolder)) { ResourceFolder = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, ResourceFolder); } } FileInfo fileInfo = new FileInfo(Path); fileConnector = new FileSystemConnector(fileInfo.DirectoryName, ""); } else { Uri fileUri = new Uri(Path); var webUrl = Microsoft.SharePoint.Client.Web.WebUrlFromFolderUrlDirect(this.ClientContext, fileUri); var templateContext = this.ClientContext.Clone(webUrl.ToString()); string library = Path.ToLower().Replace(templateContext.Url.ToLower(), "").TrimStart('/'); int idx = library.IndexOf("/"); library = library.Substring(0, idx); fileConnector = new SharePointConnector(templateContext, templateContext.Url, library); } XMLTemplateProvider provider = null; ProvisioningTemplate provisioningTemplate = null; Stream stream = fileConnector.GetFileStream(templateFileName); var isOpenOfficeFile = IsOpenOfficeFile(stream); if (isOpenOfficeFile) { provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(templateFileName, fileConnector)); templateFileName = templateFileName.Substring(0, templateFileName.LastIndexOf(".")) + ".xml"; } else { if (templateFromFileSystem) { provider = new XMLFileSystemTemplateProvider(fileConnector.Parameters[FileConnectorBase.CONNECTIONSTRING] + "", ""); } else { throw new NotSupportedException("Only .pnp package files are supported from a SharePoint library"); } } provisioningTemplate = provider.GetTemplate(templateFileName, TemplateProviderExtensions); if (provisioningTemplate == null) { return; } if (isOpenOfficeFile) { provisioningTemplate.Connector = provider.Connector; } else { if (ResourceFolder != null) { var fileSystemConnector = new FileSystemConnector(ResourceFolder, ""); provisioningTemplate.Connector = fileSystemConnector; } else { provisioningTemplate.Connector = provider.Connector; } } if (Parameters != null) { foreach (var parameter in Parameters.Keys) { if (provisioningTemplate.Parameters.ContainsKey(parameter.ToString())) { provisioningTemplate.Parameters[parameter.ToString()] = Parameters[parameter].ToString(); } else { provisioningTemplate.Parameters.Add(parameter.ToString(), Parameters[parameter].ToString()); } } } var applyingInformation = new ProvisioningTemplateApplyingInformation(); if (this.MyInvocation.BoundParameters.ContainsKey("Handlers")) { applyingInformation.HandlersToProcess = Handlers; } if (this.MyInvocation.BoundParameters.ContainsKey("ExcludeHandlers")) { foreach (var handler in (OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers[])Enum.GetValues(typeof(Handlers))) { if (!ExcludeHandlers.Has(handler) && handler != Handlers.All) { Handlers = Handlers | handler; } } applyingInformation.HandlersToProcess = Handlers; } if (ExtensibilityHandlers != null) { applyingInformation.ExtensibilityHandlers = ExtensibilityHandlers.ToList <ExtensibilityHandler>(); } applyingInformation.ProgressDelegate = (message, step, total) => { WriteProgress(new ProgressRecord(0, string.Format("Applying template to {0}", SelectedWeb.Url), message) { PercentComplete = (100 / total) * step }); }; applyingInformation.MessagesDelegate = (message, type) => { if (type == ProvisioningMessageType.Warning) { WriteWarning(message); } }; applyingInformation.OverwriteSystemPropertyBagValues = OverwriteSystemPropertyBagValues; SelectedWeb.ApplyProvisioningTemplate(provisioningTemplate, applyingInformation); }
private List <ProvisioningTemplateInformation> SearchProvisioningTemplatesInternal(string searchText, TargetPlatform platforms, TargetScope scope, String cacheKey) { List <ProvisioningTemplateInformation> result = new List <ProvisioningTemplateInformation>(); // Connect to the target Templates Site Collection using (var context = PnPPartnerPackContextProvider.GetAppOnlyClientContext(TemplatesSiteUrl)) { // Get a reference to the target library Web web = context.Web; String platformsCAMLFilter = null; // Build the target Platforms filter if (platforms != TargetPlatform.None && platforms != TargetPlatform.All) { if ((platforms & TargetPlatform.SharePointOnline) == TargetPlatform.SharePointOnline) { platformsCAMLFilter = @"<Eq> <FieldRef Name='PnPProvisioningTemplatePlatform' /> <Value Type='MultiChoice'>SharePoint Online</Value> </Eq>"; } if ((platforms & TargetPlatform.SharePoint2016) == TargetPlatform.SharePoint2016) { if (!String.IsNullOrEmpty(platformsCAMLFilter)) { platformsCAMLFilter = @"<Or>" + platformsCAMLFilter + @" <Eq> <FieldRef Name='PnPProvisioningTemplatePlatform' /> <Value Type='MultiChoice'>SharePoint 2016</Value> </Eq> </Or>"; } else { platformsCAMLFilter = @"<Eq> <FieldRef Name='PnPProvisioningTemplatePlatform' /> <Value Type='MultiChoice'>SharePoint 2016</Value> </Eq>"; } } if ((platforms & TargetPlatform.SharePoint2013) == TargetPlatform.SharePoint2013) { if (!String.IsNullOrEmpty(platformsCAMLFilter)) { platformsCAMLFilter = @"<Or>" + platformsCAMLFilter + @" <Eq> <FieldRef Name='PnPProvisioningTemplatePlatform' /> <Value Type='MultiChoice'>SharePoint 2013</Value> </Eq> </Or>"; } else { platformsCAMLFilter = @"<Eq> <FieldRef Name='PnPProvisioningTemplatePlatform' /> <Value Type='MultiChoice'>SharePoint 2013</Value> </Eq>"; } } try { List list = web.Lists.GetByTitle(PnPPartnerPackConstants.PnPProvisioningTemplates); // Get only Provisioning Templates documents with the specified Scope CamlQuery query = new CamlQuery(); query.ViewXml = @"<View> <Query> <Where>" + (!String.IsNullOrEmpty(platformsCAMLFilter) ? " < And>" : String.Empty) + @" <And> <Eq> <FieldRef Name='PnPProvisioningTemplateScope' /> <Value Type='Choice'>" + scope.ToString() + @"</Value> </Eq> <Eq> <FieldRef Name='ContentType' /> <Value Type=''Computed''>PnPProvisioningTemplate</Value> </Eq> </And>" + platformsCAMLFilter + (!String.IsNullOrEmpty(platformsCAMLFilter) ? "</And>" : String.Empty) + @" </Where> </Query> <ViewFields> <FieldRef Name='Title' /> <FieldRef Name='PnPProvisioningTemplateScope' /> <FieldRef Name='PnPProvisioningTemplatePlatform' /> <FieldRef Name='PnPProvisioningTemplateSourceUrl' /> </ViewFields> </View>"; ListItemCollection items = list.GetItems(query); context.Load(items, includes => includes.Include(i => i.File, i => i[PnPPartnerPackConstants.PnPProvisioningTemplateScope], i => i[PnPPartnerPackConstants.PnPProvisioningTemplatePlatform], i => i[PnPPartnerPackConstants.PnPProvisioningTemplateSourceUrl])); context.ExecuteQueryRetry(); web.EnsureProperty(w => w.Url); // Configure the SharePoint Connector var sharepointConnector = new SharePointConnector(context, web.Url, PnPPartnerPackConstants.PnPProvisioningTemplates); foreach (ListItem item in items) { // Get the template file name and server relative URL item.File.EnsureProperties(f => f.Name, f => f.ServerRelativeUrl); TemplateProviderBase provider = null; // If the target is a .PNP Open XML template if (item.File.Name.ToLower().EndsWith(".pnp")) { // Configure the Open XML provider for SharePoint provider = new XMLOpenXMLTemplateProvider( new OpenXMLConnector(item.File.Name, sharepointConnector)); } else { // Otherwise use the .XML template provider for SharePoint provider = new XMLSharePointTemplateProvider(context, web.Url, PnPPartnerPackConstants.PnPProvisioningTemplates); } // Determine the name of the XML file inside the PNP Open XML file, if any var xmlTemplateFile = item.File.Name.ToLower().Replace(".pnp", ".xml"); // Get the template ProvisioningTemplate template = provider.GetTemplate(xmlTemplateFile); // Prepare the resulting item var templateInformation = new ProvisioningTemplateInformation { // Scope = (TargetScope)Enum.Parse(typeof(TargetScope), (String)item[PnPPartnerPackConstants.PnPProvisioningTemplateScope], true), TemplateSourceUrl = item[PnPPartnerPackConstants.PnPProvisioningTemplateSourceUrl] != null ? ((FieldUrlValue)item[PnPPartnerPackConstants.PnPProvisioningTemplateSourceUrl]).Url : null, TemplateFileUri = String.Format("{0}/{1}/{2}", web.Url, PnPPartnerPackConstants.PnPProvisioningTemplates, item.File.Name), TemplateImageUrl = template.ImagePreviewUrl, DisplayName = template.DisplayName, Description = template.Description, }; #region Determine Scope String targetScope; if (template.Properties.TryGetValue(PnPPartnerPackConstants.TEMPLATE_SCOPE, out targetScope)) { if (String.Equals(targetScope, PnPPartnerPackConstants.TEMPLATE_SCOPE_PARTIAL, StringComparison.InvariantCultureIgnoreCase)) { templateInformation.Scope = TargetScope.Partial; } else if (String.Equals(targetScope, PnPPartnerPackConstants.TEMPLATE_SCOPE_WEB, StringComparison.InvariantCultureIgnoreCase)) { templateInformation.Scope = TargetScope.Web; } else if (String.Equals(targetScope, PnPPartnerPackConstants.TEMPLATE_SCOPE_SITE, StringComparison.InvariantCultureIgnoreCase)) { templateInformation.Scope = TargetScope.Site; } } #endregion #region Determine target Platforms String spoPlatform, sp2016Platform, sp2013Platform; if (template.Properties.TryGetValue(PnPPartnerPackConstants.PLATFORM_SPO, out spoPlatform)) { if (spoPlatform.Equals(PnPPartnerPackConstants.TRUE_VALUE, StringComparison.InvariantCultureIgnoreCase)) { templateInformation.Platforms |= TargetPlatform.SharePointOnline; } } if (template.Properties.TryGetValue(PnPPartnerPackConstants.PLATFORM_SP2016, out sp2016Platform)) { if (sp2016Platform.Equals(PnPPartnerPackConstants.TRUE_VALUE, StringComparison.InvariantCultureIgnoreCase)) { templateInformation.Platforms |= TargetPlatform.SharePoint2016; } } if (template.Properties.TryGetValue(PnPPartnerPackConstants.PLATFORM_SP2013, out sp2013Platform)) { if (sp2013Platform.Equals(PnPPartnerPackConstants.TRUE_VALUE, StringComparison.InvariantCultureIgnoreCase)) { templateInformation.Platforms |= TargetPlatform.SharePoint2013; } } #endregion // If we don't have a search text // or we have a search text and it is contained either // in the DisplayName or in the Description of the template if ((!String.IsNullOrEmpty(searchText) && ((!String.IsNullOrEmpty(template.DisplayName) && template.DisplayName.ToLower().Contains(searchText.ToLower())) || (!String.IsNullOrEmpty(template.Description) && template.Description.ToLower().Contains(searchText.ToLower())))) || String.IsNullOrEmpty(searchText)) { // Add the template to the result result.Add(templateInformation); } } } catch (ServerException) { // In case of any issue, ignore the failing templates } } } CacheItemPolicy policy = new CacheItemPolicy { Priority = CacheItemPriority.Default, AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30), // Cache results for 30 minutes RemovedCallback = (args) => { if (args.RemovedReason == CacheEntryRemovedReason.Expired) { var removedKey = args.CacheItem.Key; var searchInputs = JsonConvert.DeserializeObject <SharePointSearchCacheKey>(removedKey); var newItem = SearchProvisioningTemplatesInternal( searchInputs.SearchText, searchInputs.Platforms, searchInputs.Scope, removedKey); } }, }; Cache.Set(cacheKey, result, policy); return(result); }
private void GetAndShowMainTabs() { SPListItemCollection mainTabsItems = SharePointConnector.GetMainTabs(); if (mainTabsItems == null) { this.ShowErrorMessage("No existen elementos que mostrar.<br/>Verifique que exista al menos UN elemento aprobado en la lista."); } else { string formatedTitle = ""; string formatedContent = ""; short limit = WPMainTabs.spTabsLimit; foreach (SPListItem tab in mainTabsItems) { if (limit == 0) { break; } string selectedOpt = ""; switch (tab["Icono_x0020_asociado"].ToString()) { case "ICONO 1": selectedOpt = "icon-opt1"; break; case "ICONO 2": selectedOpt = "icon-opt2"; break; case "ICONO 3": selectedOpt = "icon-opt3"; break; case "ICONO 4": selectedOpt = "icon-opt4"; break; case "ICONO 5": selectedOpt = "icon-opt5"; break; case "ICONO 6": selectedOpt = "icon-opt6"; break; case "ICONO 7": selectedOpt = "icon-opt7"; break; } string title = tab.Title.Trim(); string imagePath = tab["Imagen_x0020_asociada"].ToString().Contains(",") ? tab["Imagen_x0020_asociada"].ToString().Remove(tab["Imagen_x0020_asociada"].ToString().IndexOf(',')) : tab["Imagen_x0020_asociada"].ToString(); string description = ""; if (tab["Descripci_x00f3_n_x0020_asociada"] != null) { string fullDescription = tab["Descripci_x00f3_n_x0020_asociada"].ToString(); if (fullDescription.StartsWith("\"") && fullDescription.EndsWith("\"")) { description = string.Format( "<p class=\"left\">“</p><p>{0}</p><p class=\"right\">”</p>", fullDescription.Replace("\"", "")); } else { description = string.Format("<p>{0}</p>", fullDescription); } } formatedTitle += string.Format( "<li><a href=\"javascript:;\" title=\"\" class=\"{0}\"><span>{1}</span></a></li>", selectedOpt, title); formatedContent += string.Format( "<section style=\"background: url({0}) no-repeat center 0;\">" + "<div>{1}</div></section>", imagePath, description); limit--; } ltrTabsTitle.Text = formatedTitle; ltrTabsContent.Text = formatedContent; } }
protected override void ExecuteCmdlet() { SelectedWeb.EnsureProperty(w => w.Url); ProvisioningTemplate provisioningTemplate; FileConnectorBase fileConnector; if (ParameterSpecified(nameof(Path))) { bool templateFromFileSystem = !Path.ToLower().StartsWith("http"); string templateFileName = System.IO.Path.GetFileName(Path); if (templateFromFileSystem) { if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } if (!System.IO.File.Exists(Path)) { throw new FileNotFoundException($"File not found"); } if (!string.IsNullOrEmpty(ResourceFolder)) { if (!System.IO.Path.IsPathRooted(ResourceFolder)) { ResourceFolder = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, ResourceFolder); } } var fileInfo = new FileInfo(Path); fileConnector = new FileSystemConnector(fileInfo.DirectoryName, ""); } else { Uri fileUri = new Uri(Path); var webUrl = Microsoft.SharePoint.Client.Web.WebUrlFromFolderUrlDirect(ClientContext, fileUri); var templateContext = ClientContext.Clone(webUrl.ToString()); var library = Path.ToLower().Replace(templateContext.Url.ToLower(), "").TrimStart('/'); var idx = library.IndexOf("/", StringComparison.Ordinal); library = library.Substring(0, idx); // This syntax creates a SharePoint connector regardless we have the -InputInstance argument or not fileConnector = new SharePointConnector(templateContext, templateContext.Url, library); } // If we don't have the -InputInstance parameter, we load the template from the source connector Stream stream = fileConnector.GetFileStream(templateFileName); var isOpenOfficeFile = FileUtilities.IsOpenOfficeFile(stream); XMLTemplateProvider provider; if (isOpenOfficeFile) { var openXmlConnector = new OpenXMLConnector(templateFileName, fileConnector); provider = new XMLOpenXMLTemplateProvider(openXmlConnector); if (!String.IsNullOrEmpty(openXmlConnector.Info?.Properties?.TemplateFileName)) { templateFileName = openXmlConnector.Info.Properties.TemplateFileName; } else { templateFileName = templateFileName.Substring(0, templateFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml"; } } else { if (templateFromFileSystem) { provider = new XMLFileSystemTemplateProvider(fileConnector.Parameters[FileConnectorBase.CONNECTIONSTRING] + "", ""); } else { throw new NotSupportedException("Only .pnp package files are supported from a SharePoint library"); } } if (ParameterSpecified(nameof(TemplateId))) { provisioningTemplate = provider.GetTemplate(templateFileName, TemplateId, null, TemplateProviderExtensions); } else { provisioningTemplate = provider.GetTemplate(templateFileName, TemplateProviderExtensions); } if (provisioningTemplate == null) { // If we don't have the template, raise an error and exit WriteError(new ErrorRecord(new Exception("The -Path parameter targets an invalid repository or template object."), "WRONG_PATH", ErrorCategory.SyntaxError, null)); return; } if (isOpenOfficeFile) { provisioningTemplate.Connector = provider.Connector; } else { if (ResourceFolder != null) { var fileSystemConnector = new FileSystemConnector(ResourceFolder, ""); provisioningTemplate.Connector = fileSystemConnector; } else { provisioningTemplate.Connector = provider.Connector; } } } else { provisioningTemplate = InputInstance; if (ResourceFolder != null) { var fileSystemConnector = new FileSystemConnector(ResourceFolder, ""); provisioningTemplate.Connector = fileSystemConnector; } else { if (Path != null) { if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } } else { Path = SessionState.Path.CurrentFileSystemLocation.Path; } var fileInfo = new FileInfo(Path); fileConnector = new FileSystemConnector(System.IO.Path.IsPathRooted(fileInfo.FullName) ? fileInfo.FullName : fileInfo.DirectoryName, ""); provisioningTemplate.Connector = fileConnector; } } if (Parameters != null) { foreach (var parameter in Parameters.Keys) { if (provisioningTemplate.Parameters.ContainsKey(parameter.ToString())) { provisioningTemplate.Parameters[parameter.ToString()] = Parameters[parameter].ToString(); } else { provisioningTemplate.Parameters.Add(parameter.ToString(), Parameters[parameter].ToString()); } } } var applyingInformation = new ProvisioningTemplateApplyingInformation(); if (ParameterSpecified(nameof(Handlers))) { applyingInformation.HandlersToProcess = Handlers; } if (ParameterSpecified(nameof(ExcludeHandlers))) { foreach (var handler in (Handlers[])Enum.GetValues(typeof(Handlers))) { if (!ExcludeHandlers.Has(handler) && handler != Handlers.All) { Handlers = Handlers | handler; } } applyingInformation.HandlersToProcess = Handlers; } if (ExtensibilityHandlers != null) { applyingInformation.ExtensibilityHandlers = ExtensibilityHandlers.ToList(); } applyingInformation.ProgressDelegate = (message, step, total) => { if (message != null) { var percentage = Convert.ToInt32((100 / Convert.ToDouble(total)) * Convert.ToDouble(step)); progressRecord.Activity = $"Applying template to {SelectedWeb.Url}"; progressRecord.StatusDescription = message; progressRecord.PercentComplete = percentage; progressRecord.RecordType = ProgressRecordType.Processing; WriteProgress(progressRecord); } }; var warningsShown = new List <string>(); applyingInformation.MessagesDelegate = (message, type) => { switch (type) { case ProvisioningMessageType.Warning: { if (!warningsShown.Contains(message)) { WriteWarning(message); warningsShown.Add(message); } break; } case ProvisioningMessageType.Progress: { if (message != null) { var activity = message; if (message.IndexOf("|") > -1) { var messageSplitted = message.Split('|'); if (messageSplitted.Length == 4) { var current = double.Parse(messageSplitted[2]); var total = double.Parse(messageSplitted[3]); subProgressRecord.RecordType = ProgressRecordType.Processing; subProgressRecord.Activity = string.IsNullOrEmpty(messageSplitted[0]) ? "-" : messageSplitted[0]; subProgressRecord.StatusDescription = string.IsNullOrEmpty(messageSplitted[1]) ? "-" : messageSplitted[1]; subProgressRecord.PercentComplete = Convert.ToInt32((100 / total) * current); WriteProgress(subProgressRecord); } else { subProgressRecord.Activity = "Processing"; subProgressRecord.RecordType = ProgressRecordType.Processing; subProgressRecord.StatusDescription = activity; subProgressRecord.PercentComplete = 0; WriteProgress(subProgressRecord); } } else { subProgressRecord.Activity = "Processing"; subProgressRecord.RecordType = ProgressRecordType.Processing; subProgressRecord.StatusDescription = activity; subProgressRecord.PercentComplete = 0; WriteProgress(subProgressRecord); } } break; } case ProvisioningMessageType.Completed: { WriteProgress(new ProgressRecord(1, message, " ") { RecordType = ProgressRecordType.Completed }); break; } } }; applyingInformation.OverwriteSystemPropertyBagValues = OverwriteSystemPropertyBagValues; applyingInformation.IgnoreDuplicateDataRowErrors = IgnoreDuplicateDataRowErrors; applyingInformation.ClearNavigation = ClearNavigation; applyingInformation.ProvisionContentTypesToSubWebs = ProvisionContentTypesToSubWebs; applyingInformation.ProvisionFieldsToSubWebs = ProvisionFieldsToSubWebs; #if !ONPREMISES using (var provisioningContext = new PnPProvisioningContext((resource, scope) => { // Get Azure AD Token if (PnPConnection.CurrentConnection != null) { var graphAccessToken = PnPConnection.CurrentConnection.TryGetAccessToken(Enums.TokenAudience.MicrosoftGraph); if (graphAccessToken != null) { // Authenticated using -Graph or using another way to retrieve the accesstoken with Connect-PnPOnline return(Task.FromResult(graphAccessToken)); } } if (PnPConnection.CurrentConnection.PSCredential != null) { // Using normal credentials return(Task.FromResult(TokenHandler.AcquireToken(resource, null))); } else { // No token... return(null); } })) { #endif SelectedWeb.ApplyProvisioningTemplate(provisioningTemplate, applyingInformation); #if !ONPREMISES } #endif WriteProgress(new ProgressRecord(0, $"Applying template to {SelectedWeb.Url}", " ") { RecordType = ProgressRecordType.Completed }); }
protected override void ExecuteCmdlet() { SelectedWeb.EnsureProperty(w => w.Url); bool templateFromFileSystem = !Path.ToLower().StartsWith("http"); FileConnectorBase fileConnector; string templateFileName = System.IO.Path.GetFileName(Path); if (templateFromFileSystem) { if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } FileInfo fileInfo = new FileInfo(Path); fileConnector = new FileSystemConnector(fileInfo.DirectoryName, ""); } else { Uri fileUri = new Uri(Path); var webUrl = Microsoft.SharePoint.Client.Web.WebUrlFromFolderUrlDirect(ClientContext, fileUri); var templateContext = ClientContext.Clone(webUrl.ToString()); string library = Path.ToLower().Replace(templateContext.Url.ToLower(), "").TrimStart('/'); int idx = library.IndexOf("/"); library = library.Substring(0, idx); fileConnector = new SharePointConnector(templateContext, templateContext.Url, library); } XMLTemplateProvider provider; ProvisioningTemplate provisioningTemplate; Stream stream = fileConnector.GetFileStream(templateFileName); var isOpenOfficeFile = FileUtilities.IsOpenOfficeFile(stream); if (isOpenOfficeFile) { var openXmlConnector = new OpenXMLConnector(templateFileName, fileConnector); provider = new XMLOpenXMLTemplateProvider(openXmlConnector); if (!String.IsNullOrEmpty(openXmlConnector.Info?.Properties?.TemplateFileName)) { templateFileName = openXmlConnector.Info.Properties.TemplateFileName; } else { templateFileName = templateFileName.Substring(0, templateFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml"; } } else { if (templateFromFileSystem) { provider = new XMLFileSystemTemplateProvider(fileConnector.Parameters[FileConnectorBase.CONNECTIONSTRING] + "", ""); } else { throw new NotSupportedException("Only .pnp package files are supported from a SharePoint library"); } } provisioningTemplate = provider.GetTemplate(templateFileName, TemplateProviderExtensions); if (provisioningTemplate == null) { return; } GetSiteTemplate.SetTemplateMetadata(provisioningTemplate, TemplateDisplayName, TemplateImagePreviewUrl, TemplateProperties); provider.SaveAs(provisioningTemplate, templateFileName, TemplateProviderExtensions); }
protected void cblProduct_SelectedIndexChanged(object sender, EventArgs e) { ltrMessage.Text = ""; cbxProductType.Checked = false; cbxWarranty.Checked = false; cbxTerm.Checked = false; cbxPeriod.Checked = false; cblProductType.Items.Clear(); cblWarranty.Items.Clear(); cblTerm.Items.Clear(); cblPeriod.Items.Clear(); try { foreach (ListItem item in rblProduct.Items) { if (item.Selected) { List <Product> products = SharePointConnector.GetProductTypes(item.Value, rblCreditType.SelectedValue); List <Warranty> warranties = SharePointConnector.GetWarranties(item.Value, rblCreditType.SelectedValue); List <Term> terms = SharePointConnector.GetTerms(item.Value, rblCreditType.SelectedValue, null, rblBanx.SelectedValue); List <Period> periods = SharePointConnector.GetPeriods(item.Value, rblCreditType.SelectedValue, null, rblBanx.SelectedValue); cblProductType.Items.Add(new ListItem(item.Value, "", false)); cblWarranty.Items.Add(new ListItem(item.Value, "", false)); cblTerm.Items.Add(new ListItem(item.Value, "", false)); cblPeriod.Items.Add(new ListItem(item.Value, "", false)); foreach (Product product in products) { cblProductType.Items.Add(new ListItem(product.Name, product.Id.ToString())); } foreach (Warranty warranty in warranties) { cblWarranty.Items.Add(new ListItem(warranty.Name, warranty.Id.ToString())); } foreach (Term term in terms) { cblTerm.Items.Add(new ListItem(term.Display, term.Name)); } foreach (Period period in periods) { cblPeriod.Items.Add(new ListItem(period.Display, period.Name)); } } } } catch (Exception ex) { System.Web.UI.LiteralControl errorMessage = new System.Web.UI.LiteralControl(); errorMessage.Text = ex.Message; ltrMessage.Text = ex.Message; } }
protected override void OnInit(EventArgs e) { base.OnInit(e); isUserContentEditor = SharePointConnector.IsContentEditor(); }
protected void ddlProduct_SelectedIndexChanged(object sender, EventArgs e) { //System.Threading.Thread.Sleep(1000); try { if (SharePointConnector.HasForeignCurrency( ddlProduct.SelectedValue, rblCreditType.SelectedValue, ddlSegmentType.SelectedItem.Value)) { rblCurrency.Enabled = true; rblCurrency.Focus(); } else { rblCurrency.Enabled = false; rblCurrency.SelectedIndex = 0; ddlProductType.Focus(); } ddlProductType.DataSource = SharePointConnector.GetProductTypes(ddlProduct.SelectedValue, rblCreditType.SelectedValue); ddlProductType.DataTextField = "Name"; ddlProductType.DataValueField = "Id"; ddlProductType.DataBind(); ddlProductType.Items.Insert(0, new ListItem("(Seleccione el tipo de producto)", string.Empty)); ddlProductType.SelectedIndex = 0; ddlWarranty.DataSource = SharePointConnector.GetWarranties(ddlProduct.SelectedValue, rblCreditType.SelectedValue); ddlWarranty.DataTextField = "Name"; ddlWarranty.DataValueField = "Id"; ddlWarranty.DataBind(); ddlWarranty.Items.Insert(0, new ListItem("(Seleccione la garantía)", string.Empty)); ddlWarranty.SelectedIndex = 0; ddlTerm.DataSource = SharePointConnector.GetTerms(ddlProduct.SelectedValue, rblCreditType.SelectedValue, txbClientBirthdate.Text, null); ddlTerm.DataTextField = "Display"; ddlTerm.DataValueField = "Name"; ddlTerm.DataBind(); ddlTerm.Items.Insert(0, new ListItem("(Seleccione el plazo)", string.Empty)); ddlTerm.SelectedIndex = 0; ddlPeriodFixed.DataSource = SharePointConnector.GetPeriods(ddlProduct.SelectedValue, rblCreditType.SelectedValue, txbClientBirthdate.Text, null); ddlPeriodFixed.DataTextField = "Display"; ddlPeriodFixed.DataValueField = "Name"; ddlPeriodFixed.DataBind(); ddlPeriodFixed.Items.Insert(0, new ListItem("(Seleccione el período)", string.Empty)); ddlPeriodFixed.SelectedIndex = 0; ddlMargin.DataSource = SharePointConnector.GetMargins(ddlProduct.SelectedValue, ddlSegmentType.SelectedItem.Value, rblCreditType.SelectedValue); ddlMargin.DataTextField = "Name"; ddlMargin.DataValueField = "Id"; ddlMargin.DataBind(); ddlMargin.Items.Insert(0, new ListItem("(Seleccione el margen de negociación)", string.Empty)); ddlMargin.SelectedIndex = 0; } catch (Exception ex) { System.Web.UI.LiteralControl errorMessage = new System.Web.UI.LiteralControl(); errorMessage.Text = ex.Message; this.Controls.Clear(); this.Controls.Add(errorMessage); } }
public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo) { // Load object if not there bool executeQueryNeeded = false; if (!web.IsPropertyAvailable("Url")) { web.Context.Load(web, w => w.Url); executeQueryNeeded = true; } if (!web.IsPropertyAvailable("MasterUrl")) { web.Context.Load(web, w => w.MasterUrl); executeQueryNeeded = true; } #if !CLIENTSDKV15 if (!web.IsPropertyAvailable("AlternateCssUrl")) { web.Context.Load(web, w => w.AlternateCssUrl); executeQueryNeeded = true; } if (!web.IsPropertyAvailable("SiteLogoUrl")) { web.Context.Load(web, w => w.SiteLogoUrl); executeQueryNeeded = true; } #endif if (executeQueryNeeded) { web.Context.ExecuteQueryRetry(); } // Information coming from the site template.ComposedLook.MasterPage = Tokenize(web.MasterUrl, web.Url); #if !CLIENTSDKV15 template.ComposedLook.AlternateCSS = Tokenize(web.AlternateCssUrl, web.Url); template.ComposedLook.SiteLogo = Tokenize(web.SiteLogoUrl, web.Url); #else template.ComposedLook.AlternateCSS = null; template.ComposedLook.SiteLogo = null; #endif var theme = web.GetCurrentComposedLook(); if (theme != null) { if (creationInfo != null) { // Don't exclude the DesignPreviewThemedCssFolderUrl property bag, if any creationInfo.PropertyBagPropertiesToPreserve.Add("DesignPreviewThemedCssFolderUrl"); } template.ComposedLook.Name = theme.Name; if (theme.IsCustomComposedLook) { if (creationInfo != null && creationInfo.PersistComposedLookFiles && creationInfo.FileConnector != null) { Site site = (web.Context as ClientContext).Site; if (!site.IsObjectPropertyInstantiated("Url")) { web.Context.Load(site); web.Context.ExecuteQueryRetry(); } // Let's create a SharePoint connector since our files anyhow are in SharePoint at this moment SharePointConnector spConnector = new SharePointConnector(web.Context, web.Url, "dummy"); // to get files from theme catalog we need a connector linked to the root site SharePointConnector spConnectorRoot; if (!site.Url.Equals(web.Url, StringComparison.InvariantCultureIgnoreCase)) { spConnectorRoot = new SharePointConnector(web.Context.Clone(site.Url), site.Url, "dummy"); } else { spConnectorRoot = spConnector; } // Download the theme/branding specific files DownLoadFile(spConnector, spConnectorRoot, creationInfo.FileConnector, web.Url, web.AlternateCssUrl); DownLoadFile(spConnector, spConnectorRoot, creationInfo.FileConnector, web.Url, web.SiteLogoUrl); DownLoadFile(spConnector, spConnectorRoot, creationInfo.FileConnector, web.Url, theme.BackgroundImage); DownLoadFile(spConnector, spConnectorRoot, creationInfo.FileConnector, web.Url, theme.Theme); DownLoadFile(spConnector, spConnectorRoot, creationInfo.FileConnector, web.Url, theme.Font); } template.ComposedLook.BackgroundFile = FixFileUrl(Tokenize(theme.BackgroundImage, web.Url)); template.ComposedLook.ColorFile = FixFileUrl(Tokenize(theme.Theme, web.Url)); template.ComposedLook.FontFile = FixFileUrl(Tokenize(theme.Font, web.Url)); // Create file entries for the custom theme files if (!string.IsNullOrEmpty(template.ComposedLook.BackgroundFile)) { template.Files.Add(GetComposedLookFile(template.ComposedLook.BackgroundFile)); } if (!string.IsNullOrEmpty(template.ComposedLook.ColorFile)) { template.Files.Add(GetComposedLookFile(template.ComposedLook.ColorFile)); } if (!string.IsNullOrEmpty(template.ComposedLook.FontFile)) { template.Files.Add(GetComposedLookFile(template.ComposedLook.FontFile)); } if (!string.IsNullOrEmpty(template.ComposedLook.SiteLogo)) { template.Files.Add(GetComposedLookFile(template.ComposedLook.SiteLogo)); } // If a base template is specified then use that one to "cleanup" the generated template model if (creationInfo != null && creationInfo.BaseTemplate != null) { template = CleanupEntities(template, creationInfo.BaseTemplate); } } else { template.ComposedLook.BackgroundFile = ""; template.ComposedLook.ColorFile = ""; template.ComposedLook.FontFile = ""; } } else { template.ComposedLook = null; } if (creationInfo != null && creationInfo.BaseTemplate != null) { template = CleanupEntities(template, creationInfo.BaseTemplate); } return(template); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] ApplyTemplateRequest request, TraceWriter log) { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); string siteUrl = request.SiteURL; RedirectAssembly(); try { if (string.IsNullOrWhiteSpace(request.SiteURL)) { throw new ArgumentException("Parameter cannot be null", "SiteURL"); } if (string.IsNullOrWhiteSpace(request.TemplateURL)) { throw new ArgumentException("Parameter cannot be null", "TemplateURL"); } string templateUrl = request.TemplateURL.Trim(); // remove potential spaces/line breaks var clientContext = await ConnectADAL.GetClientContext(siteUrl, log); var web = clientContext.Web; web.Lists.EnsureSiteAssetsLibrary(); clientContext.ExecuteQueryRetry(); Uri templateFileUri = new Uri(templateUrl); var webUrl = Web.WebUrlFromFolderUrlDirect(clientContext, templateFileUri); var templateContext = clientContext.Clone(webUrl.ToString()); var library = templateUrl.ToLower().Replace(templateContext.Url.ToLower(), "").TrimStart('/'); var idx = library.IndexOf("/", StringComparison.Ordinal); library = library.Substring(0, idx); // This syntax creates a SharePoint connector regardless we have the -InputInstance argument or not var fileConnector = new SharePointConnector(templateContext, templateContext.Url, library); string templateFileName = Path.GetFileName(templateUrl); XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(templateFileName, fileConnector)); templateFileName = templateFileName.Substring(0, templateFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml"; var provisioningTemplate = provider.GetTemplate(templateFileName, new ITemplateProviderExtension[0]); if (request.Parameters != null) { foreach (var parameter in request.Parameters) { provisioningTemplate.Parameters[parameter.Key] = parameter.Value; } } provisioningTemplate.Connector = provider.Connector; TokenReplaceCustomAction(provisioningTemplate, clientContext.Web); ProvisioningTemplateApplyingInformation applyingInformation = new ProvisioningTemplateApplyingInformation() { ProgressDelegate = (message, progress, total) => { log.Info(String.Format("{0:00}/{1:00} - {2}", progress, total, message)); }, MessagesDelegate = (message, messageType) => { log.Info(String.Format("{0} - {1}", messageType, message)); } }; clientContext.Web.ApplyProvisioningTemplate(provisioningTemplate, applyingInformation); stopWatch.Stop(); var applyTemplateResponse = new ApplyTemplateResponse { TemplateApplied = true, ElapsedMilliseconds = stopWatch.ElapsedMilliseconds }; return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new ObjectContent <ApplyTemplateResponse>(applyTemplateResponse, new JsonMediaTypeFormatter()) })); } catch (Exception e) { stopWatch.Stop(); log.Error($"Error: {e.Message}\n\n{e.StackTrace}"); return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) { Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter()) })); } }
public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo) { using (var scope = new PnPMonitoredScope(this.Name)) { // Load object if not there #if !CLIENTSDKV15 web.EnsureProperties(w => w.Url, w => w.MasterUrl, w => w.AlternateCssUrl, w => w.SiteLogoUrl); #else web.EnsureProperties(w => w.Url, w => w.MasterUrl); #endif // Information coming from the site template.ComposedLook.MasterPage = Tokenize(web.MasterUrl, web.Url); #if !CLIENTSDKV15 template.ComposedLook.AlternateCSS = Tokenize(web.AlternateCssUrl, web.Url); template.ComposedLook.SiteLogo = Tokenize(web.SiteLogoUrl, web.Url); #else template.ComposedLook.AlternateCSS = null; template.ComposedLook.SiteLogo = null; #endif scope.LogInfo(CoreResources.Provisioning_ObjectHandlers_ComposedLooks_ExtractObjects_Retrieving_current_composed_look); Site site = (web.Context as ClientContext).Site; if (!site.IsObjectPropertyInstantiated("Url")) { web.Context.Load(site); web.Context.ExecuteQueryRetry(); } SharePointConnector spConnector = new SharePointConnector(web.Context, web.Url, "dummy"); // to get files from theme catalog we need a connector linked to the root site SharePointConnector spConnectorRoot; if (!site.Url.Equals(web.Url, StringComparison.InvariantCultureIgnoreCase)) { spConnectorRoot = new SharePointConnector(web.Context.Clone(site.Url), site.Url, "dummy"); } else { spConnectorRoot = spConnector; } // Check if we have composed look info in the property bag, if so, use that, otherwise try to detect the current composed look if (web.PropertyBagContainsKey("_PnP_ProvisioningTemplateComposedLookInfo")) { scope.LogInfo(CoreResources.Provisioning_ObjectHandlers_ComposedLooks_ExtractObjects_Using_ComposedLookInfoFromPropertyBag); try { var composedLook = JsonConvert.DeserializeObject <ComposedLook>(web.GetPropertyBagValueString("_PnP_ProvisioningTemplateComposedLookInfo", "")); if (composedLook.Name == null || composedLook.BackgroundFile == null || composedLook.FontFile == null || composedLook.MasterPage == null || composedLook.SiteLogo == null) { scope.LogError(CoreResources.Provisioning_ObjectHandlers_ComposedLooks_ExtractObjects_ComposedLookInfoFailedToDeserialize); throw new JsonSerializationException(); } composedLook.AlternateCSS = Tokenize(composedLook.AlternateCSS, web.Url); composedLook.BackgroundFile = Tokenize(composedLook.BackgroundFile, web.Url); composedLook.MasterPage = Tokenize(composedLook.MasterPage, web.Url); composedLook.SiteLogo = Tokenize(composedLook.SiteLogo, web.Url); composedLook.FontFile = Tokenize(composedLook.FontFile, web.Url); composedLook.ColorFile = Tokenize(composedLook.ColorFile, web.Url); template.ComposedLook = composedLook; if (creationInfo != null && creationInfo.PersistComposedLookFiles && creationInfo.FileConnector != null) { scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ComposedLooks_ExtractObjects_Creating_SharePointConnector); // Let's create a SharePoint connector since our files anyhow are in SharePoint at this moment // Download the theme/branding specific files #if !CLIENTSDKV15 DownLoadFile(spConnector, spConnectorRoot, creationInfo.FileConnector, web.Url, web.AlternateCssUrl, scope); DownLoadFile(spConnector, spConnectorRoot, creationInfo.FileConnector, web.Url, web.SiteLogoUrl, scope); #endif TokenParser parser = new TokenParser(web, template); DownLoadFile(spConnector, spConnectorRoot, creationInfo.FileConnector, web.Url, parser.ParseString(composedLook.BackgroundFile), scope); DownLoadFile(spConnector, spConnectorRoot, creationInfo.FileConnector, web.Url, parser.ParseString(composedLook.ColorFile), scope); DownLoadFile(spConnector, spConnectorRoot, creationInfo.FileConnector, web.Url, parser.ParseString(composedLook.FontFile), scope); } // Create file entries for the custom theme files if (!string.IsNullOrEmpty(template.ComposedLook.BackgroundFile)) { var f = GetComposedLookFile(template.ComposedLook.BackgroundFile); f.Folder = Tokenize(f.Folder, web.Url); template.Files.Add(f); } if (!string.IsNullOrEmpty(template.ComposedLook.ColorFile)) { var f = GetComposedLookFile(template.ComposedLook.ColorFile); f.Folder = Tokenize(f.Folder, web.Url); template.Files.Add(f); } if (!string.IsNullOrEmpty(template.ComposedLook.FontFile)) { var f = GetComposedLookFile(template.ComposedLook.FontFile); f.Folder = Tokenize(f.Folder, web.Url); template.Files.Add(f); } if (!string.IsNullOrEmpty(template.ComposedLook.SiteLogo)) { var f = GetComposedLookFile(template.ComposedLook.SiteLogo); f.Folder = Tokenize(f.Folder, web.Url); template.Files.Add(f); } } catch (JsonSerializationException) { // cannot deserialize the object, fall back to composed look detection template = DetectComposedLook(web, template, creationInfo, scope, spConnector, spConnectorRoot); } } else { template = DetectComposedLook(web, template, creationInfo, scope, spConnector, spConnectorRoot); } if (creationInfo != null && creationInfo.BaseTemplate != null) { template = CleanupEntities(template, creationInfo.BaseTemplate); } } return(template); }
private string LoadPropertyDetails() { string assetId = this.Request.QueryString["AssetId"]; FinancedEstate financedProperty = SharePointConnector.GetFinancedProperty(int.Parse(assetId)); string latitude = ""; string longitude = ""; try { if (!string.IsNullOrEmpty(financedProperty.Latlong)) { latitude = financedProperty.Latlong.Split('/')[0].Trim(); longitude = financedProperty.Latlong.Split('/')[1].Trim(); } } catch {} string mapScript = string.Format( "function initMap() {{" + "var map;" + "var bounds = new google.maps.LatLngBounds();" + "var mapOptions = {{ mapTypeId: 'roadmap' }};" + "map = new google.maps.Map(document.getElementById('mapCanvas'), mapOptions); map.setTilt(50);" + "var markers = [['{0}',{1},{2}]];" + "var infoWindowContent = [['<div class=info_content>'+'<h3>{0}</h3>'+'<p>{3}</p>'+'</div>']];" + "var infoWindow = new google.maps.InfoWindow(), marker, i; " + "for( i = 0; i < markers.length; i++ ) {{" + "var position = new google.maps.LatLng(markers[i][1], markers[i][2]);" + "bounds.extend(position);" + "marker = new google.maps.Marker({{position: position,map: map,icon: '/Inmuebles%20Financiados%20Imgenes/000_icon.png',title: markers[i][0]}});" + "google.maps.event.addListener(marker, 'click', (function(marker, i) {{" + "return function() {{infoWindow.setContent(infoWindowContent[i][0]);infoWindow.open(map, marker);}}" + "}})(marker, i));map.fitBounds(bounds);}}" + "var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {{" + "this.setZoom(17);" + "google.maps.event.removeListener(boundsListener);" + "}});" + "}}" + "google.maps.event.addDomListener(window, 'load', initMap);", financedProperty.Name, latitude, longitude, financedProperty.Address); string accordionscript = "var acc = document.getElementsByClassName('accordion');" + "var i;" + "for (i = 0; i < acc.length; i++) {{" + "acc[i].onclick = function () {{" + "this.classList.toggle('active');" + "var panel = this.nextElementSibling;" + "if (panel.style.maxHeight) {{panel.style.maxHeight = null;}}" + "else {{panel.style.maxHeight = panel.scrollHeight + 'px';}}" + "}}}}"; string script = accordionscript; if (!string.IsNullOrEmpty(latitude) && !string.IsNullOrEmpty(longitude)) { script = mapScript + accordionscript; } string formatedResult = string.Format( "<div style='border-bottom: 1px solid #a3291c;'>" + "<div style='padding-bottom: 10px;'><h2>{6}</h2><p>{0}</p></div>" + "<a href='javascript:;' class='accordion'>Características</a>" + "<div class='panel'><p>{1}</p><p><a href='{7}'>Descargue el folleto</a><p></div>" + "<a href='javascript:;' class='accordion'>Precio</a>" + "<div class='panel'><p>{2}</p></div>" + "</div>" + "<div style='padding-bottom: 10px;'><h2>Contacto</h2><p>{3}</p><p><a href='javascript:;' onclick=\"{8}\">Quiero que me contacten</a></p></div>" + "<div style='background-color: #b72718;'><p><b>Dirección</b><br />{4}</p></div>" + "<a href='javascript:;' class='accordion'>Ubicación</a>" + "<div class='panel'><div id='mapContainer'><div id='mapCanvas'></div></div></div>" + "<script>{5}</script>", financedProperty.City, financedProperty.Description, financedProperty.Price == 0 ? "Sin precio asignado" : string.Format("{0:0,0.00}", financedProperty.Price) + " " + financedProperty.Currency, financedProperty.FullContactInfo(), financedProperty.Address, script, financedProperty.Name, financedProperty.Attached, "OpenInDialog(500,350,true,true,true,'/Paginas/Formularios/financiamientosofertas2.aspx?" + "AssetCode=" + financedProperty.Code + "','Quiero que me contacten');"); return(formatedResult); }
public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo) { using (var scope = new PnPMonitoredScope(this.Name)) { scope.LogInfo(CoreResources.Provisioning_ObjectHandlers_ComposedLooks_ExtractObjects_Retrieving_current_composed_look); // Ensure that we have URL property loaded for web and site web.EnsureProperty(w => w.Url); Site site = (web.Context as ClientContext).Site; site.EnsureProperty(s => s.Url); SharePointConnector spConnector = new SharePointConnector(web.Context, web.Url, "dummy"); // to get files from theme catalog we need a connector linked to the root site SharePointConnector spConnectorRoot; if (!site.Url.Equals(web.Url, StringComparison.InvariantCultureIgnoreCase)) { spConnectorRoot = new SharePointConnector(web.Context.Clone(site.Url), site.Url, "dummy"); } else { spConnectorRoot = spConnector; } // Check if we have composed look info in the property bag, if so, use that, otherwise try to detect the current composed look if (web.PropertyBagContainsKey("_PnP_ProvisioningTemplateComposedLookInfo")) { scope.LogInfo(CoreResources.Provisioning_ObjectHandlers_ComposedLooks_ExtractObjects_Using_ComposedLookInfoFromPropertyBag); try { var composedLook = JsonConvert.DeserializeObject <ComposedLook>(web.GetPropertyBagValueString("_PnP_ProvisioningTemplateComposedLookInfo", "")); if (composedLook.Name == null) { scope.LogError(CoreResources.Provisioning_ObjectHandlers_ComposedLooks_ExtractObjects_ComposedLookInfoFailedToDeserialize); throw new JsonSerializationException(); } composedLook.BackgroundFile = Tokenize(composedLook.BackgroundFile, web.Url); composedLook.FontFile = Tokenize(composedLook.FontFile, web.Url); composedLook.ColorFile = Tokenize(composedLook.ColorFile, web.Url); template.ComposedLook = composedLook; if (!web.IsSubSite() && creationInfo != null && creationInfo.PersistBrandingFiles && creationInfo.FileConnector != null) { scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ComposedLooks_ExtractObjects_Creating_SharePointConnector); // Let's create a SharePoint connector since our files anyhow are in SharePoint at this moment TokenParser parser = new TokenParser(web, template); DownLoadFile(spConnector, spConnectorRoot, creationInfo.FileConnector, web.Url, parser.ParseString(composedLook.BackgroundFile), scope); DownLoadFile(spConnector, spConnectorRoot, creationInfo.FileConnector, web.Url, parser.ParseString(composedLook.ColorFile), scope); DownLoadFile(spConnector, spConnectorRoot, creationInfo.FileConnector, web.Url, parser.ParseString(composedLook.FontFile), scope); } // Create file entries for the custom theme files if (!string.IsNullOrEmpty(template.ComposedLook.BackgroundFile)) { var f = GetComposedLookFile(template.ComposedLook.BackgroundFile); f.Folder = Tokenize(f.Folder, web.Url); template.Files.Add(f); } if (!string.IsNullOrEmpty(template.ComposedLook.ColorFile)) { var f = GetComposedLookFile(template.ComposedLook.ColorFile); f.Folder = Tokenize(f.Folder, web.Url); template.Files.Add(f); } if (!string.IsNullOrEmpty(template.ComposedLook.FontFile)) { var f = GetComposedLookFile(template.ComposedLook.FontFile); f.Folder = Tokenize(f.Folder, web.Url); template.Files.Add(f); } } catch (JsonSerializationException) { // cannot deserialize the object, fall back to composed look detection template = DetectComposedLook(web, template, creationInfo, scope, spConnector, spConnectorRoot); } } else { template = DetectComposedLook(web, template, creationInfo, scope, spConnector, spConnectorRoot); } if (creationInfo != null && creationInfo.BaseTemplate != null) { template = CleanupEntities(template, creationInfo.BaseTemplate); } } return(template); }
protected override void ExecuteCmdlet() { SelectedWeb.EnsureProperty(w => w.Url); bool templateFromFileSystem = !Path.ToLower().StartsWith("http"); FileConnectorBase fileConnector; string templateFileName = System.IO.Path.GetFileName(Path); if (templateFromFileSystem) { if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } if (!string.IsNullOrEmpty(ResourceFolder)) { if (!System.IO.Path.IsPathRooted(ResourceFolder)) { ResourceFolder = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, ResourceFolder); } } var fileInfo = new FileInfo(Path); fileConnector = new FileSystemConnector(fileInfo.DirectoryName, ""); } else { Uri fileUri = new Uri(Path); var webUrl = Microsoft.SharePoint.Client.Web.WebUrlFromFolderUrlDirect(ClientContext, fileUri); var templateContext = ClientContext.Clone(webUrl.ToString()); var library = Path.ToLower().Replace(templateContext.Url.ToLower(), "").TrimStart('/'); var idx = library.IndexOf("/", StringComparison.Ordinal); library = library.Substring(0, idx); // This syntax creates a SharePoint connector regardless we have the -InputInstance argument or not fileConnector = new SharePointConnector(templateContext, templateContext.Url, library); } ProvisioningTemplate provisioningTemplate; // If we don't have the -InputInstance parameter, we load the template from the source connector if (InputInstance == null) { Stream stream = fileConnector.GetFileStream(templateFileName); var isOpenOfficeFile = IsOpenOfficeFile(stream); XMLTemplateProvider provider; if (isOpenOfficeFile) { provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(templateFileName, fileConnector)); templateFileName = templateFileName.Substring(0, templateFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml"; } else { if (templateFromFileSystem) { provider = new XMLFileSystemTemplateProvider(fileConnector.Parameters[FileConnectorBase.CONNECTIONSTRING] + "", ""); } else { throw new NotSupportedException("Only .pnp package files are supported from a SharePoint library"); } } provisioningTemplate = provider.GetTemplate(templateFileName, TemplateProviderExtensions); if (provisioningTemplate == null) { // If we don't have the template, raise an error and exit WriteError(new ErrorRecord(new Exception("The -Path parameter targets an invalid repository or template object."), "WRONG_PATH", ErrorCategory.SyntaxError, null)); return; } if (isOpenOfficeFile) { provisioningTemplate.Connector = provider.Connector; } else { if (ResourceFolder != null) { var fileSystemConnector = new FileSystemConnector(ResourceFolder, ""); provisioningTemplate.Connector = fileSystemConnector; } else { provisioningTemplate.Connector = provider.Connector; } } } // Otherwise we use the provisioning template instance provided through the -InputInstance parameter else { provisioningTemplate = InputInstance; if (ResourceFolder != null) { var fileSystemConnector = new FileSystemConnector(ResourceFolder, ""); provisioningTemplate.Connector = fileSystemConnector; } else { provisioningTemplate.Connector = fileConnector; } } if (Parameters != null) { foreach (var parameter in Parameters.Keys) { if (provisioningTemplate.Parameters.ContainsKey(parameter.ToString())) { provisioningTemplate.Parameters[parameter.ToString()] = Parameters[parameter].ToString(); } else { provisioningTemplate.Parameters.Add(parameter.ToString(), Parameters[parameter].ToString()); } } } var applyingInformation = new ProvisioningTemplateApplyingInformation(); if (MyInvocation.BoundParameters.ContainsKey("Handlers")) { applyingInformation.HandlersToProcess = Handlers; } if (MyInvocation.BoundParameters.ContainsKey("ExcludeHandlers")) { foreach (var handler in (Handlers[])Enum.GetValues(typeof(Handlers))) { if (!ExcludeHandlers.Has(handler) && handler != Handlers.All) { Handlers = Handlers | handler; } } applyingInformation.HandlersToProcess = Handlers; } if (ExtensibilityHandlers != null) { applyingInformation.ExtensibilityHandlers = ExtensibilityHandlers.ToList(); } applyingInformation.ProgressDelegate = (message, step, total) => { WriteProgress(new ProgressRecord(0, $"Applying template to {SelectedWeb.Url}", message) { PercentComplete = (100 / total) * step }); }; applyingInformation.MessagesDelegate = (message, type) => { if (type == ProvisioningMessageType.Warning) { WriteWarning(message); } }; applyingInformation.OverwriteSystemPropertyBagValues = OverwriteSystemPropertyBagValues; SelectedWeb.ApplyProvisioningTemplate(provisioningTemplate, applyingInformation); }
protected void btnShowReport_Click(object sender, EventArgs e) { if (rblReportType.SelectedIndex != -1 && rblCreditType.SelectedIndex != -1 && rblCurrency.SelectedIndex != -1 && rblBanx.SelectedIndex != -1 && cblSegment.SelectedIndex != -1 && rblProduct.SelectedIndex != -1 && cblProductType.SelectedIndex != -1 && cblWarranty.SelectedIndex != -1 && cblTerm.SelectedIndex != -1 && cblPeriod.SelectedIndex != -1) { if (isUserContentEditor) { btnExportReport.Visible = true; } dgrReport.Visible = true; ltrMessage.Text = ""; List <string[]> reportTypeList = new List <string[]>(); List <string[]> currencyList = new List <string[]>(); List <string[]> banxList = new List <string[]>(); List <string[]> creditTypeList = new List <string[]>(); List <string[]> segmentList = new List <string[]>(); List <string[]> productList = new List <string[]>(); List <string[]> productTypeList = new List <string[]>(); List <string[]> warrantyList = new List <string[]>(); List <string[]> termList = new List <string[]>(); List <string[]> periodList = new List <string[]>(); foreach (ListItem item in rblReportType.Items) { if (item.Selected) { reportTypeList.Add(new string[] { item.Text, item.Value }); } } foreach (ListItem item in rblCurrency.Items) { if (item.Selected) { currencyList.Add(new string[] { item.Text, item.Value }); } } foreach (ListItem item in rblBanx.Items) { if (item.Selected) { banxList.Add(new string[] { item.Text, item.Value }); } } foreach (ListItem item in rblCreditType.Items) { if (item.Selected) { creditTypeList.Add(new string[] { item.Text, item.Value }); } } foreach (ListItem item in cblSegment.Items) { if (item.Selected) { string itemText = item.Text.Remove(item.Text.LastIndexOf('|') - 1); string itemLevel = item.Text.Substring(item.Text.LastIndexOf('|') + 2); segmentList.Add(new string[] { itemText, item.Value, itemLevel }); } } foreach (ListItem item in rblProduct.Items) { if (item.Selected) { productList.Add(new string[] { item.Text, item.Value }); } } foreach (ListItem item in cblProductType.Items) { if (item.Selected) { productTypeList.Add(new string[] { item.Text, item.Value }); } } foreach (ListItem item in cblWarranty.Items) { if (item.Selected) { warrantyList.Add(new string[] { item.Text, item.Value }); } } foreach (ListItem item in cblTerm.Items) { if (item.Selected) { termList.Add(new string[] { item.Text, item.Value }); } } foreach (ListItem item in cblPeriod.Items) { if (item.Selected) { periodList.Add(new string[] { item.Text, item.Value }); } } dgrReport.DataSource = SharePointConnector.GetReportTableRates( reportTypeList, currencyList, banxList, creditTypeList, segmentList, productList, productTypeList, warrantyList, termList, periodList); dgrReport.DataBind(); } else { dgrReport.Visible = false; btnExportReport.Visible = false; ltrMessage.Text = "<strong style='color:#e82523'>Los filtros elegidos no son correctos.</strong>"; } }
protected override void ExecuteCmdlet() { SelectedWeb.EnsureProperty(w => w.Url); ProvisioningTemplate provisioningTemplate; FileConnectorBase fileConnector; if (MyInvocation.BoundParameters.ContainsKey("Path")) { bool templateFromFileSystem = !Path.ToLower().StartsWith("http"); string templateFileName = System.IO.Path.GetFileName(Path); if (templateFromFileSystem) { if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } if (!string.IsNullOrEmpty(ResourceFolder)) { if (!System.IO.Path.IsPathRooted(ResourceFolder)) { ResourceFolder = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, ResourceFolder); } } var fileInfo = new FileInfo(Path); fileConnector = new FileSystemConnector(fileInfo.DirectoryName, ""); } else { Uri fileUri = new Uri(Path); var webUrl = Microsoft.SharePoint.Client.Web.WebUrlFromFolderUrlDirect(ClientContext, fileUri); var templateContext = ClientContext.Clone(webUrl.ToString()); var library = Path.ToLower().Replace(templateContext.Url.ToLower(), "").TrimStart('/'); var idx = library.IndexOf("/", StringComparison.Ordinal); library = library.Substring(0, idx); // This syntax creates a SharePoint connector regardless we have the -InputInstance argument or not fileConnector = new SharePointConnector(templateContext, templateContext.Url, library); } // If we don't have the -InputInstance parameter, we load the template from the source connector Stream stream = fileConnector.GetFileStream(templateFileName); var isOpenOfficeFile = IsOpenOfficeFile(stream); XMLTemplateProvider provider; if (isOpenOfficeFile) { provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(templateFileName, fileConnector)); templateFileName = templateFileName.Substring(0, templateFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml"; } else { if (templateFromFileSystem) { provider = new XMLFileSystemTemplateProvider(fileConnector.Parameters[FileConnectorBase.CONNECTIONSTRING] + "", ""); } else { throw new NotSupportedException("Only .pnp package files are supported from a SharePoint library"); } } provisioningTemplate = provider.GetTemplate(templateFileName, TemplateProviderExtensions); if (provisioningTemplate == null) { // If we don't have the template, raise an error and exit WriteError(new ErrorRecord(new Exception("The -Path parameter targets an invalid repository or template object."), "WRONG_PATH", ErrorCategory.SyntaxError, null)); return; } if (isOpenOfficeFile) { provisioningTemplate.Connector = provider.Connector; } else { if (ResourceFolder != null) { var fileSystemConnector = new FileSystemConnector(ResourceFolder, ""); provisioningTemplate.Connector = fileSystemConnector; } else { provisioningTemplate.Connector = provider.Connector; } } } else { if (MyInvocation.BoundParameters.ContainsKey("GalleryTemplateId")) { provisioningTemplate = GalleryHelper.GetTemplate(GalleryTemplateId); } else { provisioningTemplate = InputInstance; } if (ResourceFolder != null) { var fileSystemConnector = new FileSystemConnector(ResourceFolder, ""); provisioningTemplate.Connector = fileSystemConnector; } else { if (Path != null) { if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } } else { Path = SessionState.Path.CurrentFileSystemLocation.Path; } var fileInfo = new FileInfo(Path); fileConnector = new FileSystemConnector(fileInfo.DirectoryName, ""); provisioningTemplate.Connector = fileConnector; } } if (Parameters != null) { foreach (var parameter in Parameters.Keys) { if (provisioningTemplate.Parameters.ContainsKey(parameter.ToString())) { provisioningTemplate.Parameters[parameter.ToString()] = Parameters[parameter].ToString(); } else { provisioningTemplate.Parameters.Add(parameter.ToString(), Parameters[parameter].ToString()); } } } var applyingInformation = new ProvisioningTemplateApplyingInformation(); if (MyInvocation.BoundParameters.ContainsKey("Handlers")) { applyingInformation.HandlersToProcess = Handlers; } if (MyInvocation.BoundParameters.ContainsKey("ExcludeHandlers")) { foreach (var handler in (Handlers[])Enum.GetValues(typeof(Handlers))) { if (!ExcludeHandlers.Has(handler) && handler != Handlers.All) { Handlers = Handlers | handler; } } applyingInformation.HandlersToProcess = Handlers; } if (ExtensibilityHandlers != null) { applyingInformation.ExtensibilityHandlers = ExtensibilityHandlers.ToList(); } applyingInformation.ProgressDelegate = (message, step, total) => { var percentage = Convert.ToInt32((100 / Convert.ToDouble(total)) * Convert.ToDouble(step)); progressRecord.Activity = $"Applying template to {SelectedWeb.Url}"; progressRecord.StatusDescription = message; progressRecord.PercentComplete = percentage; progressRecord.RecordType = ProgressRecordType.Processing; WriteProgress(progressRecord); }; applyingInformation.MessagesDelegate = (message, type) => { switch (type) { case ProvisioningMessageType.Warning: { WriteWarning(message); break; } case ProvisioningMessageType.Progress: { var activity = message; if (message.IndexOf("|") > -1) { var messageSplitted = message.Split('|'); if (messageSplitted.Length == 4) { var current = double.Parse(messageSplitted[2]); var total = double.Parse(messageSplitted[3]); subProgressRecord.RecordType = ProgressRecordType.Processing; subProgressRecord.Activity = messageSplitted[0]; subProgressRecord.StatusDescription = messageSplitted[1]; subProgressRecord.PercentComplete = Convert.ToInt32((100 / total) * current); WriteProgress(subProgressRecord); } else { subProgressRecord.Activity = "Processing"; subProgressRecord.RecordType = ProgressRecordType.Processing; subProgressRecord.StatusDescription = activity; subProgressRecord.PercentComplete = 0; WriteProgress(subProgressRecord); } } else { subProgressRecord.Activity = "Processing"; subProgressRecord.RecordType = ProgressRecordType.Processing; subProgressRecord.StatusDescription = activity; subProgressRecord.PercentComplete = 0; WriteProgress(subProgressRecord); } break; } case ProvisioningMessageType.Completed: { WriteProgress(new ProgressRecord(1, message, " ") { RecordType = ProgressRecordType.Completed }); break; } } }; applyingInformation.OverwriteSystemPropertyBagValues = OverwriteSystemPropertyBagValues; applyingInformation.IgnoreDuplicateDataRowErrors = IgnoreDuplicateDataRowErrors; applyingInformation.ClearNavigation = ClearNavigation; applyingInformation.ProvisionContentTypesToSubWebs = ProvisionContentTypesToSubWebs; SelectedWeb.ApplyProvisioningTemplate(provisioningTemplate, applyingInformation); WriteProgress(new ProgressRecord(0, $"Applying template to {SelectedWeb.Url}", " ") { RecordType = ProgressRecordType.Completed }); }
protected void btnShowRates_Click(object sender, EventArgs e) { try { pnlForm.Visible = false; pnlPrint.Visible = true; lblMessage.Visible = false; btnPrint.Visible = false; btnSaveAndPrint.Visible = true; Rate theRate = SharePointConnector.GetRates( rblCreditType.SelectedValue, int.Parse(ddlSegmentType.SelectedItem.Value), ddlProduct.SelectedValue, ddlProductType.SelectedItem.Text, SharePointConnector.IsBanxClient(txbClientBirthdate.Text), SharePointConnector.IsDisabledClient(rblDisabled.SelectedValue), SharePointConnector.IsCpopClient(rblCpop.SelectedValue), rblSector.SelectedValue, txbIvc.Text, txbIrt.Text, ddlMargin.SelectedItem.Text, ddlWarranty.SelectedItem.Text, ddlTerm.SelectedItem.Value, ddlPeriodFixed.SelectedItem.Value, rblCurrency.SelectedValue); if (theRate.RateFixed > 50.0) { ltrMessage.Text = "<table class='print' style='width:100%;padding:3em 12em;'>" + "<tr><td><span class='number' style='padding:20px;'>" + "LA TASA SOLICITADA NO APLICA.</span></td></tr></table>"; tblPrint.Visible = false; btnSaveAndPrint.Visible = false; return; } else if (rblCreditType.SelectedValue == "PERSONAL" && ddlProductType.SelectedItem.Text == "VISA INTERNACIONAL PAYBANX" && ddlWarranty.SelectedItem.Text.StartsWith("NO DEBIDAMENTE GARANTIZADO", StringComparison.CurrentCultureIgnoreCase)) { ltrMessage.Text = "<table class='print' style='width:100%;padding:3em 12em;'>" + "<tr><td><span class='number' style='padding:20px;'>" + "LA TASA SOLICITADA NO APLICA.</span></td></tr></table>"; tblPrint.Visible = false; btnSaveAndPrint.Visible = false; } else { ltrMessage.Text = ""; tblPrint.Visible = true; btnSaveAndPrint.Visible = true; } #region Make the assignments lblFisa.Text = txbFisa.Text; lblBank.Text = rblBank.SelectedValue; lblClientCode.Text = txbClientCode.Text; lblClientName.Text = txbClientName.Text; lblBanx.Text = SharePointConnector.IsBanxClient(txbClientBirthdate.Text) ? "SI" : "NO"; lblSector.Text = rblSector.SelectedValue; lblSegmentType.Text = ddlSegmentType.SelectedItem.Text; lblSegmentLabel.Text = (rblCreditType.SelectedValue == "PERSONAL" ? "Segmento" : "Tamaño de Actividad") + " | Tipo de Segmento"; lblCpop.Text = rblCpop.SelectedValue; lblDisabled.Text = rblDisabled.SelectedValue; lblIvc.Text = string.IsNullOrEmpty(txbIvc.Text) ? "(sin valor)" : txbIvc.Text; lblIrt.Text = string.IsNullOrEmpty(txbIrt.Text) ? "(sin valor)" : txbIrt.Text;; lblProduct.Text = rblCreditType.SelectedValue + " | " + ddlProduct.SelectedValue; lblProductType.Text = ddlProductType.SelectedItem.Text; lblWarranty.Text = ddlWarranty.SelectedItem.Text; lblTerm.Text = ddlTerm.SelectedItem.Text; lblPeriodFixed.Text = ddlPeriodFixed.SelectedItem.Text; lblCurrency.Text = rblCurrency.SelectedValue; lblMargin.Text = ddlMargin.SelectedItem.Text; if (rblCreditType.SelectedValue != "PERSONAL" && !ddlProduct.SelectedValue.Contains("NO PRODUCTIVO") && ddlProduct.SelectedValue.Contains("PRODUCTIVO")) { theRate.RateVariable = 100; } Int16 period, term; if (Int16.TryParse(ddlPeriodFixed.SelectedItem.Value, out period) && Int16.TryParse(ddlTerm.SelectedItem.Value, out term) && period < term && theRate.RateVariable < 50) {//if 'Periodo Fijo' (months) is a number & is smaller than 'Plazo' (months) lblRate.Text = "<span class='number'>" + string.Format("{0:0.00}", theRate.RateFixed) + "%</span> fijo los primeros " + "<span class='number'>" + period + " meses</span>,<br/>" + "<span class='number'>" + string.Format("{0:0.00}", theRate.RateVariable) + "%</span> + TRE a partir del " + "<span class='number'>mes " + (period + 1) + "</span>."; } else { lblRate.Text = "<span class='number'>" + string.Format("{0:0.00}", theRate.RateFixed) + "%</span> todo el período del crédito.<br/>"; } if (lblCpop.Text == "SI") { if (!string.IsNullOrEmpty(theRate.CpopBenefit)) { lblCpopBenefit.Text = theRate.CpopBenefit; } else if (theRate.CpopValue != 0.0) { lblCpopBenefit.Text = "Reducción de tasa (ya incluida en la tasa calculada)."; } else { lblCpopBenefit.Text = "(no disponible)"; } } else { lblCpopBenefit.Text = "(no disponible)"; } if (lblDisabled.Text == "SI") { if (!string.IsNullOrEmpty(theRate.DisabledBenefit)) { lblDisabledBenefit.Text = theRate.DisabledBenefit; } else if (theRate.DisabledValue != 0.0) { lblDisabledBenefit.Text = "Reducción de tasa (ya incluida en la tasa calculada)."; } else { lblDisabledBenefit.Text = "(no disponible)"; } } else { lblDisabledBenefit.Text = "(no disponible)"; } #endregion } catch (Exception ex) { System.Web.UI.LiteralControl errorMessage = new System.Web.UI.LiteralControl(); errorMessage.Text = ex.Message; this.Controls.Clear(); this.Controls.Add(errorMessage); } }