private void LoadSettings() { if (Request.QueryString["return"] != null) { returnUrl = Request.QueryString["return"]; lnkReturn.NavigateUrl = returnUrl; lnkReturn.Visible = true; } siteSettings = CacheHelper.GetCurrentSiteSettings(); if (siteSettings == null) { return; } FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider]; if (p == null) { return; } fileSystem = p.GetFileSystem(); if (fileSystem == null) { return; } rootDirectory = fileSystem.VirtualRoot; if (WebUser.IsAdminOrContentAdmin) { canEdit = true; } else if (WebUser.IsInRoles(siteSettings.GeneralBrowseAndUploadRoles)) { canEdit = true; } else if (WebUser.IsInRoles(siteSettings.UserFilesBrowseAndUploadRoles)) { canEdit = true; } if (Request.QueryString["src"] != null) { sourceImageVirtualPath = Request.QueryString["src"]; if (sourceImageVirtualPath.Length > 0) { if ((fileSystem.FileBaseUrl.Length > 0) && (sourceImageVirtualPath.StartsWith(fileSystem.FileBaseUrl))) { sourceImageVirtualPath = sourceImageVirtualPath.Substring(fileSystem.FileBaseUrl.Length); } isAllowedPath = WebFolder.IsDecendentVirtualPath(rootDirectory, sourceImageVirtualPath); sourceExists = fileSystem.FileExists(sourceImageVirtualPath); isAllowedPath = WebFolder.IsDecendentVirtualPath(rootDirectory, sourceImageVirtualPath); } } if (sourceImageVirtualPath.Length == 0) { cropper.Visible = false; return; } destImageVirtualPath = VirtualPathUtility.Combine(VirtualPathUtility.GetDirectory(sourceImageVirtualPath), Path.GetFileNameWithoutExtension(sourceImageVirtualPath) + "crop" + VirtualPathUtility.GetExtension(sourceImageVirtualPath)); SiteUtils.SetFormAction(Page, Request.RawUrl); }
private string FilterInvalidCharacters(string path) { return(FileSystemProvider.FilterInvalidCharacters(path)); }
private void LoadSettings() { config = new SharedFilesConfiguration(Settings); EditContentImage = WebConfigSettings.EditContentImage; lblError.Text = String.Empty; FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider]; if (p == null) { return; } fileSystem = p.GetFileSystem(); if (fileSystem == null) { return; } siteUser = SiteUtils.GetCurrentSiteUser(); newWindowMarkup = displaySettings.NewWindowLinkMarkup; if (BrowserHelper.IsIE()) { //this is a needed hack because IE 8 doesn't work correctly with window.open // a "security feature" of IE 8 // unfortunately this is not valid xhtml to use target but it works in IE newWindowMarkup = displaySettings.IeNewWindowLinkMarkup; } if (!SharedFilesConfiguration.DownloadLinksOpenNewWindow) { newWindowMarkup = string.Empty; } TimeOffset = SiteUtils.GetUserTimeOffset(); timeZone = SiteUtils.GetUserTimeZone(); fileVirtualBasePath = $"~/Data/Sites/{siteSettings.SiteId.ToInvariantString()}/SharedFiles/"; try { // this keeps the action from changing during ajax postback in folder based sites SiteUtils.SetFormAction(Page, Request.RawUrl); } catch (MissingMethodException) { //this method was introduced in .NET 3.5 SP1 } btnUpload2.Visible = IsEditable; uploader.Visible = IsEditable; uploader.MaxFilesAllowed = SharedFilesConfiguration.MaxFilesToUploadAtOnce; uploader.ServiceUrl = $"{SiteRoot}/SharedFiles/upload.ashx?pageid={PageId.ToInvariantString()}&mid={ModuleId.ToInvariantString()}"; uploader.FormFieldClientId = hdnCurrentFolderId.ClientID; uploader.UploadButtonClientId = btnUpload2.ClientID; if (IsEditable) { string refreshFunction = $"function refresh{ModuleId.ToInvariantString()}() {{ $('#{btnRefresh.ClientID}').click(); }};"; uploader.UploadCompleteCallback = $"refresh{ModuleId.ToInvariantString()}"; ScriptManager.RegisterClientScriptBlock( this, GetType(), $"refresh{ModuleId.ToInvariantString()}", refreshFunction, true ); } if (dgFile.TableCssClass.Contains("jqtable") && !WebConfigSettings.DisablejQuery) { string script = $@" function setupJTable{ModuleId.ToInvariantString()}() {{ $('#{dgFile.ClientID} th').each(function() {{ $(this).addClass('ui-state-default'); }}); $('table.jqtable td').each(function() {{ $(this).addClass('ui-widget-content'); }}); $('table.jqtable tr').hover( function() {{ $(this).children('td').addClass('ui-state-hover'); }}, function() {{ $(this).children('td').removeClass('ui-state-hover'); }} ); $('table.jqtable tr').on('click', function() {{ $(this).children('td').toggleClass('ui-state-highlight'); }}); }}; Sys.WebForms.PageRequestManager.getInstance().add_endRequest(setupJTable{ModuleId.ToInvariantString()});"; ScriptManager.RegisterStartupScript( this, GetType(), $"jTable{ModuleId.ToInvariantString()}", script, true ); } trObjectCount.Visible = config.ShowObjectCount; if (config.InstanceCssClass.Length > 0) { pnlOuterWrap.SetOrAppendCss(config.InstanceCssClass); } if (WebConfigSettings.ForceLegacyFileUpload) { ScriptManager.GetCurrent(Page).RegisterPostBackControl(btnUpload2); } }
public void Init() { fileSystemProvider = new FileSystemProvider(); }
private void LoadSettings() { siteSettings = CacheHelper.GetCurrentSiteSettings(); FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider]; if (p == null) { log.Error("Could not load file system provider " + WebConfigSettings.FileSystemProvider); return; } fileSystem = p.GetFileSystem(); if (fileSystem == null) { log.Error("Could not load file system from provider " + WebConfigSettings.FileSystemProvider); return; } if (!IsPostBack) { hdnCurDir.Value = fileSystem.VirtualRoot; } uploader.MaxFilesAllowed = WebConfigSettings.MaxFileManagerFilesToUploadAtOnce; // need to get from file system permission based on user if ((WebUser.IsAdminOrContentAdmin) || SiteUtils.UserIsSiteEditor()) { uploader.AcceptFileTypes = SecurityHelper.GetRegexValidationForAllowedExtensionsJqueryFileUploader( WebConfigSettings.AllowedUploadFileExtensions); } else if (WebUser.IsInRoles(siteSettings.GeneralBrowseAndUploadRoles)) { uploader.AcceptFileTypes = SecurityHelper.GetRegexValidationForAllowedExtensionsJqueryFileUploader( WebConfigSettings.AllowedUploadFileExtensions); } else if (WebUser.IsInRoles(siteSettings.UserFilesBrowseAndUploadRoles)) { uploader.AcceptFileTypes = SecurityHelper.GetRegexValidationForAllowedExtensionsJqueryFileUploader( WebConfigSettings.AllowedLessPriveledgedUserUploadFileExtensions); } uploader.UploadButtonClientId = btnUpload.ClientID; string fileSystemToken = Global.FileSystemToken.ToString(); uploader.ServiceUrl = SiteUtils.GetNavigationSiteRoot() + "/Services/FileService.ashx?cmd=uploadfm&t=" + fileSystemToken; uploader.FormFieldClientId = hdnCurDir.ClientID; // //string refreshFunction = "function refresh () { window.location.reload(true); } "; //uploader.UploadCompleteCallback = "refresh"; string refreshFunction = "function refresh" + " () { $('#" + btnRefresh.ClientID + "').click(); } "; uploader.UploadCompleteCallback = "refresh"; ScriptManager.RegisterClientScriptBlock( this, this.GetType(), "refresh", refreshFunction, true); }
protected void BuildLayout(Guid siteID, Guid contactID, tbl_SiteActivityRules siteActivityRule, List <SiteActivityRuleLayoutParams> siteActivityRuleLayouts, SiteActivityRuleLayoutParams parentLayout, List <ContactColumnValueMap> contactColumnValues, bool register) { var skin = ((Skin)siteActivityRule.Skin).ToString(); FormDecorator.Skin = skin; List <SiteActivityRuleLayoutParams> layouts; if (parentLayout == null) { layouts = siteActivityRuleLayouts.Where(a => a.ParentID == null).OrderBy(a => a.Order).ToList(); } else { layouts = siteActivityRuleLayouts.Where(a => a.ParentID == parentLayout.ID).OrderBy(a => a.Order).ToList(); } foreach (var layout in layouts) { var controlToInsert = new Control(); var container = new Panel(); var fieldWrapper = new Panel { CssClass = "field-wrapper" }; if (parentLayout == null) { controlToInsert = pnlFormContainer; } else { controlToInsert = pnlFormContainer.FindControl(string.Format("csf-{0}", layout.ParentID.ToString().Replace("-", "__"))); } switch ((LayoutType)layout.LayoutType) { case LayoutType.GroupFields: if ((OutputFormat)layout.OutputFormat == OutputFormat.Header) { var hdr = new Panel { CssClass = string.Format("hdr-{0}", layout.ID) }; var linkHdr = new LinkButton { Text = layout.Name, OnClientClick = string.Format("toggleForm('csf-{0}'); return false;", layout.ID), CssClass = "hdr" }; hdr.Controls.Add(linkHdr); controlToInsert.Controls.Add(hdr); } var pnl = new Panel { ID = string.Format("csf-{0}", layout.ID.ToString().Replace("-", "__")), CssClass = string.Format("csf-{0}", layout.ID) }; pnl.Attributes.Add("style", "width: 100%; display: table;" + layout.CSSStyle); controlToInsert.Controls.Add(pnl); break; case LayoutType.TextBlock: var textBlock = new Panel { CssClass = string.Format("csf-{0}", layout.ID), ClientIDMode = ClientIDMode.Static }; textBlock.Controls.Add(new Literal { Text = layout.Description }); if (!string.IsNullOrEmpty(layout.CSSStyle) && layout.CSSStyle.Trim() != string.Empty) { textBlock.Attributes.Add("style", layout.CSSStyle); } if (!string.IsNullOrEmpty(siteActivityRule.ErrorMessage) && !string.IsNullOrEmpty(layout.LayoutParams)) { var layoutParams = LayoutParams.Deserialize(layout.LayoutParams); if (layoutParams.GetBoolValue("IsUsedForErrorMessage")) { if (textBlock.Attributes["style"] != null) { textBlock.Attributes["style"] += ";display:none"; } else { textBlock.Attributes.Add("style", "display:none;"); } textBlock.Attributes["style"] += "padding: 5px 0;color:#b63306"; textBlock.ID = "LFErrorMessageTextBlock"; } } container.Controls.Add(textBlock); controlToInsert.Controls.Add(container); break; case LayoutType.Image: var binaryImage = new RadBinaryImage { CssClass = string.Format("csf-{0}", layout.ID), ClientIDMode = ClientIDMode.Static }; var fsp = new FileSystemProvider(); var filePath = fsp.GetRemoteLink(siteID, "SiteActivityRule", layout.ID.ToString() + ".png", FileType.Image); binaryImage.ImageUrl = filePath; if (!string.IsNullOrEmpty(layout.LayoutParams)) { var layoutParams = LayoutParams.Deserialize(layout.LayoutParams); if (!string.IsNullOrEmpty(layoutParams.GetValue("ImageWidth"))) { binaryImage.Width = new Unit(int.Parse(layoutParams.GetValue("ImageWidth")), UnitType.Pixel); } if (!string.IsNullOrEmpty(layoutParams.GetValue("ImageHeight"))) { binaryImage.Height = new Unit(int.Parse(layoutParams.GetValue("ImageHeight")), UnitType.Pixel); } if (!string.IsNullOrEmpty(layoutParams.GetValue("ImageAlign"))) { container.Attributes.CssStyle.Add("text-align", layoutParams.GetValue("ImageAlign")); } if (!string.IsNullOrEmpty(layoutParams.GetValue("ImageAlternativeText"))) { binaryImage.AlternateText = layoutParams.GetValue("ImageAlternativeText"); } } container.Controls.Add(binaryImage); controlToInsert.Controls.Add(container); break; case LayoutType.ProfileField: case LayoutType.FormField: if (register && layout.IsAdmin) { continue; } //var controlId = string.Format("LF{0}___{1}___", counter++, layout.SiteColumnID.HasValue ? ((Guid)layout.SiteColumnID).ToString() : layout.SysField); var controlId = string.Format("LF{0}___{1}___", counter++, layout.SiteColumnID.HasValue ? ((Guid)layout.SiteColumnID).ToString().Replace("-", "__") : layout.SysField); var field = contactData.GetFieldByValue(layout.SiteColumnID.HasValue ? ((Guid)layout.SiteColumnID).ToString() : layout.SysField, siteActivityRule.ID); var label = new Label { AssociatedControlID = controlId, Text = layout.SiteColumnID.HasValue ? layout.SiteColumnName : field.Name, CssClass = "label" }; var fieldClass = string.Empty; if (parentLayout != null) { if ((OutputFormatFields)parentLayout.OutputFormatFields == OutputFormatFields.Top || (OutputFormatFields)parentLayout.OutputFormatFields == OutputFormatFields.Left) { container.Controls.Add(label); } if ((OutputFormatFields)parentLayout.OutputFormatFields == OutputFormatFields.Top) { container.Controls.Add(new LiteralControl("<br />")); } fieldClass = GetFieldClass(parentLayout); if (!string.IsNullOrEmpty(fieldClass)) { container.CssClass = fieldClass; } } //var contactDataValues = contactData.GetContactData(contactID); //RadDatePicker datePicker = new RadDatePicker(); var dataValue = contactDataValues.FirstOrDefault(a => a.Key == field.Value); switch (field.ColumnType) { case ColumnType.String: var textBox = new RadTextBox { ID = controlId, Width = new Unit(98, UnitType.Percentage), Skin = skin }; if (!string.IsNullOrEmpty(dataValue.Key)) { textBox.Text = dataValue.Value; } else if (field.IsAdditional && !string.IsNullOrEmpty(layout.DefaultValue)) { textBox.Text = layout.DefaultValue; } if (!string.IsNullOrEmpty(layout.CSSStyle)) { textBox.Attributes.Add("style", ClearBackground(layout.CSSStyle)); } textBox.Attributes.Add("onfocus", "TextboxFocus(this);"); if ((OutputFormatFields)parentLayout.OutputFormatFields == OutputFormatFields.InElement) { textBox.EmptyMessage = layout.SiteColumnID.HasValue ? layout.SiteColumnName : field.Name; } fieldWrapper.Controls.Add(textBox); container.Controls.Add(fieldWrapper); break; case ColumnType.Text: var text = new RadTextBox { ID = controlId, Width = new Unit(98, UnitType.Percentage), TextMode = InputMode.MultiLine, Skin = skin }; if (!string.IsNullOrEmpty(dataValue.Key)) { text.Text = !string.IsNullOrEmpty(dataValue.Value) ? dataValue.Value.Replace("<br />", "\n") : null; } else if (field.IsAdditional && !string.IsNullOrEmpty(layout.DefaultValue)) { text.Text = !string.IsNullOrEmpty(layout.DefaultValue) ? layout.DefaultValue.Replace("<br />", "\n") : null; } if (!string.IsNullOrEmpty(layout.CSSStyle)) { text.Attributes.Add("style", ClearBackground(layout.CSSStyle)); } text.Attributes.Add("onfocus", "TextboxFocus(this);"); if ((OutputFormatFields)parentLayout.OutputFormatFields == OutputFormatFields.InElement) { text.EmptyMessage = layout.SiteColumnID.HasValue ? layout.SiteColumnName : field.Name; } fieldWrapper.Controls.Add(text); container.Controls.Add(fieldWrapper); break; case ColumnType.Number: var numericTextBox = new RadNumericTextBox { ID = controlId, Width = new Unit(98, UnitType.Percentage), AutoCompleteType = AutoCompleteType.Disabled, Type = NumericType.Number, Skin = skin.ToString() }; numericTextBox.NumberFormat.GroupSeparator = ""; numericTextBox.NumberFormat.DecimalDigits = 0; if (!string.IsNullOrEmpty(dataValue.Key)) { numericTextBox.Text = dataValue.Value; } else if (field.IsAdditional && !string.IsNullOrEmpty(layout.DefaultValue)) { numericTextBox.Text = layout.DefaultValue; } if (!string.IsNullOrEmpty(layout.CSSStyle)) { numericTextBox.Attributes.Add("style", ClearBackground(layout.CSSStyle)); } numericTextBox.Attributes.Add("onfocus", "TextboxFocus(this);"); if ((OutputFormatFields)parentLayout.OutputFormatFields == OutputFormatFields.InElement) { numericTextBox.EmptyMessage = layout.SiteColumnID.HasValue ? layout.SiteColumnName : field.Name; } fieldWrapper.Controls.Add(numericTextBox); container.Controls.Add(fieldWrapper); break; case ColumnType.Date: var datePicker = new RadDateTimePicker { ID = controlId, Width = new Unit(98, UnitType.Percentage), ShowPopupOnFocus = true, Skin = skin }; datePicker.TimePopupButton.Visible = false; datePicker.DateInput.DateFormat = "dd/MM/yyyy"; if (layout.ColumnTypeExpressionID.HasValue) { var columnTypesExpression = repository.ColumnTypesExpression_SelectById((Guid)layout.ColumnTypeExpressionID); datePicker.DateInput.DateFormat = columnTypesExpression.Expression; switch (columnTypesExpression.Expression) { case "dd/MM/yyyy hh:mm": datePicker.TimePopupButton.Visible = true; break; case "hh:mm": datePicker.TimePopupButton.Visible = true; datePicker.DatePopupButton.Visible = false; datePicker.ShowPopupOnFocus = false; break; /*case "dd/MM/yyyy": * default: * datePicker.DateInput.DateFormat = columnTypesExpression.Expression; * break;*/ } } if (!string.IsNullOrEmpty(dataValue.Key)) { if (!string.IsNullOrEmpty(dataValue.Value)) { datePicker.SelectedDate = DateTime.Parse(dataValue.Value); } } else if (field.IsAdditional && !string.IsNullOrEmpty(layout.DefaultValue)) { datePicker.SelectedDate = DateTime.Parse(layout.DefaultValue); } if (!string.IsNullOrEmpty(layout.CSSStyle)) { datePicker.DateInput.Attributes.Add("style", ClearBackground(layout.CSSStyle)); } datePicker.ClientEvents.OnPopupOpening = "PopupOpening"; fieldWrapper.Controls.Add(datePicker); container.Controls.Add(fieldWrapper); break; case ColumnType.Enum: var dictionaryComboBox = (DictionaryComboBox)LoadControl("~/UserControls/DictionaryComboBox.ascx"); dictionaryComboBox.ID = controlId; dictionaryComboBox.DataValueField = "ID"; dictionaryComboBox.Skin = skin; if (field.IsAdditional) { dictionaryComboBox.DictionaryName = "tbl_SiteColumnValues"; dictionaryComboBox.DataTextField = "Value"; dictionaryComboBox.Filters.Add(new DictionaryComboBox.DictionaryFilterColumn { DbType = DbType.Guid, Name = "SiteColumnID", Value = field.Value }); if (!string.IsNullOrEmpty(dataValue.Key) && !string.IsNullOrEmpty(dataValue.Value)) { dictionaryComboBox.SelectedId = Guid.Parse(dataValue.Value); } else if (field.IsAdditional && !string.IsNullOrEmpty(layout.DefaultValue)) { dictionaryComboBox.SelectedId = Guid.Parse(layout.DefaultValue); } } else { var order = new List <DictionaryComboBox.DictionaryOrderColumn>(); switch (field.Value) { case "sys_joblevel": dictionaryComboBox.SiteID = siteID; dictionaryComboBox.DictionaryName = "tbl_ContactJobLevel"; dictionaryComboBox.DataTextField = "Name"; order.Add(new DictionaryComboBox.DictionaryOrderColumn { Name = "Name", Direction = "ASC" }); break; case "sys_functionincompany": dictionaryComboBox.SiteID = siteID; dictionaryComboBox.DictionaryName = "tbl_ContactFunctionInCompany"; dictionaryComboBox.DataTextField = "Name"; order.Add(new DictionaryComboBox.DictionaryOrderColumn { Name = "Name", Direction = "ASC" }); break; case "sys_country": dictionaryComboBox.DictionaryName = "tbl_Country"; dictionaryComboBox.DataTextField = "Name"; order.Add(new DictionaryComboBox.DictionaryOrderColumn { Name = "Name", Direction = "ASC" }); break; case "sys_city": dictionaryComboBox.DictionaryName = "tbl_City"; dictionaryComboBox.DataTextField = "Name"; order.Add(new DictionaryComboBox.DictionaryOrderColumn { Name = "Name", Direction = "ASC" }); break; case "sys_advertisingplatform": dictionaryComboBox.SiteID = siteID; dictionaryComboBox.DictionaryName = "tbl_AdvertisingPlatform"; dictionaryComboBox.DataTextField = "Title"; order.Add(new DictionaryComboBox.DictionaryOrderColumn { Name = "Title", Direction = "ASC" }); break; case "sys_advertisingtype": dictionaryComboBox.SiteID = siteID; dictionaryComboBox.DictionaryName = "tbl_AdvertisingType"; dictionaryComboBox.DataTextField = "Title"; order.Add(new DictionaryComboBox.DictionaryOrderColumn { Name = "Title", Direction = "ASC" }); break; case "sys_advertisingcampaign": dictionaryComboBox.SiteID = siteID; dictionaryComboBox.DictionaryName = "tbl_AdvertisingCampaign"; dictionaryComboBox.DataTextField = "Title"; order.Add(new DictionaryComboBox.DictionaryOrderColumn { Name = "Title", Direction = "ASC" }); break; } dictionaryComboBox.Order = order; if (!string.IsNullOrEmpty(dataValue.Value)) { dictionaryComboBox.SelectedId = Guid.Parse(dataValue.Value); } } if (layout.IsRequired) { dictionaryComboBox.ComboBox.OnClientSelectedIndexChanged = "ClientSelectedIndexChanged"; dictionaryComboBox.ValidationGroup = "vg"; } if (!string.IsNullOrEmpty(layout.CSSStyle)) { dictionaryComboBox.ComboBox.Attributes.Add("style", ClearBackground(layout.CSSStyle)); if (IsContainsBackground(layout.CSSStyle)) { dictionaryComboBox.Skin = "Transparent"; } } if ((OutputFormatFields)parentLayout.OutputFormatFields == OutputFormatFields.InElement) { dictionaryComboBox.EmptyItemText = layout.SiteColumnID.HasValue ? layout.SiteColumnName : field.Name; } fieldWrapper.Controls.Add(dictionaryComboBox); container.Controls.Add(fieldWrapper); break; case ColumnType.Logical: var checkBox = new CheckBox { ID = controlId, Width = new Unit(16, UnitType.Pixel) }; if (!checkboxes.Contains(controlId)) { checkboxes.Add(controlId); } if (!string.IsNullOrEmpty(dataValue.Key)) { checkBox.Checked = !string.IsNullOrEmpty(dataValue.Value) ? bool.Parse(dataValue.Value) : false; } else if (field.IsAdditional && !string.IsNullOrEmpty(layout.DefaultValue)) { checkBox.Checked = !string.IsNullOrEmpty(layout.DefaultValue) ? bool.Parse(layout.DefaultValue) : false; } /*if (!string.IsNullOrEmpty(layout.CSSStyle)) * text.Attributes.Add("style", ClearBackground(layout.CSSStyle));*/ fieldWrapper.Controls.Add(checkBox); container.Controls.Add(fieldWrapper); break; } /*if (!string.IsNullOrEmpty(layout.CSSStyle) && layout.CSSStyle.Trim() != string.Empty) * fieldWrapper.Attributes.Add("style", layout.CSSStyle);*/ if (layout.IsRequired && field.ColumnType != ColumnType.Enum) { fieldWrapper.Controls.Add(new RequiredFieldValidator { ControlToValidate = controlId, ErrorMessage = "Поле обязательное для заполнения", Display = ValidatorDisplay.None, ValidationGroup = "vg" }); } if (layout.ColumnTypeExpressionID.HasValue) { if (field.ColumnType != ColumnType.Date) { var columnTypesExpression = repository.ColumnTypesExpression_SelectById((Guid)layout.ColumnTypeExpressionID); fieldWrapper.Controls.Add(new RegularExpressionValidator { ValidationExpression = columnTypesExpression.Expression, ControlToValidate = controlId, ErrorMessage = "Неправильный формат поля", Display = ValidatorDisplay.None, ValidationGroup = "vg" }); } } if (!layout.IsExtraField || (layout.IsExtraField && (siteActivityRule.CountExtraFields == null || siteActivityRule.CountExtraFields > extraFieldCount) && string.IsNullOrEmpty(dataValue.Value))) { controlToInsert.Controls.Add(container); extraFieldCount++; } break; } BuildLayout(siteID, contactID, siteActivityRule, siteActivityRuleLayouts, layout, contactColumnValues, register); } }
public static string GetDirectoryName(string path) { return(FileSystemProvider.GetDirectoryName(path)); }
/// <summary> /// HERVE GLOTIN /// Combined audio2csv + zooming spectrogram task. /// This is used to analyse Herve Glotin's BIRD50 data set. /// ############################# IMPORTANT ######################################## /// In order to analyse the short recordings in BIRD50 dataset, need following change to code: /// need to modify AudioAnalysis.AnalysisPrograms.AcousticIndices.cs #line648 /// need to change AnalysisMinSegmentDuration = TimeSpan.FromSeconds(20), /// to AnalysisMinSegmentDuration = TimeSpan.FromSeconds(1), /// THIS iS to analyse BIRD50 short recordings. /// </summary> public static void HiRes1() { string recordingPath = @"C:\SensorNetworks\WavFiles\TestRecordings\TEST_7min_artificial.wav"; //// HERVE GLOTIN BIRD50 TRAINING RECORDINGS //DirectoryInfo dataDir = new DirectoryInfo(@"D:\SensorNetworks\WavFiles\Glotin\Bird50\AmazonBird50_training_input"); //string parentDir = @"C:\SensorNetworks\Output\BIRD50"; //string speciesLabelsFile = parentDir + @"\AmazonBird50_training_output.csv"; //int speciesCount = 50; //////set file name format -depends on train or test. E.g. "ID0003"; //string fileStemFormatString = "ID{0:d4}"; // for training files //string indexPropertiesConfig = @"C:\Work\GitHub\audio-analysis\AudioAnalysis\AnalysisConfigFiles\IndexPropertiesConfigHiRes.yml"; //string learningMode = "Train"; //// HERVE GLOTIN BIRD50 TESTING RECORDINGS DirectoryInfo dataDir = new DirectoryInfo(@"D:\SensorNetworks\WavFiles\Glotin\Bird50\AmazonBird50_testing_input"); string parentDir = @"C:\SensorNetworks\Output\BIRD50"; string speciesLabelsFile = null; int speciesCount = 50; ////set file name format -depends on train or test. E.g. "ID0003"; string fileStemFormatString = "ID1{0:d3}"; // for testing files string indexPropertiesConfig = @"C:\Work\GitHub\audio-analysis\AudioAnalysis\AnalysisConfigFiles\IndexPropertiesConfigHiRes.yml"; string learningMode = "Test"; // HERVE GLOTIN BOMBYX WHALE RECORDINGS //DirectoryInfo dataDir = new DirectoryInfo(@"C:\SensorNetworks\WavFiles\WhaleFromGlotin"); //string parentDir = @"C:\SensorNetworks\Output\Glotin\Bombyx_SpermWhales"; //string speciesLabelsFile = null; //int speciesCount = 0; //////set file name format -depends on train or test. E.g. "ID0003"; //string fileStemFormatString = null; ////string fileStemFormatString = "ID1{0:d3}"; // for testing files //string indexPropertiesConfig = @"C:\Work\GitHub\audio-analysis\AudioAnalysis\AnalysisConfigFiles\IndexPropertiesConfigHiResGianniPavan.yml"; //string learningMode = "Train"; // GIANNI PAVAN SASSAFRAS RECORDINGS //DirectoryInfo dataDir = new DirectoryInfo(@"C:\SensorNetworks\WavFiles\GianniPavan\SABIOD - TEST SASSOFRATINO"); //string parentDir = @"C:\SensorNetworks\Output\GianniPavan"; //string speciesLabelsFile = null; //int speciesCount = 0; //string fileStemFormatString = null; //string indexPropertiesConfig = @"C:\Work\GitHub\audio-analysis\AudioAnalysis\AnalysisConfigFiles\IndexPropertiesConfigHiResGianniPavan.yml"; //string learningMode = "Train"; // ###################################################################### string outputDir = parentDir + @"\" + learningMode; string imageOutputDir = parentDir + @"\" + learningMode + "Images"; string csvDir = outputDir + @"\Towsey.Acoustic"; string zoomOutputDir = outputDir; string audio2csvConfigPath = @"C:\Work\GitHub\audio-analysis\AudioAnalysis\AnalysisConfigFiles\Towsey.AcousticHiRes.yml"; string hiResZoomConfigPath = @"C:\Work\GitHub\audio-analysis\AudioAnalysis\AnalysisConfigFiles\SpectrogramHiResConfig.yml"; FileInfo[] wavFiles = { new FileInfo(recordingPath) }; // comment next two lines when debugging a single recording file string match = @"*.wav"; wavFiles = dataDir.GetFiles(match, SearchOption.AllDirectories); // READ IN THE SPECIES LABELS FILE AND SET UP THE DATA string[] fileID = new string[wavFiles.Length]; int[] speciesID = new int[speciesCount]; if (speciesLabelsFile != null) { BirdClefExperiment1.ReadGlotinsSpeciesLabelFile(speciesLabelsFile, wavFiles.Length, out fileID, out speciesID); } else // make seperate species name for each file { speciesID = new int[wavFiles.Length]; } //LOOP THROUGH ALL WAV FILES //for (int i = 538; i < 539; i++) //for (int i = 0; i < 8; i++) for (int i = 0; i < wavFiles.Length; i++) { FileInfo file = wavFiles[i]; recordingPath = file.FullName; string idName = Path.GetFileNameWithoutExtension(file.FullName); string name = string.Format("{0}_Species{1:d2}", idName, speciesID[i]); outputDir = parentDir + @"\" + learningMode + @"\" + name; csvDir = parentDir + @"\" + learningMode + @"\" + name + @"\Towsey.Acoustic"; zoomOutputDir = outputDir; Console.WriteLine("\n\n"); Console.WriteLine($@">>>>{i}: File<{name}>"); try { // A: analyse the recording files == audio2csv. var audio2csvArguments = new AnalyseLongRecordings.AnalyseLongRecording.Arguments { Source = recordingPath.ToFileInfo(), Config = audio2csvConfigPath, Output = outputDir.ToDirectoryInfo(), }; if (!audio2csvArguments.Source.Exists) { LoggedConsole.WriteWarnLine(" >>>>>>>>>>>> WARNING! The Source Recording file cannot be found! This will cause an exception."); } if (!File.Exists(audio2csvArguments.Config)) { LoggedConsole.WriteWarnLine(" >>>>>>>>>>>> WARNING! The Configuration file cannot be found! This will cause an exception."); } AnalyseLongRecordings.AnalyseLongRecording.Execute(audio2csvArguments); // B: Concatenate the summary indices and produce images // Use the Zoomingspectrograms action. // need to find out how long the recording is. string fileName = audio2csvArguments.Source.BaseName(); string testFileName = fileName + @"__Towsey.Acoustic.ACI.csv"; List<string> data = FileTools.ReadTextFile(Path.Combine(csvDir, testFileName)); int lineCount = data.Count - 1; // -1 for header. int imageWidth = lineCount; //assume scale is index calculation duration = 0.1s // i.e. image resolution 0.1s/px. or 600px/min double focalMinute = (double)lineCount / 600 / 2; if (focalMinute < 0.016666) { focalMinute = 0.016666; // shortest recording = 1 second. } var zoomingArguments = new DrawZoomingSpectrograms.Arguments { // use the default set of index properties in the AnalysisConfig directory. SourceDirectory = csvDir, Output = zoomOutputDir, SpectrogramZoomingConfig = hiResZoomConfigPath, // draw a focused multi-resolution pyramid of images ZoomAction = DrawZoomingSpectrograms.Arguments.ZoomActionType.Focused, }; LoggedConsole.WriteLine("# Spectrogram Zooming config : " + zoomingArguments.SpectrogramZoomingConfig); LoggedConsole.WriteLine("# Input Directory : " + zoomingArguments.SourceDirectory); LoggedConsole.WriteLine("# Output Directory : " + zoomingArguments.Output); var common = new ZoomParameters(zoomingArguments.SourceDirectory.ToDirectoryEntry(), zoomingArguments.SpectrogramZoomingConfig.ToFileEntry(), false); var io = FileSystemProvider.GetInputOutputFileSystems( zoomingArguments.SourceDirectory, FileSystemProvider.MakePath(zoomingArguments.Output, common.OriginalBasename, zoomingArguments.OutputFormat, "Tiles")) .EnsureInputIsDirectory(); // Create directory if not exists if (!Directory.Exists(zoomingArguments.Output)) { Directory.CreateDirectory(zoomingArguments.Output); } ZoomFocusedSpectrograms.DrawStackOfZoomedSpectrograms( zoomingArguments.SourceDirectory.ToDirectoryInfo(), zoomingArguments.Output.ToDirectoryInfo(), io, common, AcousticIndices.TowseyAcoustic, TimeSpan.FromMinutes(focalMinute), imageWidth); // DRAW THE VARIOUS IMAGES string fileStem = fileName; if (fileStemFormatString != null) { fileStem = string.Format(fileStemFormatString, i + 1); // training images } var ldfcSpectrogramArguments = new DrawLongDurationSpectrograms.Arguments { // use the default set of index properties in the AnalysisConfig directory. InputDataDirectory = csvDir, OutputDirectory = imageOutputDir, IndexPropertiesConfig = indexPropertiesConfig, }; // there are two possible tasks // 1: draw the aggregated grey scale spectrograms int secDuration = DrawLongDurationSpectrograms.DrawAggregatedSpectrograms(ldfcSpectrogramArguments, fileStem); // 2: draw the coloured ridge spectrograms secDuration = DrawLongDurationSpectrograms.DrawRidgeSpectrograms(ldfcSpectrogramArguments, fileStem); // copy files // POW, EVN, SPT, RHZ, RVT, RPS, RNG // WARNING: POW was removed December 2018 string[] copyArray = { "POW", "EVN", "SPT", "RHZ", "RVT", "RPS", "RNG" }; DirectoryInfo sourceDirectory = new DirectoryInfo(csvDir); string destinationDirectory = parentDir + @"\TrainingClassifier"; foreach (string key in copyArray) { // ID0002__Towsey.Acoustic.BGN.csv fileName += @"__Towsey.Acoustic.ACI.csv"; string sourceFileName = string.Format(idName + "__Towsey.Acoustic." + key + ".csv"); string sourcePath = Path.Combine(sourceDirectory.FullName, sourceFileName); string nameOfParentDirectory = sourceDirectory.Parent.Name; string destinationFileName = string.Format(nameOfParentDirectory + "." + key + ".csv"); string destinationPath = Path.Combine(destinationDirectory, destinationFileName); File.Copy(sourcePath, destinationPath, true); } } // try block catch (Exception e) { LoggedConsole.WriteErrorLine(string.Format("ERROR!!!!! RECORDING {0} FILE {1}", i, name)); LoggedConsole.WriteErrorLine(string.Format(e.ToString())); } } // end loop through all wav files } // HiRes1()
public static IEnumerable <string> GetDirectoryFiles(string directoryName) { return(FileSystemProvider.GetFiles(directoryName)); }
public static string GetFileName(string pathAndFileName) { return(FileSystemProvider.GetFileName(pathAndFileName)); }
public static bool DirectoryExists(string directoryName) { return(FileSystemProvider.DirectoryExists(directoryName)); }
public static string GetParentPath(string fileName) { return(FileSystemProvider.GetDirectoryName(fileName)); }
public static string CurrentPath() { return(FileSystemProvider.GetCurrentDirectory()); }
public static DateTime LastWriteTime(string fileName) { return(FileSystemProvider.GetLastWriteTimeUtc(fileName)); }
public static void Execute(Arguments arguments) { if (arguments == null) { throw new NoDeveloperMethodException(); } string description; switch (arguments.ZoomAction) { case Arguments.ZoomActionType.Focused: description = "# DRAW STACK OF FOCUSED MULTI-SCALE LONG DURATION SPECTROGRAMS DERIVED FROM SPECTRAL INDICES."; break; case Arguments.ZoomActionType.Tile: description = "# DRAW ZOOMING SPECTROGRAMS DERIVED FROM SPECTRAL INDICES OBTAINED FROM AN AUDIO RECORDING"; break; default: throw new ArgumentOutOfRangeException(); } LoggedConsole.WriteLine(description); LoggedConsole.WriteLine("# Spectrogram Zooming config : " + arguments.SpectrogramZoomingConfig); LoggedConsole.WriteLine("# Input Directory : " + arguments.SourceDirectory); LoggedConsole.WriteLine("# Output Directory : " + arguments.Output); var common = new ZoomParameters( arguments.SourceDirectory.ToDirectoryEntry(), arguments.SpectrogramZoomingConfig.ToFileEntry(), !string.IsNullOrEmpty(arguments.OutputFormat)); LoggedConsole.WriteLine("# File name of recording : " + common.OriginalBasename); // create file systems for reading input and writing output. It gets //arguments.SourceDirectory.ToDirectoryInfo(), //arguments.Output.ToDirectoryInfo(), var io = FileSystemProvider.GetInputOutputFileSystems( arguments.SourceDirectory, FileSystemProvider.MakePath(arguments.Output, common.OriginalBasename, arguments.OutputFormat, "Tiles")) .EnsureInputIsDirectory(); switch (arguments.ZoomAction) { case Arguments.ZoomActionType.Focused: // draw a focused multi-resolution pyramid of images TimeSpan focalTime; if (arguments.FocusMinute.HasValue) { focalTime = TimeSpan.FromMinutes(arguments.FocusMinute.Value); } else { throw new ArgumentException("FocusMinute is null, cannot proceed"); } ZoomFocusedSpectrograms.DrawStackOfZoomedSpectrograms( arguments.SourceDirectory.ToDirectoryInfo(), arguments.Output.ToDirectoryInfo(), io, common, AcousticIndices.TowseyAcoustic, focalTime, imageWidth: 1500); break; case Arguments.ZoomActionType.Tile: // Create the super tiles for a full set of recordings ZoomTiledSpectrograms.DrawTiles( io, common, AcousticIndices.TowseyAcoustic); break; default: Log.Warn("Other ZoomAction results in standard LD Spectrogram to be drawn"); // draw standard false color spectrograms - useful to check what spectrograms of the individual // indices are like. throw new NotImplementedException(); /*LDSpectrogramRGB.DrawSpectrogramsFromSpectralIndices( * arguments.SourceDirectory, * arguments.Output, * arguments.SpectrogramConfigPath, * arguments.IndexPropertiesConfig);*/ break; } }
private void LoadSettings() { pageId = WebUtils.ParseInt32FromQueryString("pageid", -1); moduleId = WebUtils.ParseInt32FromQueryString("mid", true, -1); currencyCulture = ResourceHelper.GetCurrencyCulture(siteSettings.GetCurrency().Code); store = StoreHelper.GetStore(); if (store == null) { return; } config = new WebStoreConfiguration(ModuleSettings.GetModuleSettings(store.ModuleId)); siteUser = SiteUtils.GetCurrentSiteUser(); productGuid = WebUtils.ParseGuidFromQueryString("prod", productGuid); if (productGuid == Guid.Empty) { return; } grdImages.Config = config; grdImages.ReferenceGuid = productGuid; virtualRoot = WebUtils.GetApplicationRoot(); upLoadPath = $"~/Data/Sites/{siteSettings.SiteId.ToInvariantString()}/webstoreproductfiles/"; teaserFileBasePath = $"~/Data/Sites/{siteSettings.SiteId.ToInvariantString()}/webstoreproductpreviewfiles/"; AddClassToBody("webstore webstoreproductedit"); FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider]; if (p == null) { log.Error($"Could not load file system provider {WebConfigSettings.FileSystemProvider}"); return; } fileSystem = p.GetFileSystem(); if (fileSystem == null) { log.Error($"Could not load file system from provider {WebConfigSettings.FileSystemProvider}"); return; } if (!fileSystem.FolderExists(upLoadPath)) { fileSystem.CreateFolder(upLoadPath); } if (!fileSystem.FolderExists(teaserFileBasePath)) { fileSystem.CreateFolder(teaserFileBasePath); } productUploader.ServiceUrl = SiteRoot + "/WebStore/upload.ashx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString() + "&prod=" + productGuid.ToString(); productUploader.UploadButtonClientId = btnUpload.ClientID; productUploader.FormFieldClientId = hdnState.ClientID; // not really used but prevents submitting all the form string refreshFunction = "function refresh" + moduleId.ToInvariantString() + " (data, errorsOccurred) { if(errorsOccurred === false) { $('#" + btnSave.ClientID + "').click(); } } "; productUploader.UploadCompleteCallback = "refresh" + moduleId.ToInvariantString(); ScriptManager.RegisterClientScriptBlock( this, this.GetType(), "refresh" + moduleId.ToInvariantString(), refreshFunction, true); teaserUploader.ServiceUrl = SiteRoot + "/WebStore/upload.ashx?type=teaser&pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString() + "&prod=" + productGuid.ToString(); teaserUploader.UploadButtonClientId = btnUploadTeaser.ClientID; teaserUploader.FormFieldClientId = hdnState.ClientID; // not really used but prevents submitting all the form teaserUploader.UploadCompleteCallback = "refresh" + moduleId.ToInvariantString(); ScriptConfig.IncludeColorBox = true; }
private void LoadSettings() { timeZone = SiteUtils.GetUserTimeZone(); virtualSourcePath = "~/Data/Sites/" + siteSettings.SiteId.ToInvariantString() + "/SharedFiles/"; virtualHistoryPath = "~/Data/Sites/" + siteSettings.SiteId.ToInvariantString() + "/SharedFiles/History/"; lnkCancelFile.NavigateUrl = SiteUtils.GetCurrentPageUrl(); lnkCancelFolder.NavigateUrl = lnkCancelFile.NavigateUrl; //if (BrowserHelper.IsIE()) //{ // //this is a needed hack because IE 8 doesn't work correctly with window.open // // a "security feature" of IE 8 // // unfortunately this is not valid xhtml to use target but it works in IE // newWindowMarkup = " target='_blank' "; //} //this page handles both folders and files //expected strItem examples are 23~folder and 13~file //the number portion is the ItemID of the folder or file if (strItem.IndexOf("~") > -1) { try { char[] separator = { '~' }; string[] args = strItem.Split(separator); this.itemId = int.Parse(args[0]); type = args[1]; } catch { }; } Hashtable moduleSettings = ModuleSettings.GetModuleSettings(moduleId); config = new SharedFilesConfiguration(moduleSettings); divHistory.Visible = config.EnableVersioning; uploader.UploadButtonClientId = btnUpload.ClientID; uploader.ServiceUrl = SiteRoot + "/SharedFiles/upload.ashx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString() + "&ItemID=" + itemId.ToInvariantString(); uploader.FormFieldClientId = hdnCurrentFolderId.ClientID; string refreshFunction = "function refresh" + moduleId.ToInvariantString() + " () { window.location.reload(true); } "; uploader.UploadCompleteCallback = "refresh" + moduleId.ToInvariantString(); ScriptManager.RegisterClientScriptBlock( this, this.GetType(), "refresh" + moduleId.ToInvariantString(), refreshFunction, true); AddClassToBody("sharedfilesedit"); FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider]; if (p == null) { return; } fileSystem = p.GetFileSystem(); }
public static string GetHelpText(string helpKey, ModuleConfiguration config) { FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider]; if (p == null) { log.Error("File System Provider Could Not Be Loaded."); return(string.Empty); } IFileSystem fileSystem = p.GetFileSystem(); if (fileSystem == null) { log.Error("File System Could Not Be Loaded."); return(string.Empty); } string helpText = string.Empty; WebFile helpFile = new WebFile(); if (helpKey.ToLower().EndsWith(".sfhelp") || helpKey.ToLower().EndsWith(".config") || helpKey.ToLower().EndsWith(".html")) { if (helpKey.IndexOf("$_FlexiHelp_$") >= 0) { string path = fileSystem.CombinePath("~/Data/SuperFlexi/Help/", helpKey.Replace("$_FlexiHelp_$", string.Empty)); helpFile = fileSystem.RetrieveFile(path); } else if (helpKey.IndexOf("$_SitePath_$") >= 0) { string path = helpKey.Replace("$_SitePath_$", "~/Data/Sites/" + CacheHelper.GetCurrentSiteSettings().SiteId.ToInvariantString()); helpFile = fileSystem.RetrieveFile(path); } else if (helpKey.IndexOf("$_Data_$") >= 0) { string path = helpKey.Replace("$_Data_$", "~/Data"); helpFile = fileSystem.RetrieveFile(path); } else if (helpKey.IndexOf("~/") >= 0) { helpFile = fileSystem.RetrieveFile(helpKey); } else { string path = fileSystem.CombinePath(config.RelativeSolutionLocation, helpKey); helpFile = fileSystem.RetrieveFile(path); } } else { helpText = ResourceHelper.GetHelpFileText(helpKey); helpFile = null; } if (helpFile != null && fileSystem.FileExists(helpFile.VirtualPath)) { //FileInfo file = new FileInfo(helpFilePath); //fileSystem.GetAsStream(helpFile.VirtualPath); //StreamReader sr = file.OpenText(); StreamReader sr = new StreamReader(fileSystem.GetAsStream(helpFile.VirtualPath)); helpText = sr.ReadToEnd(); sr.Close(); } return(helpText); }
public Logic() { this.fs = new FileSystemProvider(); this.dataContainer = fs.load(); }
protected void Page_Load(object sender, EventArgs e) { Page.Header.DataBind(); if (!string.IsNullOrEmpty(Request.QueryString["code"])) { _activityCode = Request.QueryString["code"]; } rblFormMode.Items.Clear(); tsFormMode.Tabs.Clear(); foreach (var mode in EnumHelper.EnumToList <FormMode>()) { rblFormMode.Items.Add(new ListItem(EnumHelper.GetEnumDescription(mode), ((int)mode).ToString())); tsFormMode.Tabs.Add(new Telerik.Web.UI.RadTab(EnumHelper.GetEnumDescription(mode), ((int)mode).ToString())); } rblFormMode.SelectedIndex = 0; lrlCounterCode.Text = HttpUtility.HtmlEncode(ScriptTemplates.Form(CurrentUser.Instance.SiteID, _activityCode) .Replace("$Mode", ((int)FormMode.Inner).ToString()) .Replace("$FromVisit", string.Empty) .Replace("$Through", string.Empty) .Replace("$Period", string.Empty) .Replace("$Parameter", string.Empty)); //rblPeriod.Items.Clear(); foreach (var period in EnumHelper.EnumToList <Period>()) { rblPeriod.Items.Add(new ListItem(EnumHelper.GetEnumDescription(period), ((int)period).ToString())); } foreach (var category in EnumHelper.EnumToList <FormContactCategory>()) { rblContactCategory.Items.Add(new ListItem(EnumHelper.GetEnumDescription(category), ((int)category).ToString())); } rblContactCategory.Items.FindByValue("0").Selected = true; foreach (var align in EnumHelper.EnumToList <PopupAlign>()) { rblPopupAlign.Items.Add(new ListItem("", ((int)align).ToString())); } rblPopupAlign.Items.FindByValue("4").Selected = true; foreach (var effect in EnumHelper.EnumToList <PopupEffectAppear>()) { ddlPopupEffectAppear.Items.Add(new ListItem(EnumHelper.GetEnumDescription(effect), ((int)effect).ToString())); } foreach (var position in EnumHelper.EnumToList <FloatingButtonPosition>()) { ddlFloatingButtonPosition.Items.Add(new ListItem(EnumHelper.GetEnumDescription(position), ((int)position).ToString())); } if (!Page.ClientScript.IsClientScriptIncludeRegistered("FormCodeJS")) { ScriptManager.RegisterClientScriptInclude(this, typeof(FormCode), "FormCodeJS", ResolveUrl("~/Scripts/formcode.js")); } if (!Page.ClientScript.IsClientScriptIncludeRegistered("HighlightJS")) { ScriptManager.RegisterClientScriptInclude(this, typeof(FormCode), "HighlightJS", ResolveUrl("~/Scripts/highlight.pack.js")); } if (!Page.ClientScript.IsClientScriptBlockRegistered("FormCodeTemplateJS")) { var script = string.Format("<script type=\"text/javascript\">var popupFormTemplate = \"{0}\"; var integratedFormTemplate = \"{1}\"; var autocallFormTemplate = \"{2}\"; var floatingButtonFormTemplate = \"{3}\"; var callOnClosingFormTemplate = \"{4}\";$('pre code').each(function(i, e) {{ hljs.highlightBlock(e); }});</script>", HttpUtility.HtmlEncode(ScriptTemplates.PopupForm(CurrentUser.Instance.SiteID, _activityCode)), HttpUtility.HtmlEncode(ScriptTemplates.IntegratedForm(CurrentUser.Instance.SiteID, _activityCode)), HttpUtility.HtmlEncode(ScriptTemplates.AutoCallForm(CurrentUser.Instance.SiteID, _activityCode)), HttpUtility.HtmlEncode(ScriptTemplates.FloatingButtonForm(CurrentUser.Instance.SiteID, _activityCode)), HttpUtility.HtmlEncode(ScriptTemplates.CallOnClosingForm(CurrentUser.Instance.SiteID, _activityCode))).Replace("\r\n", "\\r\\n"); ScriptManager.RegisterClientScriptBlock(this, typeof(FormCode), "FormCodeTemplateJS", script, false); } var fsProvider = new FileSystemProvider(); var floatingButtonDirectory = fsProvider.GetFloatingButtonDirectory(CurrentUser.Instance.SiteID); rfeFloatingButtonIcon.Configuration.ViewPaths = new[] { floatingButtonDirectory }; rfeFloatingButtonIcon.Configuration.UploadPaths = new[] { floatingButtonDirectory }; rfeFloatingButtonIcon.Configuration.DeletePaths = new[] { floatingButtonDirectory }; rfeFloatingButtonIcon.Configuration.MaxUploadFileSize = 1048576; hlSettings.NavigateUrl = UrlsData.AP_Settings("Settings").Replace("/FormCode.aspx", ""); }
private void LoadSettings(HttpContext context) { //logAllFileSystemActivity = WebConfigSettings.LogAllFileManagerActivity; if (context.Request.QueryString["cmd"] != null) { cmd = context.Request.QueryString["cmd"]; } if (context.Request.Params.Get("path") != null) { pipedPath = context.Request.Params.Get("path"); } if (context.Request.QueryString["srcPath"] != null) { pipedSourcePath = context.Request.QueryString["srcPath"]; } if (context.Request.QueryString["destPath"] != null) { pipedTargetPath = context.Request.QueryString["destPath"]; } overwriteExistingFiles = WebConfigSettings.FileManagerOverwriteFiles; if (WebConfigSettings.RequireFileSystemServiceToken) { Guid fileSystemToken = WebUtils.ParseGuidFromQueryString("t", Guid.Empty); if (fileSystemToken != Global.FileSystemToken) { log.Info("Invalid token received by FileService.ashx so blocking access"); return; } } siteRoot = SiteUtils.GetNavigationSiteRoot(); FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider]; if (p == null) { log.Error("Could not load file system provider " + WebConfigSettings.FileSystemProvider); return; } fileSystem = p.GetFileSystem(); if (fileSystem == null) { log.Error("Could not load file system from provider " + WebConfigSettings.FileSystemProvider); return; } virtualPath = GetVirtualPath(SanitizePath(pipedPath)); virtualSourcePath = GetVirtualPath(SanitizePath(pipedSourcePath)); virtualTargetPath = GetVirtualPath(SanitizePath(pipedTargetPath)); if (context.Request.Params["fld"] != null) { virtualTargetPath = context.Request.Params["fld"].Replace("..", string.Empty); } //log.Info(context.Request.RawUrl); if (WebConfigSettings.LogAllFileServiceRequests) { log.Info("virtualPath = " + virtualPath + " virtualSourcePath = " + virtualSourcePath + " virtualTargetPath = " + virtualTargetPath); } }
public void ProceedResources(tbl_SiteActivityRules siteActivityRules) { var externalResources = repository.ExternalResource_SelectByDestinationID(siteActivityRules.ID); if (!externalResources.Any()) { return; } foreach (var resource in externalResources) { switch ((ExternalResourceType)resource.ExternalResourceTypeID) { case ExternalResourceType.JavaScript: var result = string.Empty; if (!string.IsNullOrEmpty(resource.File)) { var fsp = new FileSystemProvider(); var filePath = fsp.GetRemoteLink(siteActivityRules.SiteID, "ExternalResource", resource.File, FileType.Attachment); result += string.Format(@"<script type=""text/javascript"" src=""{0}""></script>", filePath); } if (!string.IsNullOrEmpty(resource.Url)) { result += string.Format(@"<script type=""text/javascript"" src=""{0}""></script>", resource.Url); } if (!string.IsNullOrEmpty(resource.Text)) { if (!resource.Text.Contains("<script")) { result += string.Format(@"<script type=""text/javascript"">{0}</script>", resource.Text); } else { result += resource.Text; } } PutToPlace((ResourcePlace)resource.ResourcePlaceID, result); break; case ExternalResourceType.CSS: var css = string.Empty; if (!string.IsNullOrEmpty(resource.File)) { var fsp = new FileSystemProvider(); var filePath = fsp.GetRemoteLink(siteActivityRules.SiteID, "ExternalResource", resource.File, FileType.Attachment); css += string.Format(@"<link rel=""stylesheet"" type=""text/css"" href=""{0}"" />", filePath); } if (!string.IsNullOrEmpty(resource.Url)) { css += string.Format(@"<link rel=""stylesheet"" type=""text/css"" href=""{0}"" />", resource.Url); } if (!string.IsNullOrEmpty(resource.Text)) { if (!resource.Text.Contains("<style")) { css += string.Format(@"<style type=""text/css"">{0}</style>", resource.Text); } else { css += resource.Text; } } PutToPlace((ResourcePlace)resource.ResourcePlaceID, css); break; } } }
internal RootDirectory(Core.Core core, FileSystemProvider fileSystem) { this.core = core; m_MyDirectory = new MyDirectory(fileSystem); }
private dynamic LoadSettings(QueryParams queryParams) { IFileSystem fileSystem = null; SiteSettings siteSettings = null; ILog log = LogManager.GetLogger(typeof(FileServiceController)); siteSettings = CacheHelper.GetCurrentSiteSettings(); if (siteSettings == null) { log.Info(Resource.FileSystemSiteSettingsNotLoaded); } FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider]; if (p == null) { log.Info(string.Format(Resource.FileSystemProviderNotLoaded, WebConfigSettings.FileSystemProvider)); } fileSystem = p.GetFileSystem(); if (fileSystem == null) { log.Info(string.Format(Resource.FileSystemNotLoadedFromProvider, WebConfigSettings.FileSystemProvider)); } var virtualPath = VirtualPathUtility.RemoveTrailingSlash(fileSystem.FileBaseUrl + fileSystem.VirtualRoot.Replace("~", string.Empty)); var rootName = virtualPath.Split('/'); var model = new Models.FileManager { OverwriteFiles = WebConfigSettings.FileManagerOverwriteFiles, FileSystemToken = Global.FileSystemToken.ToString(), RootName = rootName[rootName.Count() - 1], VirtualPath = virtualPath, ReturnFullPath = queryParams.returnFullPath, View = Request.QueryString.Get("view"), Type = queryParams.type, Editor = queryParams.editor, InputId = queryParams.inputId, CKEditorFuncNumber = queryParams.CKEditorFuncNum, QueryString = queryParams, Upload = WebUser.IsInRoles(siteSettings.GeneralBrowseAndUploadRoles) ? "true" : "false", Rename = WebUser.IsInRoles(siteSettings.GeneralBrowseAndUploadRoles) ? "true" : "false", Move = WebUser.IsInRoles(siteSettings.GeneralBrowseAndUploadRoles) ? "true" : "false", Copy = WebUser.IsInRoles(siteSettings.GeneralBrowseAndUploadRoles) ? "true" : "false", Edit = WebUser.IsInRoles(siteSettings.GeneralBrowseAndUploadRoles) ? "true" : "false", Compress = WebUser.IsInRoles(siteSettings.GeneralBrowseAndUploadRoles) ? "true" : "false", CompressChooseName = "true", Extract = WebUser.IsInRoles(siteSettings.GeneralBrowseAndUploadRoles) ? "true" : "false", Download = "true", DownloadMultiple = "true", Preview = "true", Remove = WebUser.IsInRoles(siteSettings.RolesThatCanDeleteFilesInEditor) || WebUser.IsContentAdmin ? "true" : "false", CreateFolder = WebUser.IsInRoles(siteSettings.GeneralBrowseAndUploadRoles) ? "true" : "false", PagePickerLinkText = Resource.FileManagerPagePickerLink, BackToWebsiteLinkText = Resource.FileManagerBackToWebsite, BackToFileManagerLinkText = Resource.FileManagerBackToManagerLink }; return(model); }
/// <summary> /// Opens or creates a file for reading and/or writing, returning an /// asynchronous file channel to access the file. /// /// <para> The {@code options} parameter determines how the file is opened. /// The <seealso cref="StandardOpenOption#READ READ"/> and {@link StandardOpenOption#WRITE /// WRITE} options determines if the file should be opened for reading and/or /// writing. If neither option is contained in the array then an existing file /// is opened for reading. /// /// </para> /// <para> In addition to {@code READ} and {@code WRITE}, the following options /// may be present: /// /// <table border=1 cellpadding=5 summary=""> /// <tr> <th>Option</th> <th>Description</th> </tr> /// <tr> /// <td> <seealso cref="StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING"/> </td> /// <td> When opening an existing file, the file is first truncated to a /// size of 0 bytes. This option is ignored when the file is opened only /// for reading.</td> /// </tr> /// <tr> /// <td> <seealso cref="StandardOpenOption#CREATE_NEW CREATE_NEW"/> </td> /// <td> If this option is present then a new file is created, failing if /// the file already exists. When creating a file the check for the /// existence of the file and the creation of the file if it does not exist /// is atomic with respect to other file system operations. This option is /// ignored when the file is opened only for reading. </td> /// </tr> /// <tr> /// <td > <seealso cref="StandardOpenOption#CREATE CREATE"/> </td> /// <td> If this option is present then an existing file is opened if it /// exists, otherwise a new file is created. When creating a file the check /// for the existence of the file and the creation of the file if it does /// not exist is atomic with respect to other file system operations. This /// option is ignored if the {@code CREATE_NEW} option is also present or /// the file is opened only for reading. </td> /// </tr> /// <tr> /// <td > <seealso cref="StandardOpenOption#DELETE_ON_CLOSE DELETE_ON_CLOSE"/> </td> /// <td> When this option is present then the implementation makes a /// <em>best effort</em> attempt to delete the file when closed by the /// the <seealso cref="#close close"/> method. If the {@code close} method is not /// invoked then a <em>best effort</em> attempt is made to delete the file /// when the Java virtual machine terminates. </td> /// </tr> /// <tr> /// <td><seealso cref="StandardOpenOption#SPARSE SPARSE"/> </td> /// <td> When creating a new file this option is a <em>hint</em> that the /// new file will be sparse. This option is ignored when not creating /// a new file. </td> /// </tr> /// <tr> /// <td> <seealso cref="StandardOpenOption#SYNC SYNC"/> </td> /// <td> Requires that every update to the file's content or metadata be /// written synchronously to the underlying storage device. (see <a /// href="../file/package-summary.html#integrity"> Synchronized I/O file /// integrity</a>). </td> /// </tr> /// <tr> /// <td> <seealso cref="StandardOpenOption#DSYNC DSYNC"/> </td> /// <td> Requires that every update to the file's content be written /// synchronously to the underlying storage device. (see <a /// href="../file/package-summary.html#integrity"> Synchronized I/O file /// integrity</a>). </td> /// </tr> /// </table> /// /// </para> /// <para> An implementation may also support additional options. /// /// </para> /// <para> The {@code executor} parameter is the <seealso cref="ExecutorService"/> to /// which tasks are submitted to handle I/O events and dispatch completion /// results for operations initiated on resulting channel. /// The nature of these tasks is highly implementation specific and so care /// should be taken when configuring the {@code Executor}. Minimally it /// should support an unbounded work queue and should not run tasks on the /// caller thread of the <seealso cref="ExecutorService#execute execute"/> method. /// Shutting down the executor service while the channel is open results in /// unspecified behavior. /// /// </para> /// <para> The {@code attrs} parameter is an optional array of file {@link /// FileAttribute file-attributes} to set atomically when creating the file. /// /// </para> /// <para> The new channel is created by invoking the {@link /// FileSystemProvider#newFileChannel newFileChannel} method on the /// provider that created the {@code Path}. /// /// </para> /// </summary> /// <param name="file"> /// The path of the file to open or create </param> /// <param name="options"> /// Options specifying how the file is opened </param> /// <param name="executor"> /// The thread pool or {@code null} to associate the channel with /// the default thread pool </param> /// <param name="attrs"> /// An optional list of file attributes to set atomically when /// creating the file /// </param> /// <returns> A new asynchronous file channel /// </returns> /// <exception cref="IllegalArgumentException"> /// If the set contains an invalid combination of options </exception> /// <exception cref="UnsupportedOperationException"> /// If the {@code file} is associated with a provider that does not /// support creating asynchronous file channels, or an unsupported /// open option is specified, or the array contains an attribute that /// cannot be set atomically when creating the file </exception> /// <exception cref="IOException"> /// If an I/O error occurs </exception> /// <exception cref="SecurityException"> /// If a security manager is installed and it denies an /// unspecified permission required by the implementation. /// In the case of the default provider, the {@link /// SecurityManager#checkRead(String)} method is invoked to check /// read access if the file is opened for reading. The {@link /// SecurityManager#checkWrite(String)} method is invoked to check /// write access if the file is opened for writing </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public static AsynchronousFileChannel open(Path file, java.util.Set<? extends OpenOption> options, java.util.concurrent.ExecutorService executor, java.nio.file.attribute.FileAttribute<?>... attrs) throws java.io.IOException //JAVA TO C# CONVERTER TODO TASK: Java wildcard generics are not converted to .NET: public static AsynchronousFileChannel open <T1>(Path file, Set <T1> options, ExecutorService executor, params FileAttribute <?>[] attrs) where T1 : OpenOption { FileSystemProvider provider = file.FileSystem.Provider(); return(provider.NewAsynchronousFileChannel(file, options, executor, attrs)); }
public FileService.ReturnObject UploadFiles() { FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider]; if (p == null) { log.Error(string.Format(Resource.FileSystemProviderNotLoaded, WebConfigSettings.FileSystemProvider)); return(new FileService.ReturnObject(new FileService.ReturnMessage { Success = false, Error = string.Format(Resource.FileSystemProviderNotLoaded, WebConfigSettings.FileSystemProvider) })); } fileSystem = p.GetFileSystem(); if (fileSystem == null) { log.Error(string.Format(Resource.FileSystemNotLoadedFromProvider, WebConfigSettings.FileSystemProvider)); return(new FileService.ReturnObject(new FileService.ReturnMessage { Success = false, Error = string.Format(Resource.FileSystemNotLoadedFromProvider, WebConfigSettings.FileSystemProvider) })); } virtualPath = fileSystem.VirtualRoot; var context = HttpContext.Current; HttpFileCollection files = context.Request.Files.Count > 0 ? context.Request.Files : null; OpResult results = OpResult.Error; StringBuilder errors = new StringBuilder(); SiteSettings siteSettings = CacheHelper.GetCurrentSiteSettings(); string uploadPath = virtualPath; bool canUpload = ( WebUser.IsAdminOrContentAdmin || SiteUtils.UserIsSiteEditor() || WebUser.IsInRoles(siteSettings.GeneralBrowseAndUploadRoles) || WebUser.IsInRoles(siteSettings.UserFilesBrowseAndUploadRoles) || WebUser.IsInRoles(siteSettings.RolesThatCanDeleteFilesInEditor) ); if (files.Count == 0) { log.Info(Resource.NoFileSelectedWarning); return(new FileService.ReturnObject(new FileService.ReturnMessage { Success = false, Error = Resource.NoFileSelectedWarning })); } if (WebConfigSettings.DisableFileManager) { log.Info(Resource.FileManagerDisabledMessage); return(new FileService.ReturnObject(new FileService.ReturnMessage { Success = false, Error = Resource.FileManagerDisabledMessage })); } if (siteSettings == null) { return(new FileService.ReturnObject(new FileService.ReturnMessage { Success = false, Error = Resource.FileSystemSiteSettingsNotLoaded })); } if (!canUpload) { return(new FileService.ReturnObject(new FileService.ReturnMessage { Success = false, Error = Resource.AccessDenied })); } if (context.Request.Form.Get("destination") != null) { uploadPath = FilePath(VirtualPathUtility.AppendTrailingSlash(context.Request.Form.Get("destination"))); } if (files != null) { var fileUploadsRemaining = fileSystem.Permission.MaxFiles - fileSystem.CountAllFiles(); if (fileUploadsRemaining < files.Count) { string errorMessage = string.Empty; log.Info("upload rejected due to fileSystem.Permission.MaxFiles"); if (fileUploadsRemaining == 0) { errorMessage = Resource.FileSystemFileLimitReached; } else { errorMessage = string.Format(Resource.FileSystemFileLimitRemainder, fileUploadsRemaining); } return(new FileService.ReturnObject(new FileService.ReturnMessage { Success = false, Error = errorMessage })); } for (int f = 0; f < files.Count; f++) { HttpPostedFile file = files[f]; bool doUpload = true; if (file.ContentLength > fileSystem.Permission.MaxSizePerFile) { log.Info(Resource.FileSystemFileTooLargeError); errors.AppendLine(Resource.FileSystemFileTooLargeError); doUpload = false; } else if (fileSystem.GetTotalSize() + file.ContentLength >= fileSystem.Permission.Quota) { log.Info(Resource.FileSystemStorageQuotaError); errors.AppendLine(Resource.FileSystemStorageQuotaError); doUpload = false; } if (!fileSystem.Permission.IsExtAllowed(VirtualPathUtility.GetExtension(file.FileName))) { log.Info(Resource.FileTypeNotAllowed); errors.AppendLine(Resource.FileTypeNotAllowed); doUpload = false; } string destPath = VirtualPathUtility.Combine(uploadPath, Path.GetFileName(file.FileName).ToCleanFileName(WebConfigSettings.ForceLowerCaseForUploadedFiles)); string ext = Path.GetExtension(file.FileName); string mimeType = file.ContentType; if (doUpload) { using (Stream s = file.InputStream) { results = fileSystem.SaveFile(destPath, s, mimeType, true); } if (results != OpResult.Succeed) { errors.AppendLine(results.ToString()); } } } if (errors.Length > 0) { return(new FileService.ReturnObject(new FileService.ReturnMessage { Success = false, Error = errors.ToString() })); } return(new FileService.ReturnObject(new FileService.ReturnMessage { Success = true })); } else { return(new FileService.ReturnObject(new FileService.ReturnMessage { Success = false, Error = Resource.NoFileSelectedWarning })); } }
private FileService.ReturnMessage LoadSettings(FileService.RequestObject request, string t) { allowEditing = WebConfigSettings.AllowFileEditInFileManager; overwriteExistingFiles = WebConfigSettings.FileManagerOverwriteFiles; siteSettings = CacheHelper.GetCurrentSiteSettings(); if (siteSettings == null) { return(new FileService.ReturnMessage { Success = false, Error = Resource.FileSystemSiteSettingsNotLoaded }); } if (WebConfigSettings.RequireFileSystemServiceToken && (t != Global.FileSystemToken.ToString())) { log.Info(Resource.FileSystemInvalidToken); return(new FileService.ReturnMessage { Success = false, Error = Resource.FileSystemInvalidToken }); } FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider]; if (p == null) { log.Error(string.Format(Resource.FileSystemProviderNotLoaded, WebConfigSettings.FileSystemProvider)); return(new FileService.ReturnMessage { Success = false, Error = string.Format(Resource.FileSystemProviderNotLoaded, WebConfigSettings.FileSystemProvider) }); } fileSystem = p.GetFileSystem(); if (fileSystem == null) { log.Error(string.Format(Resource.FileSystemNotLoadedFromProvider, WebConfigSettings.FileSystemProvider)); return(new FileService.ReturnMessage { Success = false, Error = string.Format(Resource.FileSystemNotLoadedFromProvider, WebConfigSettings.FileSystemProvider) }); } virtualPath = fileSystem.VirtualRoot; if (WebUser.IsAdminOrContentAdmin || SiteUtils.UserIsSiteEditor() || WebUser.IsInRoles(siteSettings.GeneralBrowseAndUploadRoles + siteSettings.GeneralBrowseRoles)) { allowedExtensions = WebConfigSettings.AllowedUploadFileExtensions; } else if (WebUser.IsInRoles(siteSettings.UserFilesBrowseAndUploadRoles)) { currentUser = SiteUtils.GetCurrentSiteUser(); if (currentUser == null) { return(new FileService.ReturnMessage { Success = false, Error = Resource.FileSystemUserNotAuthorized }); } allowedExtensions = WebConfigSettings.AllowedLessPriveledgedUserUploadFileExtensions; } if (WebConfigSettings.LogAllFileServiceRequests) { StringBuilder message = new StringBuilder(); message.AppendLine("\nFile Manager Activity:"); message.AppendFormat("Request Action: {0}\n", request.Action); if (request.CompressedFilename != null) { message.AppendFormat("CompressedFilename: {0}\n", request.CompressedFilename); } if (request.Content != null) { message.AppendFormat("Content: {0}\n", request.Content); } if (request.Destination != null) { message.AppendFormat("Destination: {0}\n", request.Destination); } if (request.Item != null) { message.AppendFormat("Item: {0}\n", request.Item); } if (request.Items != null) { message.AppendFormat("Items: {0}\n", request.Items); } if (request.NewItemPath != null) { message.AppendFormat("NewItemPath: {0}\n", request.NewItemPath); } if (request.NewPath != null) { message.AppendFormat("NewPath: {0}\n", request.NewPath); } if (request.FolderName != null) { message.AppendFormat("FolderName: {0}\n", request.FolderName); } if (request.Path != null) { message.AppendFormat("Path: {0}\n", request.Path); } if (request.Perms != null) { message.AppendFormat("Perms: {0}\n", request.Perms); } if (request.PermsCode != null) { message.AppendFormat("PermsCode: {0}\n", request.PermsCode); } if (request.Recursive != null) { message.AppendFormat("Recursive: {0}\n", request.Recursive); } if (request.SingleFileName != null) { message.AppendFormat("SingleFileName: {0}\n", request.SingleFileName); } if (request.ToFilename != null) { message.AppendFormat("ToFilename: {0}\n", request.ToFilename); } log.Info(message); } return(new FileService.ReturnMessage { Success = true }); }
private void EnsureItems() { FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider]; if (p == null) { log.Error("File System Provider Could Not Be Loaded."); return; } IFileSystem fileSystem = p.GetFileSystem(); if (fileSystem == null) { log.Error("File System Could Not Be Loaded."); return; } //string virtualPath = fileSystem.VirtualRoot; if (ddDefinitions == null) { ddDefinitions = new DropDownList(); if (this.Controls.Count == 0) { this.Controls.Add(ddDefinitions); } } if (ddDefinitions.Items.Count > 0) { return; } string siteSuperFlexiPath = "~/Data/Sites/" + siteSettings.SiteId.ToInvariantString() + "/SuperFlexi/"; string globalSuperFlexiPath = "~/Data/SuperFlexi/"; Dictionary <string, string> solutions = new Dictionary <string, string>(); List <string> names = new List <string>(); List <SolutionFileLocation> solutionLocations = new List <SolutionFileLocation>() { new SolutionFileLocation { Path = siteSuperFlexiPath + "Solutions/", Extension = ".sfmarkup", RecurseLevel = RecurseLevel.OneLevel, Global = false }, new SolutionFileLocation { Path = siteSuperFlexiPath + "MarkupDefinitions/", Extension = ".config", RecurseLevel = RecurseLevel.TopDirectoryOnly, Global = false }, new SolutionFileLocation { Path = globalSuperFlexiPath + "Solutions/", Extension = ".sfmarkup", RecurseLevel = RecurseLevel.OneLevel, Global = true }, new SolutionFileLocation { Path = globalSuperFlexiPath + "MarkupDefinitions/", Extension = ".config", RecurseLevel = RecurseLevel.TopDirectoryOnly, Global = true } }; foreach (var location in solutionLocations) { //WebFolder folder = new WebFolder(); //DirectoryInfo dir = new DirectoryInfo(HttpContext.Current.Server.MapPath(location.Path)); //if (dir.Exists) if (fileSystem.FolderExists(location.Path)) { List <WebFile> files = new List <WebFile>(); switch (location.RecurseLevel) { case RecurseLevel.OneLevel: var folders = fileSystem.GetFolderList(location.Path); foreach (var folder in folders) { files.AddRange(fileSystem.GetFileList(folder.VirtualPath).Where(f => f.Extension.ToLower() == location.Extension)); } break; case RecurseLevel.TopDirectoryOnly: files.AddRange(fileSystem.GetFileList(location.Path).Where(f => f.Extension.ToLower() == location.Extension)); break; } //foreach (FileInfo file in dir.GetFiles(location.Pattern, location.SearchOption)) foreach (var file in files) { //if (File.Exists(file.FullName)) //{ string nameAppendage = string.Empty; if (location.Global) { nameAppendage = " (global)"; } XmlDocument doc = new XmlDocument(); doc.Load(file.Path); XmlNode node = doc.DocumentElement.SelectSingleNode("/Definitions/MarkupDefinition"); if (node != null) { XmlAttributeCollection attrCollection = node.Attributes; string solutionName = string.Empty; if (attrCollection["name"] != null) { solutionName = attrCollection["name"].Value + nameAppendage;; } else { solutionName = file.Name.ToString().ToLower().Replace(location.Extension, "") + nameAppendage;; } names.Add(solutionName); if (solutions.ContainsKey(solutionName)) { solutionName += string.Format(" [{0}]", names.Where(n => n.Equals(solutionName)).Count()); } //todo: add capability to nest folders in a solution folder? solutions.Add( solutionName, //location.Path + (location.RecurseLevel == RecurseLevel.ImmediateSubDirectory ? file.Directory.Name + "/" : "") + file.Name); file.VirtualPath.Replace("\\", "/").TrimStart('~')); } //} } } } ddDefinitions.DataSource = solutions.OrderBy(i => i.Key); ddDefinitions.DataTextField = "Key"; ddDefinitions.DataValueField = "Value"; ddDefinitions.DataBind(); ddDefinitions.Items.Insert(0, new ListItem(SuperFlexiResources.SolutionDropDownPleaseSelect, "0")); }
private void LoadSettings() { timeZone = SiteUtils.GetUserTimeZone(); virtualSourcePath = $"~/Data/Sites/{siteSettings.SiteId.ToInvariantString()}/SharedFiles/"; virtualHistoryPath = $"~/Data/Sites/{siteSettings.SiteId.ToInvariantString()}/SharedFiles/History/"; lnkCancelFile.NavigateUrl = SiteUtils.GetCurrentPageUrl(); lnkCancelFolder.NavigateUrl = lnkCancelFile.NavigateUrl; //this page handles both folders and files //expected strItem examples are 23~folder and 13~file //the number portion is the ItemID of the folder or file if (strItem.IndexOf("~") > -1) { try { char[] separator = { '~' }; string[] args = strItem.Split(separator); itemId = int.Parse(args[0]); type = args[1]; } catch { }; } Hashtable moduleSettings = ModuleSettings.GetModuleSettings(moduleId); config = new SharedFilesConfiguration(moduleSettings); divHistory.Visible = config.EnableVersioning; uploader.UploadButtonClientId = btnUpload.ClientID; uploader.ServiceUrl = SiteRoot + "/SharedFiles/upload.ashx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString() + "&ItemID=" + itemId.ToInvariantString(); uploader.FormFieldClientId = hdnCurrentFolderId.ClientID; string refreshFunction = "function refresh" + moduleId.ToInvariantString() + " () { window.location.reload(true); } "; uploader.UploadCompleteCallback = $"refresh{moduleId.ToInvariantString()}"; ScriptManager.RegisterClientScriptBlock( this, GetType(), $"refresh{moduleId.ToInvariantString()}", refreshFunction, true ); AddClassToBody("sharedfilesedit"); FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider]; if (p == null) { return; } fileSystem = p.GetFileSystem(); }
public static bool Init(ISettings settings) { if (loaded == true) { throw new Exception ("Please only call this method once."); } if (settings == null) { throw new ArgumentNullException("settings"); } Core.Settings = settings; string pidFilePath = Path.Combine(Core.Settings.DataPath, "meshwork.pid"); if (File.Exists(pidFilePath)) { int processId = -1; Int32.TryParse(File.ReadAllText(pidFilePath), out processId); try { Process.GetProcessById(processId); Console.Error.WriteLine("Meshwork is already running (PID {0})!", processId); return false; } catch (ArgumentException) { File.Delete(pidFilePath); } } File.WriteAllText(pidFilePath, Process.GetCurrentProcess().Id.ToString()); if (settings.KeyEncrypted) { PasswordPrompt(null, EventArgs.Empty); if (!settings.KeyUnlocked) { // Quit! return false; } } rsaProvider = new RSACryptoServiceProvider(); rsaProvider.ImportParameters(settings.EncryptionParameters); nodeID = Common.SHA512Str(rsaProvider.ToXmlString(false)); fileSystem = new FileSystemProvider(); shareBuilder = new ShareBuilder(); shareBuilder.FinishedIndexing += ShareBuilder_FinishedIndexing; shareWatcher = new ShareWatcher(); shareHasher = new ShareHasher(); transportManager = new TransportManager (); fileTransferManager = new FileTransferManager(); fileSearchManager = new FileSearchManager(); destinationManager = new DestinationManager(); // XXX: Use reflection to load these: destinationManager.RegisterSource(new TCPIPv4DestinationSource()); destinationManager.RegisterSource(new TCPIPv6DestinationSource()); MonoTorrent.Client.Tracker.TrackerFactory.Register("meshwork", typeof(MeshworkTracker)); ITransportListener tcpListener = new TcpTransportListener(Core.Settings.TcpListenPort); transportListeners.Add(tcpListener); loaded = true; if (FinishedLoading != null) { FinishedLoading(null, EventArgs.Empty); } return true; }
public static long FileSize(string fileName) { return(FileSystemProvider.GetFileSize(fileName)); }