// GET: MultiFileUpload public MultiFileUploadController(OpenAccessContext context, FileService fileService, EntityService entityService, IFileMailer fileMailer) : base(context) { _fileService = fileService; _entityService = entityService; _fileMailer = fileMailer; }
private string SaveTempFile() { FileService fileService = new FileService(); TranFileInfo file = new TranFileInfo() { CompanyInfo = string.Empty, Id = Guid.NewGuid().ToString(), UserInfo = WebSecurity.CurrentUserName, UploadStartDate = DateTime.Now }; string fileSavePath = string.Empty; if (HttpContext.Current.Request.Files.AllKeys.Any()) { var httpPostedFile = HttpContext.Current.Request.Files["UploadedFile"]; if (httpPostedFile != null) { fileSavePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Format(@"data\tmp\{0}_{1}_{2}.csv", httpPostedFile.FileName, Guid.NewGuid(), DateTime.Now.ToString("dd.MM.yyyy"))); httpPostedFile.SaveAs(fileSavePath); file.Path = fileSavePath; file.UploadEndDate = DateTime.Now; file.UploadTime = file.UploadEndDate - file.UploadStartDate; fileService.Create(file); } } return file.Id; }
public void CanRetrieveLines() { FileService fileService = new FileService(); var files = fileService.RetrieveLinesFromFile(); Assert.AreEqual(81790, files.Length); }
public void DeleteMedia_NormalCase_Deleted() { Mock<ILoggerService> loggerService = new Mock<ILoggerService>(); loggerService.SetupSequence(o => o.Log(It.IsAny<Log>())).Returns(true); FileService Service = new FileService(loggerService.Object); bool flag = Service.DeleteMedia(this.StoredMedia); Assert.IsTrue(flag); }
public void SaveMedia_NormalCase_Saved() { Mock<ILoggerService> loggerService = new Mock<ILoggerService>(); loggerService.SetupSequence(o => o.Log(It.IsAny<Log>())).Returns(true); FileService Service = new FileService(loggerService.Object); string path = "/test.txt"; bool flag = Service.SaveMedia(path, new byte[1]); Assert.IsTrue(flag); }
public void GetMedia_NormalCase_Saved() { Mock<ILoggerService> loggerService = new Mock<ILoggerService>(); loggerService.SetupSequence(o => o.Log(It.IsAny<Log>())).Returns(true); FileService Service = new FileService(loggerService.Object); byte[] retrieved = Service.GetMedia(this.StoredMedia); Assert.AreEqual("System.Byte[]", retrieved.ToString()); }
private string GetNativeTestLibraryLocation() { string path = Paths.Combine(Paths.GetDirectory((new Uri(typeof(LoadLibraryTests).Assembly.CodeBase)).LocalPath), NativeTestLibrary); IFileService system = new FileService(new ExtendedFileService()); if (!system.FileExists(path)) { throw new System.IO.FileNotFoundException(path); } return path; }
/// <summary> /// Initiate the controllerModul /// </summary> private void InitiateController() { Logger.LogInfo("New Program start"); fileService = new FileService(this); networkService = new NetworkService(this); graphicControl = new GraphicalInterfaceController(this, chatForm); Logger.LogInfo("Start network service."); networkService.Start(); }
public void CreateInfoForRootDrive(string prefix) { string driveRoot = prefix + Paths.GetPathRoot(Path.GetTempPath()); FileService fileService = new FileService(); var info = fileService.GetPathInfo(driveRoot); info.Should().BeAssignableTo<IDirectoryInformation>(); info.Exists.Should().BeTrue(); info.Name.Should().Be(driveRoot); info.Path.Should().Be(driveRoot); }
public void CreateLongPathNestedDirectoryTest() { using (var cleaner = new TestFileCleaner(false)) { string longPath = PathGenerator.CreatePathOfLength(cleaner.TempFolder, 300); FileService fileService = new FileService(); fileService.CreateDirectory(longPath); NativeMethods.FileManagement.FileExists(longPath).Should().BeFalse(); NativeMethods.FileManagement.DirectoryExists(longPath).Should().BeTrue(); } }
public void CreateDirectoryTest() { using (var cleaner = new TestFileCleaner()) { string directoryPath = Paths.Combine(cleaner.TempFolder, Path.GetRandomFileName()); FileService fileService = new FileService(); fileService.CreateDirectory(directoryPath); File.Exists(directoryPath).Should().BeFalse(); Directory.Exists(directoryPath).Should().BeTrue(); } }
public void CreateStreamsWithDifficultNames(string fileName) { using (var cleaner = new TestFileCleaner()) { FileService fileService = new FileService(); string filePath = Paths.Combine(cleaner.TempFolder, fileName); using (Stream fileStream = fileService.CreateFileStream(filePath, FileMode.CreateNew)) { fileStream.Should().NotBeNull(); fileService.FileExists(filePath).Should().BeTrue(); } } }
static void Main(string[] args) { Console.WriteLine("Downloading to c:\\"); FileData.ClientFolder = @"c:\"; Console.WriteLine("Enter the name of the file to download."); Console.WriteLine("This is a file in the server's download directory."); Console.WriteLine("The download directory is c:\\temp by default."); Console.Write("> "); string file = Console.ReadLine(); FileService proxy = new FileService(); Console.WriteLine(); Console.WriteLine("Starting download."); proxy.DownloadFile(file); Console.WriteLine("Download complete."); Console.ReadLine(); }
public void DefaultEnumerate() { using (var cleaner = new TestFileCleaner()) { string directoryPath = Paths.Combine(cleaner.TempFolder, Path.GetRandomFileName()); Directory.CreateDirectory(directoryPath); string filePath = Paths.Combine(directoryPath, Path.GetRandomFileName()); File.WriteAllText(filePath, "DefaultEnumerate"); FileService fileService = new FileService(); var directoryInfo = fileService.GetPathInfo(directoryPath) as IDirectoryInformation; directoryInfo.Should().NotBeNull(); var files = directoryInfo.EnumerateChildren().ToArray(); files.Should().HaveCount(1); files[0].Path.Should().Be(filePath); } }
public void EnumerateNestedFilteredFile() { using (var cleaner = new TestFileCleaner()) { string directoryPath = Paths.Combine(cleaner.TempFolder, Path.GetRandomFileName()); var createdDirectory = Directory.CreateDirectory(directoryPath); string fileName = Path.GetRandomFileName(); string filePath = Paths.Combine(directoryPath, fileName); File.WriteAllText(filePath, "DefaultEnumerate"); createdDirectory.Attributes = createdDirectory.Attributes |= FileAttributes.Hidden; FileService fileService = new FileService(); var directoryInfo = fileService.GetPathInfo(cleaner.TempFolder) as IDirectoryInformation; directoryInfo.Should().NotBeNull(); var files = directoryInfo.EnumerateChildren(ChildType.File, fileName, SearchOption.AllDirectories).ToArray(); files.Should().HaveCount(0); createdDirectory.Attributes = createdDirectory.Attributes &= ~FileAttributes.Hidden; } }
// GET: Files public async Task<ActionResult> Index() { List<File> myFiles = new List<File>(); FileService _fileService = new FileService(); try { myFiles = await _fileService.GetMyFilesAsync(); } catch (AdalException e) { if (e.ErrorCode == AdalError.FailedToAcquireTokenSilently) { //This exception is thrown when either you have a stale access token, or you attempted to access a resource that you don't have permissions to access. throw e; } } return View(myFiles); }
private TranFileInfo SaveTempFile(string tranType) { FileService fileService = new FileService(); TranFileInfo file = new TranFileInfo() { CompanyInfo = string.Empty, Id = Guid.NewGuid().ToString(), UserInfo = WebSecurity.CurrentUserName, UploadStartDate = DateTime.Now }; string fileSavePath = string.Empty; if (HttpContext.Current.Request.Files.AllKeys.Any()) { var httpPostedFile = HttpContext.Current.Request.Files["upload"]; if (httpPostedFile != null) { var processor = TransactionHelper.GetDynamicTransactionProcessor(tranType); string tableName = processor.UploadFile(tranType, httpPostedFile.InputStream, file.Id); file.FileName = httpPostedFile.FileName; file.Path = fileSavePath; file.UploadEndDate = DateTime.Now; file.UploadTime = file.UploadEndDate - file.UploadStartDate; file.ContentLocation = FileContentLocation.TempTable; file.TempTableName = tableName; file.TransactionType = tranType; fileService.Create(file); } } return file; }
public static void InitApp( string applicationId, string secretKey, string version ) { if( string.IsNullOrEmpty( applicationId ) ) throw new ArgumentNullException( ExceptionMessage.NULL_APPLICATION_ID ); if( string.IsNullOrEmpty( secretKey ) ) throw new ArgumentNullException(ExceptionMessage.NULL_SECRET_KEY); if( string.IsNullOrEmpty( version ) ) throw new ArgumentNullException(ExceptionMessage.NULL_VERSION); AppId = applicationId; SecretKey = secretKey; VersionNum = version; Persistence = new PersistenceService(); Data = Persistence; Geo = new GeoService(); Messaging = new MessagingService(); Files = new FileService(); UserService = new UserService(); Events = Events.GetInstance(); Cache = Cache.GetInstance(); Counters = CounterService.GetInstance(); Logging = new LoggingService(); CustomService = new CustomService(); MessageWriter.DefaultWriter = new UnderflowWriter(); MessageWriter.AddAdditionalTypeWriter( typeof( BackendlessUser ), new BackendlessUserWriter() ); ORBConfig.GetInstance().getObjectFactories().AddArgumentObjectFactory( typeof( BackendlessUser ).FullName, new BackendlessUserFactory() ); HeadersManager.CleanHeaders(); LoginStorage loginStorage = new LoginStorage(); if( loginStorage.HasData ) HeadersManager.GetInstance().AddHeader( HeadersEnum.USER_TOKEN_KEY, loginStorage.UserToken ); }
static void Notify(SvnNotifyEventArgs e, NotifData notifData, IProgressMonitor monitor) { string actiondesc; string file = e.Path; bool skipEol = false; bool notifyChange = false; switch (e.Action) { case SvnNotifyAction.Skip: if (e.ContentState == SvnNotifyState.Missing) { actiondesc = string.Format(GettextCatalog.GetString("Skipped missing target: '{0}'"), file); } else { actiondesc = string.Format(GettextCatalog.GetString("Skipped '{0}'"), file); } break; case SvnNotifyAction.UpdateDelete: actiondesc = string.Format(GettextCatalog.GetString("Deleted '{0}'"), file); break; case SvnNotifyAction.UpdateAdd: if (e.ContentState == SvnNotifyState.Conflicted) { actiondesc = string.Format(GettextCatalog.GetString("Conflict {0}"), file); } else { actiondesc = string.Format(GettextCatalog.GetString("Added {0}"), file); } break; case SvnNotifyAction.Restore: actiondesc = string.Format(GettextCatalog.GetString("Restored '{0}'"), file); break; case SvnNotifyAction.Revert: actiondesc = string.Format(GettextCatalog.GetString("Reverted '{0}'"), file); break; case SvnNotifyAction.RevertFailed: actiondesc = string.Format(GettextCatalog.GetString("Failed to revert '{0}' -- try updating instead."), file); break; case SvnNotifyAction.Resolved: actiondesc = string.Format(GettextCatalog.GetString("Resolved conflict state of '{0}'"), file); break; case SvnNotifyAction.Add: if (e.MimeTypeIsBinary) { actiondesc = string.Format(GettextCatalog.GetString("Add (bin) '{0}'"), file); } else { actiondesc = string.Format(GettextCatalog.GetString("Add '{0}'"), file); } break; case SvnNotifyAction.Delete: actiondesc = string.Format(GettextCatalog.GetString("Delete '{0}'"), file); break; case SvnNotifyAction.UpdateUpdate: actiondesc = string.Format(GettextCatalog.GetString("Update '{0}'"), file); notifyChange = true; break; case SvnNotifyAction.UpdateExternal: actiondesc = string.Format(GettextCatalog.GetString("Fetching external item into '{0}'"), file); break; case SvnNotifyAction.UpdateCompleted: // TODO actiondesc = GettextCatalog.GetString("Finished"); break; case SvnNotifyAction.StatusExternal: actiondesc = string.Format(GettextCatalog.GetString("Performing status on external item at '{0}'"), file); break; case SvnNotifyAction.StatusCompleted: actiondesc = string.Format(GettextCatalog.GetString("Status against revision: '{0}'"), e.Revision); break; case SvnNotifyAction.CommitDeleted: actiondesc = string.Format(GettextCatalog.GetString("Deleting {0}"), file); break; case SvnNotifyAction.CommitModified: actiondesc = string.Format(GettextCatalog.GetString("Sending {0}"), file); notifyChange = true; break; case SvnNotifyAction.CommitAdded: if (e.MimeTypeIsBinary) { actiondesc = string.Format(GettextCatalog.GetString("Adding (bin) '{0}'"), file); } else { actiondesc = string.Format(GettextCatalog.GetString("Adding '{0}'"), file); } break; case SvnNotifyAction.CommitReplaced: actiondesc = string.Format(GettextCatalog.GetString("Replacing {0}"), file); notifyChange = true; break; case SvnNotifyAction.CommitSendData: if (!notifData.SendingData) { notifData.SendingData = true; actiondesc = GettextCatalog.GetString("Transmitting file data"); } else { actiondesc = "."; skipEol = true; } break; case SvnNotifyAction.LockLocked: actiondesc = string.Format(GettextCatalog.GetString("'{0}' locked by user '{1}'."), file, e.Lock.Owner); break; case SvnNotifyAction.LockUnlocked: actiondesc = string.Format(GettextCatalog.GetString("'{0}' unlocked."), file); break; default: actiondesc = e.Action + " " + file; break; } if (monitor != null) { if (skipEol) { monitor.Log.Write(actiondesc); } else { monitor.Log.WriteLine(actiondesc); } } if (notifyChange && File.Exists(file)) { FileService.NotifyFileChanged(file, true); } }
public void SetUp() { _fileService = new FileService(); }
// function to test public void UtilizeService() { FileService fs = new FileService(); fs.WriteToFile("file1", "line1", "line"); lines = fs.ReadFromFile("file2"); }
public static void WriteFile(FilePath fileName, byte[] content, string encoding, ByteOrderMark bom, bool onlyIfChanged) { int contentLength = content.Length + (bom != null ? bom.Length : 0); byte[] converted; if (encoding != null) { converted = ConvertToBytes(content, content.LongLength, encoding, "UTF-8"); } else { converted = content; } if (onlyIfChanged) { FileInfo finfo = new FileInfo(fileName); if (finfo.Exists && finfo.Length == contentLength) { bool changed = false; // Open the file on disk and compare them byte by byte... using (FileStream stream = finfo.Open(FileMode.Open, FileAccess.Read, FileShare.Read)) { byte[] buf = new byte [4096]; int bomOffset = 0; int offset = 0; int nread; int i; while (!changed && (nread = stream.Read(buf, 0, buf.Length)) > 0) { i = 0; if (bom != null && bomOffset < bom.Length) { while (i < nread && bomOffset < bom.Length) { if (bom.Bytes[bomOffset] != buf[i]) { changed = true; break; } bomOffset++; i++; } if (changed) { break; } } while (i < nread && offset < converted.Length) { if (converted[offset] != buf[i]) { changed = true; break; } offset++; i++; } if (offset == converted.Length && i < nread) { changed = true; } } if (offset < converted.Length) { changed = true; } } if (!changed) { return; } } // Content has changed... } string tempName = Path.GetDirectoryName(fileName) + Path.DirectorySeparatorChar + ".#" + Path.GetFileName(fileName); FileStream fs = new FileStream(tempName, FileMode.Create, FileAccess.Write); if (bom != null) { fs.Write(bom.Bytes, 0, bom.Length); } fs.Write(converted, 0, converted.Length); fs.Flush(); fs.Close(); FileService.SystemRename(tempName, fileName); FileService.NotifyFileChanged(fileName); }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { if (!isVisible) { output.SuppressOutput(); return; } #region << Init >> var initSuccess = InitField(context, output); if (!initSuccess) { return; } #region << Init Prepend and Append >> var content = await output.GetChildContentAsync(); var htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(content.GetContent()); var prependTaghelper = htmlDoc.DocumentNode.Descendants("wv-field-prepend"); var appendTagHelper = htmlDoc.DocumentNode.Descendants("wv-field-append"); foreach (var node in prependTaghelper) { PrependHtml.Add(node.InnerHtml.ToString()); } foreach (var node in appendTagHelper) { AppendHtml.Add(node.InnerHtml.ToString()); } #endregion #endregion #region << Render >> if (Mode == FieldRenderMode.Form) { var inputReadOnlyValue = ""; var inputEditValue = ""; if (Value != null) { inputReadOnlyValue = (Value as DateTime? ?? (DateTime?)DateTime.Now).ConvertToAppDate().Value.ToString("dd MMM yyyy", Culture); inputEditValue = (Value ?? DateTime.Now).ToString("yyyy-MM-ddT00:00:00.000"); } var inputGroupEl = new TagBuilder("div"); inputGroupEl.AddCssClass("input-group"); //Prepend if (PrependHtml.Count > 0) { var prependEl = new TagBuilder("span"); prependEl.AddCssClass($"input-group-prepend {(ValidationErrors.Count > 0 ? "is-invalid" : "")}"); foreach (var htmlString in PrependHtml) { prependEl.InnerHtml.AppendHtml(htmlString); } inputGroupEl.InnerHtml.AppendHtml(prependEl); } //Control var inputEl = new TagBuilder("input"); var inputElCssClassList = new List <string>(); inputElCssClassList.Add("form-control erp-date"); inputEl.Attributes.Add("type", "text"); inputEl.Attributes.Add("id", $"input-{FieldId}"); inputEl.Attributes.Add("name", Name); if (Access == FieldAccess.Full || Access == FieldAccess.FullAndCreate) { if (Required) { inputEl.Attributes.Add("required", null); } if (!String.IsNullOrWhiteSpace(Placeholder)) { inputEl.Attributes.Add("placeholder", Placeholder); } inputEl.Attributes.Add("value", inputEditValue); } else if (Access == FieldAccess.ReadOnly) { inputEl.Attributes.Add("value", inputReadOnlyValue); inputEl.Attributes.Add("readonly", null); } if (ValidationErrors.Count > 0) { inputElCssClassList.Add("is-invalid"); } inputEl.Attributes.Add("class", String.Join(' ', inputElCssClassList)); inputGroupEl.InnerHtml.AppendHtml(inputEl); //Append if (AppendHtml.Count > 0) { var appendEl = new TagBuilder("span"); appendEl.AddCssClass($"input-group-append {(ValidationErrors.Count > 0 ? "is-invalid" : "")}"); foreach (var htmlString in AppendHtml) { appendEl.InnerHtml.AppendHtml(htmlString); } inputGroupEl.InnerHtml.AppendHtml(appendEl); } output.Content.AppendHtml(inputGroupEl); if (Access == FieldAccess.Full || Access == FieldAccess.FullAndCreate) { var jsCompressor = new JavaScriptCompressor(); #region << Init Scripts >> var tagHelperInitialized = false; if (ViewContext.HttpContext.Items.ContainsKey(typeof(WvFieldDate) + "-form")) { var tagHelperContext = (WvTagHelperContext)ViewContext.HttpContext.Items[typeof(WvFieldDate) + "-form"]; tagHelperInitialized = tagHelperContext.Initialized; } if (!tagHelperInitialized) { var scriptContent = FileService.GetEmbeddedTextResource("form.js", "WebVella.Erp.Web.TagHelpers.WvFieldDate"); var scriptEl = new TagBuilder("script"); scriptEl.Attributes.Add("type", "text/javascript"); scriptEl.InnerHtml.AppendHtml(jsCompressor.Compress(scriptContent)); output.PostContent.AppendHtml(scriptEl); ViewContext.HttpContext.Items[typeof(WvFieldDate) + "-form"] = new WvTagHelperContext() { Initialized = true }; } #endregion #region << Add Inline Init Script for this instance >> var initScript = new TagBuilder("script"); initScript.Attributes.Add("type", "text/javascript"); var scriptTemplate = @" $(function(){ InitFlatPickrDate(""{{FieldId}}""); });" ; scriptTemplate = scriptTemplate.Replace("{{FieldId}}", (FieldId ?? null).ToString()); initScript.InnerHtml.AppendHtml(jsCompressor.Compress(scriptTemplate)); output.PostContent.AppendHtml(initScript); #endregion } } else if (Mode == FieldRenderMode.Display) { if (Value != null) { var inputReadOnlyValue = (Value as DateTime? ?? (DateTime?)DateTime.Now).ConvertToAppDate().Value.ToString("dd MMM yyyy", Culture); var divEl = new TagBuilder("div"); divEl.Attributes.Add("id", $"input-{FieldId}"); divEl.AddCssClass("form-control-plaintext erp-date"); divEl.InnerHtml.Append(inputReadOnlyValue); output.Content.AppendHtml(divEl); } else { output.Content.AppendHtml(EmptyValEl); } } else if (Mode == FieldRenderMode.Simple) { if (Value != null) { output.SuppressOutput(); var inputReadOnlyValue = (Value as DateTime? ?? (DateTime?)DateTime.Now).ConvertToAppDate().Value.ToString("dd MMM yyyy", Culture); output.Content.AppendHtml(inputReadOnlyValue); } else { output.Content.AppendHtml(""); } return; } else if (Mode == FieldRenderMode.InlineEdit) { if (Access == FieldAccess.Full || Access == FieldAccess.FullAndCreate) { var editInpuValue = ""; var readOnlyInputValue = ""; if (Value != null) { readOnlyInputValue = (Value as DateTime? ?? (DateTime?)DateTime.Now).ConvertToAppDate().Value.ToString("dd MMM yyyy", Culture); editInpuValue = (Value ?? DateTime.Now).ToString("yyyy-MM-ddT00:00:00.000"); } #region << View Wrapper >> { var viewWrapperEl = new TagBuilder("div"); viewWrapperEl.AddCssClass("input-group view-wrapper"); viewWrapperEl.Attributes.Add("title", "double click to edit"); viewWrapperEl.Attributes.Add("id", $"view-{FieldId}"); //Prepend if (PrependHtml.Count > 0) { var viewInputPrepend = new TagBuilder("span"); viewInputPrepend.AddCssClass("input-group-prepend"); foreach (var htmlString in PrependHtml) { viewInputPrepend.InnerHtml.AppendHtml(htmlString); } viewWrapperEl.InnerHtml.AppendHtml(viewInputPrepend); } //Control var viewFormControlEl = new TagBuilder("div"); viewFormControlEl.AddCssClass("form-control erp-date"); viewFormControlEl.InnerHtml.Append(readOnlyInputValue); viewWrapperEl.InnerHtml.AppendHtml(viewFormControlEl); //Append var viewInputActionEl = new TagBuilder("span"); viewInputActionEl.AddCssClass("input-group-append"); foreach (var htmlString in AppendHtml) { viewInputActionEl.InnerHtml.AppendHtml(htmlString); } viewInputActionEl.InnerHtml.AppendHtml("<button type=\"button\" class='btn btn-white action' title='edit'><i class='fa fa-fw fa-pencil-alt'></i></button>"); viewWrapperEl.InnerHtml.AppendHtml(viewInputActionEl); output.Content.AppendHtml(viewWrapperEl); } #endregion #region << Edit Wrapper>> { var editWrapperEl = new TagBuilder("div"); editWrapperEl.Attributes.Add("id", $"edit-{FieldId}"); editWrapperEl.Attributes.Add("style", $"display:none;"); editWrapperEl.Attributes.Add("data-default-date", editInpuValue); //There is a problem with double initializing flatpickr which this solves editWrapperEl.AddCssClass("edit-wrapper"); var editInputGroupEl = new TagBuilder("div"); editInputGroupEl.AddCssClass("input-group"); //Prepend if (PrependHtml.Count > 0) { var editInputPrepend = new TagBuilder("span"); editInputPrepend.AddCssClass("input-group-prepend"); foreach (var htmlString in PrependHtml) { editInputPrepend.InnerHtml.AppendHtml(htmlString); } editInputGroupEl.InnerHtml.AppendHtml(editInputPrepend); } //Control var editInputEl = new TagBuilder("input"); editInputEl.AddCssClass("form-control erp-date"); editInputEl.Attributes.Add("type", "text"); if (Required) { editInputEl.Attributes.Add("required", null); } if (!String.IsNullOrWhiteSpace(Placeholder)) { editInputEl.Attributes.Add("placeholder", Placeholder); } editInputEl.Attributes.Add("value", editInpuValue); editInputGroupEl.InnerHtml.AppendHtml(editInputEl); //Append var editInputGroupAppendEl = new TagBuilder("span"); editInputGroupAppendEl.AddCssClass("input-group-append"); foreach (var htmlString in AppendHtml) { editInputGroupAppendEl.InnerHtml.AppendHtml(htmlString); } editInputGroupAppendEl.InnerHtml.AppendHtml("<button type=\"button\" class='btn btn-white save' title='save'><i class='fa fa-fw fa-check go-green'></i></button>"); editInputGroupAppendEl.InnerHtml.AppendHtml("<button type=\"button\" class='btn btn-white cancel' title='cancel'><i class='fa fa-fw fa-times go-gray'></i></button>"); editInputGroupEl.InnerHtml.AppendHtml(editInputGroupAppendEl); editWrapperEl.InnerHtml.AppendHtml(editInputGroupEl); output.Content.AppendHtml(editWrapperEl); } #endregion var jsCompressor = new JavaScriptCompressor(); #region << Init Scripts >> var tagHelperInitialized = false; if (ViewContext.HttpContext.Items.ContainsKey(typeof(WvFieldDate) + "-inline-edit")) { var tagHelperContext = (WvTagHelperContext)ViewContext.HttpContext.Items[typeof(WvFieldDate) + "-inline-edit"]; tagHelperInitialized = tagHelperContext.Initialized; } if (!tagHelperInitialized) { var scriptContent = FileService.GetEmbeddedTextResource("inline-edit.js", "WebVella.Erp.Web.TagHelpers.WvFieldDate"); var scriptEl = new TagBuilder("script"); scriptEl.Attributes.Add("type", "text/javascript"); scriptEl.InnerHtml.AppendHtml(jsCompressor.Compress(scriptContent)); output.PostContent.AppendHtml(scriptEl); ViewContext.HttpContext.Items[typeof(WvFieldDate) + "-inline-edit"] = new WvTagHelperContext() { Initialized = true }; } #endregion #region << Add Inline Init Script for this instance >> var initScript = new TagBuilder("script"); initScript.Attributes.Add("type", "text/javascript"); var scriptTemplate = @" $(function(){ DateInlineEditInit(""{{FieldId}}"",""{{Name}}"",""{{EntityName}}"",""{{RecordId}}"",{{ConfigJson}}); });" ; scriptTemplate = scriptTemplate.Replace("{{FieldId}}", (FieldId ?? null).ToString()); scriptTemplate = scriptTemplate.Replace("{{Name}}", Name); scriptTemplate = scriptTemplate.Replace("{{EntityName}}", EntityName); scriptTemplate = scriptTemplate.Replace("{{RecordId}}", (RecordId ?? null).ToString()); var fieldConfig = new WvFieldDateConfig() { ApiUrl = ApiUrl, CanAddValues = Access == FieldAccess.FullAndCreate ? true : false }; scriptTemplate = scriptTemplate.Replace("{{ConfigJson}}", JsonConvert.SerializeObject(fieldConfig)); initScript.InnerHtml.AppendHtml(jsCompressor.Compress(scriptTemplate)); output.PostContent.AppendHtml(initScript); #endregion } else if (Access == FieldAccess.ReadOnly) { var readOnlyInputValue = ""; if (Value != null) { readOnlyInputValue = (Value as DateTime? ?? (DateTime?)DateTime.Now).ConvertToAppDate().Value.ToString("dd MMM yyyy", Culture); } var divEl = new TagBuilder("div"); divEl.AddCssClass("input-group"); //Prepend if (PrependHtml.Count > 0) { var viewInputPrepend = new TagBuilder("span"); viewInputPrepend.AddCssClass("input-group-prepend"); foreach (var htmlString in PrependHtml) { viewInputPrepend.InnerHtml.AppendHtml(htmlString); } divEl.InnerHtml.AppendHtml(viewInputPrepend); } //Control var inputEl = new TagBuilder("input"); inputEl.AddCssClass("form-control erp-date"); inputEl.Attributes.Add("type", "text"); inputEl.Attributes.Add("value", readOnlyInputValue); inputEl.Attributes.Add("readonly", null); divEl.InnerHtml.AppendHtml(inputEl); //Append var appendActionSpan = new TagBuilder("span"); appendActionSpan.AddCssClass("input-group-append"); foreach (var htmlString in AppendHtml) { appendActionSpan.InnerHtml.AppendHtml(htmlString); } appendActionSpan.InnerHtml.AppendHtml("<button type=\"button\" disabled class='btn btn-white action' title='locked'><i class='fa fa-fw fa-lock'></i></button>"); divEl.InnerHtml.AppendHtml(appendActionSpan); output.Content.AppendHtml(divEl); } } #endregion //Finally if (SubInputEl != null) { output.PostContent.AppendHtml(SubInputEl); } return; }
public void WriteAndReadAlternateStreams() { using (var cleaner = new TestFileCleaner()) { string directoryPath = Paths.Combine(cleaner.TempFolder, Path.GetRandomFileName()); Directory.CreateDirectory(directoryPath); FileService fileService = new FileService(); string filePath = Paths.Combine(directoryPath, Path.GetRandomFileName()); using (Stream fileStream = fileService.CreateFileStream(filePath, FileMode.CreateNew, FileAccess.ReadWrite)) { } for (int i = 0; i < 3; i++) { string streamPath = $"{filePath}:Stream{i}:$DATA"; using (Stream fileStream = fileService.CreateFileStream(streamPath, FileMode.CreateNew, FileAccess.ReadWrite)) { string testString = $"This is test string {i}."; fileStream.Should().NotBeNull(); StreamWriter writer = new StreamWriter(fileStream); writer.WriteLine(testString); writer.Flush(); fileStream.Position = 0; StreamReader reader = new StreamReader(fileStream); string readLine = reader.ReadLine(); readLine.Should().Be(testString); } } var directoryInfo = fileService.GetPathInfo(directoryPath) as IDirectoryInformation; directoryInfo.Should().NotBeNull(); directoryInfo.EnumerateChildren().Should().HaveCount(1); } }
static string GenerateSteticCodeStructure(DotNetProject project, Stetic.ProjectItemInfo item, Stetic.Component component, Stetic.ComponentNameEventArgs args, bool saveToFile, bool overwrite) { // Generate a class which contains fields for all bound widgets of the component string name = item != null ? item.Name : component.Name; string fileName = GetBuildCodeFileName(project, name); string ns = ""; int i = name.LastIndexOf('.'); if (i != -1) { ns = name.Substring(0, i); name = name.Substring(i + 1); } if (saveToFile && !overwrite && File.Exists(fileName)) { return(fileName); } if (item != null) { component = item.Component; } CodeCompileUnit cu = new CodeCompileUnit(); if (project.UsePartialTypes) { CodeNamespace cns = new CodeNamespace(ns); cu.Namespaces.Add(cns); CodeTypeDeclaration type = new CodeTypeDeclaration(name); type.IsPartial = true; type.Attributes = MemberAttributes.Public; type.TypeAttributes = System.Reflection.TypeAttributes.Public; cns.Types.Add(type); foreach (Stetic.ObjectBindInfo binfo in component.GetObjectBindInfo()) { // When a component is being renamed, we have to generate the // corresponding field using the old name, since it will be renamed // later using refactory string nname = args != null && args.NewName == binfo.Name ? args.OldName : binfo.Name; type.Members.Add( new CodeMemberField( binfo.TypeName, nname ) ); } } else { if (!saveToFile) { return(fileName); } CodeNamespace cns = new CodeNamespace(); cns.Comments.Add(new CodeCommentStatement("Generated code for component " + component.Name)); cu.Namespaces.Add(cns); } CodeDomProvider provider = project.LanguageBinding.GetCodeDomProvider(); if (provider == null) { throw new UserException("Code generation not supported for language: " + project.LanguageName); } TextWriter fileStream; if (saveToFile) { fileStream = new StreamWriter(fileName); } else { fileStream = new StringWriter(); } try { provider.GenerateCodeFromCompileUnit(cu, fileStream, new CodeGeneratorOptions()); } finally { fileStream.Close(); } if (ProjectDomService.HasDom(project)) { // Only update the parser database if the project is actually loaded in the IDE. if (saveToFile) { ProjectDomService.Parse(project, fileName, ""); FileService.NotifyFileChanged(fileName); } else { ProjectDomService.Parse(project, fileName, "", ((StringWriter)fileStream).ToString()); } } return(fileName); }
public static Stetic.CodeGenerationResult GenerateSteticCode(IProgressMonitor monitor, DotNetProject project, ConfigurationSelector configuration) { if (generating || !GtkDesignInfo.HasDesignedObjects(project)) { return(null); } GtkDesignInfo info = GtkDesignInfo.FromProject(project); DateTime last_gen_time = File.Exists(info.SteticGeneratedFile) ? File.GetLastWriteTime(info.SteticGeneratedFile) : DateTime.MinValue; bool ref_changed = false; foreach (ProjectReference pref in project.References) { if (!pref.IsValid) { continue; } foreach (string filename in pref.GetReferencedFileNames(configuration)) { if (File.GetLastWriteTime(filename) > last_gen_time) { ref_changed = true; break; } } if (ref_changed) { break; } } // Check if generated code is already up to date. if (!ref_changed && last_gen_time >= File.GetLastWriteTime(info.SteticFile)) { return(null); } if (info.GuiBuilderProject.HasError) { monitor.ReportError(GettextCatalog.GetString("GUI code generation failed for project '{0}'. The file '{1}' could not be loaded.", project.Name, info.SteticFile), null); monitor.AsyncOperation.Cancel(); return(null); } if (info.GuiBuilderProject.IsEmpty) { return(null); } monitor.Log.WriteLine(GettextCatalog.GetString("Generating GUI code for project '{0}'...", project.Name)); // Make sure the referenced assemblies are up to date. It is necessary to do // it now since they may contain widget libraries. project.CopySupportFiles(monitor, configuration); info.GuiBuilderProject.UpdateLibraries(); ArrayList projects = new ArrayList(); projects.Add(info.GuiBuilderProject.File); generating = true; Stetic.CodeGenerationResult generationResult = null; Exception generatedException = null; bool canGenerateInProcess = IsolationMode != Stetic.IsolationMode.None || info.GuiBuilderProject.SteticProject.CanGenerateCode; if (!canGenerateInProcess) { // Run the generation in another thread to avoid freezing the GUI System.Threading.ThreadPool.QueueUserWorkItem(delegate { try { // Generate the code in another process if stetic is not isolated CodeGeneratorProcess cob = (CodeGeneratorProcess)Runtime.ProcessService.CreateExternalProcessObject(typeof(CodeGeneratorProcess), false); using (cob) { generationResult = cob.GenerateCode(projects, info.GenerateGettext, info.GettextClass, project.UsePartialTypes); } } catch (Exception ex) { generatedException = ex; } finally { generating = false; } }); while (generating) { DispatchService.RunPendingEvents(); System.Threading.Thread.Sleep(100); } } else { // No need to create another process, since stetic has its own backend process // or the widget libraries have no custom wrappers try { Stetic.GenerationOptions options = new Stetic.GenerationOptions(); options.UseGettext = info.GenerateGettext; options.GettextClass = info.GettextClass; options.UsePartialClasses = project.UsePartialTypes; options.GenerateSingleFile = false; generationResult = SteticApp.GenerateProjectCode(options, info.GuiBuilderProject.SteticProject); } catch (Exception ex) { generatedException = ex; } generating = false; } if (generatedException != null) { LoggingService.LogError("GUI code generation failed", generatedException); throw new UserException("GUI code generation failed: " + generatedException.Message); } if (generationResult == null) { return(null); } CodeDomProvider provider = project.LanguageBinding.GetCodeDomProvider(); if (provider == null) { throw new UserException("Code generation not supported for language: " + project.LanguageName); } string basePath = Path.GetDirectoryName(info.SteticGeneratedFile); string ext = Path.GetExtension(info.SteticGeneratedFile); foreach (Stetic.SteticCompilationUnit unit in generationResult.Units) { string fname; if (unit.Name.Length == 0) { fname = info.SteticGeneratedFile; } else { fname = Path.Combine(basePath, unit.Name) + ext; } StringWriter sw = new StringWriter(); try { foreach (CodeNamespace ns in unit.Namespaces) { ns.Comments.Add(new CodeCommentStatement("This file has been generated by the GUI designer. Do not modify.")); } provider.GenerateCodeFromCompileUnit(unit, sw, new CodeGeneratorOptions()); string content = sw.ToString(); content = FormatGeneratedFile(fname, content, provider); File.WriteAllText(fname, content); } finally { FileService.NotifyFileChanged(fname); } } // Make sure the generated files are added to the project if (info.UpdateGtkFolder()) { Gtk.Application.Invoke(delegate { IdeApp.ProjectOperations.Save(project); }); } return(generationResult); }
public MainViewModel(IFileService fileService, INavigationServiceEx navService) { _fileService = (fileService as FileService); _navigationService = navService as NavigationServiceEx; }
public void CreateLongPathStream() { using (var cleaner = new TestFileCleaner(false)) { string longPath = PathGenerator.CreatePathOfLength(cleaner.TempFolder, 300); FileService fileService = new FileService(); fileService.CreateDirectory(longPath); string filePath = Paths.Combine(longPath, Path.GetRandomFileName()); using (Stream fileStream = fileService.CreateFileStream(filePath, FileMode.CreateNew)) { fileStream.Should().NotBeNull(); } } }
public void WriteAndReadLongPathStream() { using (var cleaner = new TestFileCleaner(false)) { string longPath = PathGenerator.CreatePathOfLength(cleaner.TempFolder, 300); FileService fileService = new FileService(); fileService.CreateDirectory(longPath); string filePath = Paths.Combine(longPath, Path.GetRandomFileName()); using (Stream fileStream = fileService.CreateFileStream(filePath, FileMode.CreateNew, FileAccess.ReadWrite)) { fileStream.Should().NotBeNull(); StreamWriter writer = new StreamWriter(fileStream); writer.WriteLine("This is a test string."); writer.Flush(); fileStream.Position = 0; StreamReader reader = new StreamReader(fileStream); string readLine = reader.ReadLine(); readLine.Should().Be("This is a test string."); } } }
public void WriteAndReadtStream(string appendix) { using (var cleaner = new TestFileCleaner()) { FileService fileService = new FileService(); string filePath = Paths.Combine(cleaner.TempFolder, Path.GetRandomFileName() + appendix); using (Stream fileStream = fileService.CreateFileStream(filePath, FileMode.CreateNew, FileAccess.ReadWrite)) { fileStream.Should().NotBeNull(); StreamWriter writer = new StreamWriter(fileStream); writer.WriteLine("This is a test string."); writer.Flush(); fileStream.Position = 0; StreamReader reader = new StreamReader(fileStream); string readLine = reader.ReadLine(); readLine.Should().Be("This is a test string."); } } }
public FileController(FileService service) { this.fileService = service; }
public void OpenNonExistantStream(string appendix) { using (var cleaner = new TestFileCleaner()) { FileService fileService = new FileService(); string filePath = Paths.Combine(cleaner.TempFolder, Path.GetRandomFileName() + appendix); Action action = () => fileService.CreateFileStream(filePath, FileMode.Open); action.ShouldThrow<FileNotFoundException>(); } }
public WhatWeDeliveredController(WhatWeDeliveredService whatWeDeliveredService, FileService fileService, BaseRepository baseRepository) { _whatWeDeliveredService = whatWeDeliveredService; _fileService = fileService; _baseRepository = baseRepository; }
static bool UpdateCompleted(ProgressMonitor monitor, ProjectFile file, ProjectFile genFile, SingleFileCustomToolResult result, bool runMultipleFiles) { monitor.EndTask(); if (monitor.CancellationToken.IsCancellationRequested) { monitor.ReportError(GettextCatalog.GetString("Cancelled"), null); monitor.Dispose(); return(false); } string genFileName; try { bool broken = false; if (result.UnhandledException != null) { broken = true; string msg = GettextCatalog.GetString("The '{0}' code generator crashed", file.Generator); result.Errors.Add(new CompilerError(file.Name, 0, 0, "", msg + ": " + result.UnhandledException.Message)); monitor.ReportError(msg, result.UnhandledException); LoggingService.LogError(msg, result.UnhandledException); } genFileName = result.GeneratedFilePath.IsNullOrEmpty? null : result.GeneratedFilePath.ToRelative(file.FilePath.ParentDirectory); if (!string.IsNullOrEmpty(genFileName)) { bool validName = genFileName.IndexOfAny(new [] { '/', '\\' }) < 0 && FileService.IsValidFileName(genFileName); if (!broken && !validName) { broken = true; string msg = GettextCatalog.GetString("The '{0}' code generator output invalid filename '{1}'", file.Generator, result.GeneratedFilePath); result.Errors.Add(new CompilerError(file.Name, 0, 0, "", msg)); monitor.ReportError(msg, null); } } if (result.Errors.Count > 0) { Runtime.RunInMainThread(delegate { foreach (CompilerError err in result.Errors) { TaskService.Errors.Add(new TaskListEntry(file.FilePath, err.ErrorText, err.Column, err.Line, err.IsWarning? TaskSeverity.Warning : TaskSeverity.Error, TaskPriority.Normal, file.Project.ParentSolution, file)); } }); } if (broken) { return(true); } if (!runMultipleFiles) { if (result.Success) { monitor.ReportSuccess("Generated file successfully."); } else if (result.SuccessWithWarnings) { monitor.ReportSuccess("Warnings in file generation."); } else { monitor.ReportError("Errors in file generation.", null); } } } finally { if (!runMultipleFiles) { monitor.Dispose(); } } if (result.GeneratedFilePath.IsNullOrEmpty || !File.Exists(result.GeneratedFilePath)) { return(true); } // broadcast a change event so text editors etc reload the file FileService.NotifyFileChanged(result.GeneratedFilePath); // add file to project, update file properties, etc Gtk.Application.Invoke(async delegate { bool projectChanged = false; if (genFile == null) { genFile = file.Project.AddFile(result.GeneratedFilePath, result.OverrideBuildAction); projectChanged = true; } else if (result.GeneratedFilePath != genFile.FilePath) { genFile.Name = result.GeneratedFilePath; projectChanged = true; } if (file.LastGenOutput != genFileName) { file.LastGenOutput = genFileName; projectChanged = true; } if (genFile.DependsOn != file.FilePath.FileName) { genFile.DependsOn = file.FilePath.FileName; projectChanged = true; } if (projectChanged) { await IdeApp.ProjectOperations.SaveAsync(file.Project); } }); return(true); }
bool CreateProject() { if (templateView.CurrentlySelected != null) { PropertyService.Set("Dialogs.NewProjectDialog.LastSelectedCategory", ((ProjectTemplate)templateView.CurrentlySelected).Category); recentIds.Remove(templateView.CurrentlySelected.Id); recentIds.Insert(0, templateView.CurrentlySelected.Id); if (recentIds.Count > 15) { recentIds.RemoveAt(recentIds.Count - 1); } string strRecent = string.Join(",", recentIds.ToArray()); PropertyService.Set("Dialogs.NewProjectDialog.RecentTemplates", strRecent); PropertyService.SaveProperties(); //PropertyService.Set("Dialogs.NewProjectDialog.LargeImages", ((RadioButton)ControlDictionary["largeIconsRadioButton"]).Checked); } string solution = txt_subdirectory.Text; string name = txt_name.Text; string location = ProjectLocation; if (solution.Equals("")) { solution = name; //This was empty when adding after first combine } if ( !FileService.IsValidPath(solution) || !FileService.IsValidFileName(name) || name.IndexOf(' ') >= 0 || !FileService.IsValidPath(location)) { MessageService.ShowError(GettextCatalog.GetString("Illegal project name.\nOnly use letters, digits, '.' or '_'.")); return(false); } if (parentFolder != null && parentFolder.ParentSolution.FindProjectByName(name) != null) { MessageService.ShowError(GettextCatalog.GetString("A Project with that name is already in your Project Space")); return(false); } PropertyService.Set( "MonoDevelop.Core.Gui.Dialogs.NewProjectDialog.AutoCreateProjectSubdir", CreateSolutionDirectory); if (templateView.CurrentlySelected == null || name.Length == 0) { return(false); } ProjectTemplate item = (ProjectTemplate)templateView.CurrentlySelected; try { System.IO.Directory.CreateDirectory(location); } catch (IOException) { MessageService.ShowError(GettextCatalog.GetString("Could not create directory {0}. File already exists.", location)); return(false); } catch (UnauthorizedAccessException) { MessageService.ShowError(GettextCatalog.GetString("You do not have permission to create to {0}", location)); return(false); } ProjectCreateInformation cinfo = CreateProjectCreateInformation(); try { if (newSolution) { newItem = item.CreateWorkspaceItem(cinfo); } else { newItem = item.CreateProject(parentFolder, cinfo); } } catch (Exception ex) { MessageService.ShowException(ex, GettextCatalog.GetString("The project could not be created")); return(false); } selectedItem = item; return(true); }
public void CreateStream() { using (var cleaner = new TestFileCleaner()) { FileService fileService = new FileService(); string filePath = Paths.Combine(cleaner.TempFolder, Path.GetRandomFileName()); using (Stream fileStream = fileService.CreateFileStream(filePath, FileMode.CreateNew)) { fileStream.Should().NotBeNull(); } } }
public void Setup() { Mock<ILoggerService> loggerService = new Mock<ILoggerService>(); loggerService.SetupSequence(o => o.Log(It.IsAny<Log>())).Returns(true); FileService Service = new FileService(loggerService.Object); Service.SaveMedia(StoredMedia, data); }
/// <summary> /// Given the absolute location of a file, and a disc location, returns relative file path to that disk location. /// Throws UriFormatException. /// </summary> /// <param name="basePath"> /// The base path we want to relativize to. Must be absolute. /// Should <i>not</i> include a filename as the last segment will be interpreted as a directory. /// </param> /// <param name="path"> /// The path we need to make relative to basePath. The path can be either absolute path or a relative path in which case it is relative to the base path. /// If the path cannot be made relative to the base path (for example, it is on another drive), it is returned verbatim. /// </param> /// <returns>relative path (can be the full path)</returns> internal static string MakeRelative(string basePath, string path) { string result = FileService.AbsoluteToRelativePath(basePath, path); return(result); }
protected override bool OnBuild(ProgressMonitor monitor, DeployContext ctx) { string tmpFolder = FileService.CreateTempDirectory(); Solution solution = null; SolutionFolderItem entry = RootSolutionItem; try { if (generateFiles) { List <string> childEntries = new List <string> (); if (entry is SolutionFolder) { SolutionFolderItem[] ents = GetChildEntries(); foreach (SolutionFolderItem it in ents) { childEntries.Add(it.ItemId); } } else { // If the entry is not a combine, use the parent combine as base combine childEntries.Add(entry.ItemId); entry = entry.ParentFolder; } string sourceFile; if (entry is SolutionFolder) { sourceFile = entry.ParentSolution.FileName; } else { sourceFile = ((SolutionItem)entry).FileName; } string efile = Services.ProjectService.Export(new FilteredProgressMonitor(monitor), sourceFile, childEntries.ToArray(), tmpFolder, null).Result; if (efile == null) { monitor.ReportError(GettextCatalog.GetString("The project could not be exported."), null); return(false); } solution = Services.ProjectService.ReadWorkspaceItem(new ProgressMonitor(), efile).Result as Solution; } else { solution = entry.ParentSolution; } var res = solution.Build(monitor, (SolutionConfigurationSelector)defaultConfig).Result; if (res.HasErrors || monitor.CancellationToken.IsCancellationRequested) { return(false); } SolutionDeployer deployer = new SolutionDeployer(generateAutotools); deployer.AddSwitches(switchs); if (!deployer.Deploy(ctx, solution, DefaultConfiguration, TargetDir, generateFiles, monitor)) { return(false); } } finally { if (solution != null) { solution.Dispose(); } Directory.Delete(tmpFolder, true); } return(true); }
public FilesController(EntityService entityService, FileService fileService) { _entityService = entityService; _fileService = fileService; }
public static bool IsValidSolutionName(string name) { return(FileService.IsValidPath(name) && FileService.IsValidFileName(name) && name.IndexOfAny(InvalidProjectNameCharacters) < 0); }