private async Task CommitAssetsFileAsync( LockFileFormat lockFileFormat, IRestoreResult result, ILogger log, bool toolCommit, CancellationToken token) { // Commit targets/props to disk before the assets file. // Visual Studio typically watches the assets file for changes // and begins a reload when that file changes. var buildFilesToWrite = result.MSBuildOutputFiles .Where(e => BuildAssetsUtils.HasChanges(e.Content, e.Path, log)); BuildAssetsUtils.WriteFiles(buildFilesToWrite, log); if (result.LockFile == null || result.LockFilePath == null) { // there is no assets file to be written so just return return; } // Avoid writing out the lock file if it is the same to avoid triggering an intellisense // update on a restore with no actual changes. if (result.PreviousLockFile == null || !result.PreviousLockFile.Equals(result.LockFile)) { if (toolCommit) { log.LogInformation(string.Format(CultureInfo.CurrentCulture, Strings.Log_ToolWritingAssetsFile, result.LockFilePath)); await FileUtility.ReplaceWithLock( (outputPath) => lockFileFormat.Write(outputPath, result.LockFile), result.LockFilePath); } else { log.LogInformation(string.Format(CultureInfo.CurrentCulture, Strings.Log_WritingAssetsFile, result.LockFilePath)); FileUtility.Replace( (outputPath) => lockFileFormat.Write(outputPath, result.LockFile), result.LockFilePath); } } else { if (toolCommit) { log.LogInformation(string.Format(CultureInfo.CurrentCulture, Strings.Log_ToolSkippingAssetsFile, result.LockFilePath)); } else { log.LogInformation(string.Format(CultureInfo.CurrentCulture, Strings.Log_SkippingAssetsFile, result.LockFilePath)); } } }
public GoogleDriveTagDao(IServiceProvider serviceProvider, UserManager userManager, TenantManager tenantManager, TenantUtil tenantUtil, DbContextManager <FilesDbContext> dbContextManager, SetupInfo setupInfo, IOptionsMonitor <ILog> monitor, FileUtility fileUtility) : base(serviceProvider, userManager, tenantManager, tenantUtil, dbContextManager, setupInfo, monitor, fileUtility) { }
public static List <AceWrapper> GetSharedInfo(FileEntry entry) { if (entry == null) { throw new ArgumentNullException(FilesCommonResource.ErrorMassage_BadRequest); } if (!CanSetAccess(entry)) { Global.Logger.ErrorFormat("User {0} can't get shared info for {1} {2}", SecurityContext.CurrentAccount.ID, (entry.FileEntryType == FileEntryType.File ? "file" : "folder"), entry.ID); throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException); } var linkAccess = FileShare.Restrict; var result = new List <AceWrapper>(); var fileSecurity = Global.GetFilesSecurity(); var records = fileSecurity .GetShares(entry) .GroupBy(r => r.Subject) .Select(g => g.OrderBy(r => r.Level) .ThenBy(r => r.Level) .ThenByDescending(r => r.Share, new FileShareRecord.ShareComparer()).FirstOrDefault()); foreach (var r in records) { if (r.Subject == FileConstant.ShareLinkId) { linkAccess = r.Share; continue; } var u = CoreContext.UserManager.GetUsers(r.Subject); var isgroup = false; var title = u.DisplayUserName(false); if (u.ID == Constants.LostUser.ID) { var g = CoreContext.UserManager.GetGroupInfo(r.Subject); isgroup = true; title = g.Name; if (g.ID == Constants.GroupAdmin.ID) { title = FilesCommonResource.Admin; } if (g.ID == Constants.GroupEveryone.ID) { title = FilesCommonResource.Everyone; } if (g.ID == Constants.LostGroupInfo.ID) { fileSecurity.RemoveSubject(r.Subject); continue; } } var w = new AceWrapper { SubjectId = r.Subject, SubjectName = title, SubjectGroup = isgroup, Share = r.Share, Owner = entry.RootFolderType == FolderType.USER ? entry.RootFolderCreator == r.Subject : entry.CreateBy == r.Subject, LockedRights = r.Subject == SecurityContext.CurrentAccount.ID }; result.Add(w); } if (entry.FileEntryType == FileEntryType.File && !((File)entry).Encrypted && result.All(w => w.SubjectId != FileConstant.ShareLinkId) && (linkAccess != FileShare.Restrict || CoreContext.Configuration.Standalone || !TenantExtra.GetTenantQuota().Trial || FileUtility.CanWebView(entry.Title))) { var w = new AceWrapper { SubjectId = FileConstant.ShareLinkId, Link = FileShareLink.GetLink((File)entry), SubjectGroup = true, Share = linkAccess, Owner = false }; result.Add(w); } if (!result.Any(w => w.Owner)) { var ownerId = entry.RootFolderType == FolderType.USER ? entry.RootFolderCreator : entry.CreateBy; var w = new AceWrapper { SubjectId = ownerId, SubjectName = Global.GetUserName(ownerId), SubjectGroup = false, Share = FileShare.ReadWrite, Owner = true }; result.Add(w); } if (result.Any(w => w.SubjectId == SecurityContext.CurrentAccount.ID)) { result.Single(w => w.SubjectId == SecurityContext.CurrentAccount.ID).LockedRights = true; } if (entry.RootFolderType == FolderType.COMMON) { if (result.All(w => w.SubjectId != Constants.GroupAdmin.ID)) { var w = new AceWrapper { SubjectId = Constants.GroupAdmin.ID, SubjectName = FilesCommonResource.Admin, SubjectGroup = true, Share = FileShare.ReadWrite, Owner = false, LockedRights = true, }; result.Add(w); } if (result.All(w => w.SubjectId != Constants.GroupEveryone.ID)) { var w = new AceWrapper { SubjectId = Constants.GroupEveryone.ID, SubjectName = FilesCommonResource.Everyone, SubjectGroup = true, Share = fileSecurity.DefaultCommonShare, Owner = false, DisableRemove = true }; result.Add(w); } } return(result); }
public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request) { string taskName = request.DataStore.GetValue("TaskName"); TaskCollection tasks = null; using (TaskService ts = new TaskService()) { tasks = ts.RootFolder.GetTasks(new Regex(taskName)); // We expect only one task to match foreach (Task task in tasks) { switch (task.LastTaskResult) { case 0: return(new ActionResponse(ActionStatus.Success, JsonUtility.GetEmptyJObject())); case 267014: var uploaded = await uploadLogs(request); if (!uploaded.IsSuccess) { request.Logger.LogCustomProperty("UploadLogs", "Upload of Logs Failed."); } return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), new Exception("The scheduled task was terminated by the user."), "TaskSchedulerRunFailed")); case 411: return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), new Exception("PowerShell version too low - please upgrade to latest version https://msdn.microsoft.com/en-us/powershell/wmf/5.0/requirements"), "TaskSchedulerRunFailed")); } if (task.State == TaskState.Running) { return(new ActionResponse(ActionStatus.BatchNoState, JsonUtility.GetEmptyJObject())); } if (NTHelper.IsCredentialGuardEnabled()) { return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "CredentialGuardEnabled")); } //If we've encountered an error, copy the logs, zip them up, and send to blob var uploadedLogs = await uploadLogs(request); if (!uploadedLogs.IsSuccess) { request.Logger.LogCustomProperty("UploadLogs", "Upload of Logs Failed."); } ActionResponse response = new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), new Exception($"Scheduled task exited with code {task.LastTaskResult}"), "TaskSchedulerRunFailed"); response.ExceptionDetail.LogLocation = FileUtility.GetLocalTemplatePath(request.Info.AppName); return(response); } } // We should never return this return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "SccmTaskNotFound")); }
public static bool AddToCacheDependency(string key, object value) { bool retVal = false; if (!ConfigSettings.CentralManagement & ConfigSettings.EnableCache) { FileStream fileStream = null; string fileName = null; fileName = s_CacheDirectory + key + ".txt"; // ensure the file exists if not then create one if (!File.Exists(fileName)) { try { File.Create(fileName).Close(); } catch (IOException) { MDirectoryProfile DirectoryProfile = new MDirectoryProfile(); FileUtility.CreateDirectory(HttpContext.Current.Server.MapPath("~\\"), "CacheDependency", DirectoryProfile); File.Create(fileName).Close(); } HttpContext.Current.Application.Lock(); HttpContext.Current.Application[key + "WriteCache"] = true; HttpContext.Current.Application.UnLock(); } // re-write the dependancy file based on the application variable // file replication will cause the other servers to remove their cache item if (HttpContext.Current.Application[key + "WriteCache"] == null) { HttpContext.Current.Application[key + "WriteCache"] = "true"; } if (Convert.ToBoolean(HttpContext.Current.Application[key + "WriteCache"].ToString(), CultureInfo.InvariantCulture)) { try { fileStream = new FileStream(fileName, FileMode.Truncate); using (StreamWriter writer = new StreamWriter(fileStream)) { writer.WriteLine(DateTime.Now.TimeOfDay); } HttpContext.Current.Application.Lock(); HttpContext.Current.Application[key + "WriteCache"] = false; HttpContext.Current.Application.UnLock(); } catch (Exception) { throw; } finally { if (fileStream != null) { fileStream.Dispose(); } } } // cache it for future use CacheItemRemovedCallback onCacheRemove = null; CacheDependency mCacheDependency = null; try { onCacheRemove = new CacheItemRemovedCallback(CheckCallback); mCacheDependency = new CacheDependency(fileName); if ((value != null)) { HttpContext.Current.Cache.Add(key, value, mCacheDependency, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, onCacheRemove); } } catch (Exception) { throw; } finally { if (mCacheDependency != null) { mCacheDependency.Dispose(); } } // used in the orginal vb code and no eq. for the Err object exists in c# // assume that if no exception has happened the set retVal=true //if (Err().Number == 0) retVal = true; retVal = true; } else { retVal = true; } return(retVal); }
public void DeploymentImportExcelWithAssociationTest() { //imports an excel with accounts linked to test entities PrepareTests(); DeleteAll(Entities.account); DeleteAll(Entities.jmcg_testentity); var workFolder = TestingFolder + @"\ExcelImportScript"; FileUtility.CheckCreateFolder(workFolder); var sourceExcelFile = Path.Combine(workFolder, @"TestExcelImportAssociations.xlsx"); File.Copy(@"TestExcelImportAssociations.xlsx", sourceExcelFile); var app = CreateAndLoadTestApplication <ImportExcelModule>(); app.AddModule <SavedRequestModule>(); ClearSavedRequests(app); var entryViewmodel = app.NavigateToDialogModuleEntryForm <ImportExcelModule, ImportExcelDialog>(); //select the excel file entryViewmodel.GetFieldViewModel(nameof(ImportExcelRequest.ExcelFile)).ValueObject = new FileReference(sourceExcelFile); //okay on change trigger should have fired and populated all the required mappings //so lets just trigger the import entryViewmodel.SaveButtonViewModel.Command.Execute(); var dialog = app.GetNavigatedDialog <ImportExcelDialog>(); var completionScreen = dialog.CompletionItem as ImportExcelResponse; if (completionScreen.HasError) { Assert.Fail(completionScreen.GetResponseItemsWithError().First().Exception.XrmDisplayString()); } //verify the account and contact created var accounts = XrmService.RetrieveAllEntityType(Entities.account); var testEntities = XrmService.RetrieveAllEntityType(Entities.jmcg_testentity); Assert.AreEqual(2, accounts.Count()); Assert.AreEqual(2, testEntities.Count()); var associations = XrmService.RetrieveAllEntityType(Relationships.account_.jmcg_testentity_account.EntityName); Assert.AreEqual(3, associations.Count()); //okay lets run a second import which will only be for the contacts and verify the same and no errors entryViewmodel = app.NavigateToDialogModuleEntryForm <ImportExcelModule, ImportExcelDialog>(); entryViewmodel.GetFieldViewModel(nameof(ImportExcelRequest.ExcelFile)).ValueObject = new FileReference(sourceExcelFile); //trigger the import entryViewmodel.SaveButtonViewModel.Command.Execute(); dialog = app.GetNavigatedDialog <ImportExcelDialog>(); completionScreen = dialog.CompletionItem as ImportExcelResponse; if (completionScreen.HasError) { Assert.Fail(completionScreen.GetResponseItemsWithError().First().Exception.XrmDisplayString()); } //verify still same number accounts = XrmService.RetrieveAllEntityType(Entities.account); testEntities = XrmService.RetrieveAllEntityType(Entities.jmcg_testentity); Assert.AreEqual(2, accounts.Count()); Assert.AreEqual(2, testEntities.Count()); associations = XrmService.RetrieveAllEntityType(Relationships.account_.jmcg_testentity_account.EntityName); Assert.AreEqual(3, associations.Count()); }
private bool DownloadSinglePackage(PackageItem pkgItem, NuGetRequest request, string destLocation, ProgressTracker progressTracker) { try { request.Debug(Messages.DebugInfoCallMethod, "NuGetFilesFeed3", "DownloadSinglePackage"); if (string.IsNullOrWhiteSpace(pkgItem.PackageFilename) || pkgItem.PackageSource == null || pkgItem.PackageSource.Location == null || (pkgItem.PackageSource.IsSourceAFile && pkgItem.Package == null)) { request.WriteError(ErrorCategory.ObjectNotFound, pkgItem.Id, Constants.Messages.UnableToResolvePackage, pkgItem.Id); return(false); } // this is if the user says -force bool force = request.GetOptionValue("Force") != null; // combine the path and the file name destLocation = Path.Combine(destLocation, pkgItem.PackageFilename); // if the file already exists if (File.Exists(destLocation)) { // if no force, just return if (!force) { request.Verbose(Constants.Messages.SkippedDownloadedPackage, pkgItem.Id); request.YieldPackage(pkgItem, pkgItem.PackageSource.Name); return(true); } // here we know it is forced, so delete FileUtility.DeleteFile(destLocation, isThrow: false); // if after we try delete, it is still there, tells the user we can't perform the action if (File.Exists(destLocation)) { request.WriteError(ErrorCategory.ResourceUnavailable, destLocation, Constants.Messages.UnableToOverwriteExistingFile, destLocation); return(false); } } bool downloadSuccessful = false; try { // if no repository, we can't do anything if (pkgItem.PackageSource.Repository == null) { return(false); } if (pkgItem.PackageSource.Repository.IsFile) { using (var input = File.OpenRead(pkgItem.Package.FullFilePath)) { using (var output = new FileStream(destLocation, FileMode.Create, FileAccess.Write, FileShare.Read)) { input.CopyTo(output); downloadSuccessful = true; } } } else { string httpquery = MakeDownloadUri(pkgItem); if (!String.IsNullOrEmpty(httpquery)) { downloadSuccessful = NuGetClient.DownloadPackage(pkgItem.Id, pkgItem.Version, destLocation, httpquery, request, pkgItem.PackageSource, progressTracker); } else { downloadSuccessful = false; request.Warning(Messages.FailedToCreateDownloadUri, pkgItem.Id, pkgItem.Version); } } } catch (Exception ex) { ex.Dump(request); return(false); } if (downloadSuccessful) { request.Verbose(Resources.Messages.SuccessfullyDownloaded, pkgItem.Id); // provide the directory we save to to yieldpackage request.YieldPackage(pkgItem, pkgItem.PackageSource.Name, Path.GetDirectoryName(destLocation)); } return(downloadSuccessful); } finally { request.Debug(Messages.DebugInfoReturnCall, "NuGetFilesFeed3", "DownloadSinglePackage"); } }
protected void Page_Load(object sender, EventArgs e) { SPListItemId = Request["SPListItemId"]; SPListURLDir = Request["SPListURLDir"]; SPListId = Request["SPListId"]; SPSource = Request["SPSource"]; SPUserToken userToken; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(SPUrl)) { using (SPWeb web = site.OpenWeb()) { //check secret key //================================================================================== if (web.Properties["SharePointSecret"] == null) { var rnd = new Random(); var spSecret = ""; for (var i = 0; i < 6; i++) { spSecret = spSecret + rnd.Next(1, 9).ToString(); } web.AllowUnsafeUpdates = true; web.Update(); web.Properties.Add("SharePointSecret", spSecret); web.Properties.Update(); web.AllowUnsafeUpdates = true; web.Update(); } Secret = web.Properties["SharePointSecret"]; //read settings //================================================================================== if (web.Properties["DocumentServerHost"] != null) { DocumentSeverHost = web.Properties["DocumentServerHost"]; } DocumentSeverHost += DocumentSeverHost.EndsWith("/") ? "" : "/"; // get current user ID and Name //================================================================================== userToken = web.AllUsers[0].UserToken; SPSite s = new SPSite(SPUrl, userToken); var currentUserName = User.Identity.Name.Substring(User.Identity.Name.LastIndexOf("\\") + 1); var users = web.AllUsers; for (var i = 0; i < users.Count; i++) { var userNameOfList = users[i].LoginName.Substring(users[i].LoginName.LastIndexOf("\\") + 1); if (userNameOfList == currentUserName) { currentUser = users[i]; CurrentUserId = users[i].ID; CurrentUserName = users[i].Name; break; } } //get language //================================================================================== var lcid = (int)web.Language; var defaultCulture = new CultureInfo(lcid); lang = defaultCulture.IetfLanguageTag; GoToBackText = LoadResource("GoToBack"); //get user/group roles //================================================================================== canEdit = CheckForEditing(SPUrl, SPListURLDir, currentUser); //generate key and get file info for DocEditor //================================================================================== try { SPWeb w = s.OpenWeb(); //SPRoleAssignmentCollection ss = w.RoleAssignments; SPList list = w.GetList(SPListURLDir); SPListItem item = list.GetItemById(Int32.Parse(SPListItemId)); SPFile file = item.File; //SPBasePermissions bp =SPContext.Current.Web.GetUserEffectivePermissions(SPContext.Current.Web.CurrentUser.LoginName); if (file != null) { Key = file.ETag; Key = GenerateRevisionId(Key); Folder = Path.GetDirectoryName(file.ServerRelativeUrl); Folder = Folder.Replace("\\", "/"); GoToBack = host + Folder; FileAuthor = file.Author.Name; var tzi = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneInfo.Local.Id); FileTimeCreated = TimeZoneInfo.ConvertTimeFromUtc(file.TimeCreated, tzi).ToString(); FileName = file.Name; var tmp = FileName.Split('.'); FileType = tmp[tmp.Length - 1]; //check document format try { if (FileUtility.CanViewTypes.Contains(FileType)) { var canEditType = FileUtility.CanEditTypes.Contains(FileType); canEdit = canEdit & canEditType; FileEditorMode = canEdit == true ? "edit" : FileEditorMode; //documentType = FileUtility.docTypes[FileType]; DocType.GetDocType(FileName) documentType = FileUtility.GetDocType(FileType); } else { Response.Redirect(SPUrl); } } catch (Exception ex) { //if a error - redirect to home page Log.LogError(ex.Message); Response.Redirect(SPUrl); } } else { Response.Redirect(SPUrl); } } catch (Exception ex) { Log.LogError(ex.Message); Response.Redirect(SPUrl + "/_layouts/" + SPVersion + "error.aspx"); } } } }); //generate url hash //================================================================================== urlDocDownload = Encryption.GetUrlHash(SPListItemId, Folder, SPListURLDir, "download", Secret); urlDocTrack = Encryption.GetUrlHash(SPListItemId, Folder, SPListURLDir, "track", Secret); }
public void AddWaterMark(int siteId, string filePath) { var siteInfo = SiteManager.GetSiteInfo(siteId); FileUtility.AddWaterMark(siteInfo, filePath); }
public void ExecAsync <T>(File <T> file, bool deleteAfter, string password = null) { if (!MustConvert(file)) { throw new ArgumentException(FilesCommonResource.ErrorMassage_NotSupportedFormat); } if (!string.IsNullOrEmpty(file.ConvertedType) || FileUtility.InternalExtension.Values.Contains(FileUtility.GetFileExtension(file.Title))) { return; } FileMarker.RemoveMarkAsNew(file); GetFileConverter <T>().Add(file, password, TenantManager.GetCurrentTenant().TenantId, AuthContext.CurrentAccount, deleteAfter, HttpContextAccesor?.HttpContext != null ? HttpContextAccesor.HttpContext.Request.GetUrlRewriter().ToString() : null); }
public File <T> SaveConvertedFile <T>(File <T> file, string convertedFileUrl) { var fileSecurity = FileSecurity; var fileDao = DaoFactory.GetFileDao <T>(); var folderDao = DaoFactory.GetFolderDao <T>(); File <T> newFile = null; var markAsTemplate = false; var newFileTitle = FileUtility.ReplaceFileExtension(file.Title, FileUtility.GetInternalExtension(file.Title)); if (!FilesSettingsHelper.StoreOriginalFiles && fileSecurity.CanEdit(file)) { newFile = (File <T>)file.Clone(); newFile.Version++; markAsTemplate = FileUtility.ExtsTemplate.Contains(FileUtility.GetFileExtension(file.Title), StringComparer.CurrentCultureIgnoreCase) && FileUtility.ExtsWebTemplate.Contains(FileUtility.GetFileExtension(newFileTitle), StringComparer.CurrentCultureIgnoreCase); } else { var folderId = GlobalFolderHelper.GetFolderMy <T>(); var parent = folderDao.GetFolder(file.FolderID); if (parent != null && fileSecurity.CanCreate(parent)) { folderId = parent.ID; } if (Equals(folderId, 0)) { throw new SecurityException(FilesCommonResource.ErrorMassage_FolderNotFound); } if (FilesSettingsHelper.UpdateIfExist && (parent != null && !folderId.Equals(parent.ID) || !file.ProviderEntry)) { newFile = fileDao.GetFile(folderId, newFileTitle); if (newFile != null && fileSecurity.CanEdit(newFile) && !EntryManager.FileLockedForMe(newFile.ID) && !FileTracker.IsEditing(newFile.ID)) { newFile.Version++; } else { newFile = null; } } if (newFile == null) { newFile = ServiceProvider.GetService <File <T> >(); newFile.FolderID = folderId; } } newFile.Title = newFileTitle; newFile.ConvertedType = null; newFile.Comment = string.Format(FilesCommonResource.CommentConvert, file.Title); var req = (HttpWebRequest)WebRequest.Create(convertedFileUrl); if (WorkContext.IsMono && ServicePointManager.ServerCertificateValidationCallback == null) { ServicePointManager.ServerCertificateValidationCallback += (s, c, n, p) => true; //HACK: http://ubuntuforums.org/showthread.php?t=1841740 } try { using var convertedFileStream = new ResponseStream(req.GetResponse()); newFile.ContentLength = convertedFileStream.Length; newFile = fileDao.SaveFile(newFile, convertedFileStream); } catch (WebException e) { using var response = e.Response; var httpResponse = (HttpWebResponse)response; var errorString = string.Format("WebException: {0}", httpResponse.StatusCode); if (httpResponse.StatusCode != HttpStatusCode.NotFound) { using var responseStream = response.GetResponseStream(); if (responseStream != null) { using var readStream = new StreamReader(responseStream); var text = readStream.ReadToEnd(); errorString += string.Format(" Error message: {0}", text); } } throw new Exception(errorString); } FilesMessageService.Send(newFile, MessageInitiator.DocsService, MessageAction.FileConverted, newFile.Title); FileMarker.MarkAsNew(newFile); var tagDao = DaoFactory.GetTagDao <T>(); var tags = tagDao.GetTags(file.ID, FileEntryType.File, TagType.System).ToList(); if (tags.Any()) { tags.ForEach(r => r.EntryId = newFile.ID); tagDao.SaveTags(tags); } if (markAsTemplate) { tagDao.SaveTags(Tag.Template(AuthContext.CurrentAccount.ID, newFile)); } return(newFile); }
public Stream Exec <T>(File <T> file) { return(Exec(file, FileUtility.GetInternalExtension(file.Title))); }
static FunctionalTest() { fileUtility = new FileUtility(); fileUtility.FilePath = "../../../../output_revised.txt"; fileUtility.CreateTextFile(); }
/// <summary> /// ファイルを読み込んでノードに展開します /// </summary> private void FileDrop(Node target, string[] files) { // 追加する先 IList <Node> toTree = default(IList <Node>); int toIndex = default(int); { switch (target.DropPosition) { case InsertPosition.Prev: case InsertPosition.Next: toTree = this.GetParent(target)?._ChildrenSource; if (toTree == null) { toTree = this.TreeSource; } toIndex = toTree.IndexOf(target); if (target.DropPosition == InsertPosition.Next) { ++toIndex; } break; case InsertPosition.Child: toTree = target._ChildrenSource; toIndex = target._ChildrenSource.Count(); break; default: return; } } // 追加するノード var addItems = new Stack <Node>(); { foreach (var file in files) { if (!File.Exists(file)) { continue; } QuartetEditorDescription model; if (FileUtility.LoadJsonObject(file, out model) == true) { // ファイルはQuartetEditorのファイル foreach (var node in model.Node) { var additem = new Node(node); addItems.Push(additem); } continue; } else { // QuartetEditor以外のファイル string content; if (!FileUtility.LoadTextByAnyEncoding(file, out content)) { continue; } // 改行コードの置き換え if (content.IndexOf("\r\n") != -1) { content = content.Replace("\r\n", Environment.NewLine); } else if (content.IndexOf("\r") != -1) { content = content.Replace("\r", Environment.NewLine); } else if (content.IndexOf("\n") != -1) { content = content.Replace("\n", Environment.NewLine); } string fileName = Path.GetFileNameWithoutExtension(file); var node = new Node(); if (!string.IsNullOrEmpty(fileName)) { node.Name = fileName; } node.Content.Text = content; node.Content.UndoStack.ClearAll(); addItems.Push(node); continue; } } } this.AddNodes(toTree, toIndex, addItems); }
public void DeploymentImportExcelBasicTest() { //imports an excel with 1 contact linked to 1 account PrepareTests(); DeleteAll(Entities.account); DeleteAll(Entities.contact); var workFolder = TestingFolder + @"\ExcelImportScript"; FileUtility.CheckCreateFolder(workFolder); var sourceExcelFile = Path.Combine(workFolder, @"TestExcelImportAccountAndContact.xlsx"); File.Copy(@"TestExcelImportAccountAndContact.xlsx", sourceExcelFile); var app = CreateAndLoadTestApplication <ImportExcelModule>(); app.AddModule <SavedRequestModule>(); ClearSavedRequests(app); var entryViewmodel = app.NavigateToDialogModuleEntryForm <ImportExcelModule, ImportExcelDialog>(); entryViewmodel.GetBooleanFieldFieldViewModel(nameof(ImportExcelRequest.MaskEmails)).Value = true; //select the excel file entryViewmodel.GetFieldViewModel(nameof(ImportExcelRequest.ExcelFile)).ValueObject = new FileReference(sourceExcelFile); //okay on change trigger should have fired and populated mappings on contact var mappingGrid = entryViewmodel.GetEnumerableFieldViewModel(nameof(ImportExcelRequest.Mappings)); var contactSource = mappingGrid.GridRecords.First(r => r.GetRecordTypeFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.SourceTab)).Value.Key.ToLower().Contains("contact")); Assert.AreEqual(Entities.contact, contactSource.GetRecordTypeFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.TargetType)).Value?.Key); contactSource.GetEnumerableFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.Mappings)).EditButton.Command.Execute(); var contactMapEntryModel = app.GetSubObjectEntryViewModel(entryViewmodel); var fieldMappingGrid = contactMapEntryModel.GetEnumerableFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.Mappings)); //verify the autmapped field var fullNameSource = fieldMappingGrid.GridRecords.First(r => r.GetRecordFieldFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.ExcelImportFieldMapping.SourceColumn)).Value.Key.ToLower().Contains("full name")); Assert.AreEqual(Fields.contact_.fullname, fullNameSource.GetRecordFieldFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.ExcelImportFieldMapping.TargetField)).Value?.Key); //set mapping for the company field var companySource = fieldMappingGrid.GridRecords.First(r => r.GetRecordFieldFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.ExcelImportFieldMapping.SourceColumn)).Value.Key.ToLower().Contains("contact company")); companySource.GetRecordFieldFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.ExcelImportFieldMapping.TargetField)).Value = new RecordField(Fields.contact_.parentcustomerid, Fields.contact_.parentcustomerid); //remove unmapped fields foreach (var item in fieldMappingGrid.DynamicGridViewModel.GridRecords.ToArray()) { if (item.GetFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.ExcelImportFieldMapping.TargetField)).ValueObject == null) { item.DeleteRowViewModel.Command.Execute(); } } contactMapEntryModel.SaveButtonViewModel.Command.Execute(); Assert.IsFalse(entryViewmodel.ChildForms.Any()); //map the other tab to accounts var accountSource = mappingGrid.GridRecords.First(r => r.GetRecordTypeFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.SourceTab)).Value.Key.ToLower().Contains("compan")); accountSource.GetRecordTypeFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.TargetType)).Value = new RecordType(Entities.account, Entities.account); accountSource.GetEnumerableFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.Mappings)).EditButton.Command.Execute(); var accountMapEntryModel = app.GetSubObjectEntryViewModel(entryViewmodel); fieldMappingGrid = accountMapEntryModel.GetEnumerableFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.Mappings)); //map the account name var nameSource = fieldMappingGrid.GridRecords.First(r => r.GetRecordFieldFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.ExcelImportFieldMapping.SourceColumn)).Value.Key.ToLower().Contains("name")); nameSource.GetRecordFieldFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.ExcelImportFieldMapping.TargetField)).Value = new RecordField(Fields.account_.name, Fields.account_.name); accountMapEntryModel.SaveButtonViewModel.Command.Execute(); Assert.IsFalse(entryViewmodel.ChildForms.Any()); //remove unmapped tabs foreach (var item in mappingGrid.DynamicGridViewModel.GridRecords.ToArray()) { if (item.GetFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.TargetType)).ValueObject == null) { item.DeleteRowViewModel.Command.Execute(); } } ClearSavedRequests(app, entryViewmodel); //lets save the request with autoload so we can run again afterwards SaveWithAutoload(app, entryViewmodel); //trigger the import entryViewmodel.SaveButtonViewModel.Command.Execute(); var dialog = app.GetNavigatedDialog <ImportExcelDialog>(); var completionScreen = dialog.CompletionItem as ImportExcelResponse; if (completionScreen.HasError) { Assert.Fail(completionScreen.GetResponseItemsWithError().First().Exception.XrmDisplayString()); } //verify the account and contact created var accounts = XrmService.RetrieveAllEntityType(Entities.account); var contacts = XrmService.RetrieveAllEntityType(Entities.contact); Assert.AreEqual(1, accounts.Count()); Assert.AreEqual(1, contacts.Count()); //verify the contact has names populated and linked to the account foreach (var contact in contacts) { Assert.AreEqual(accounts.First().Id, contact.GetLookupGuid(Fields.contact_.parentcustomerid)); Assert.IsNotNull(contact.GetStringField(Fields.contact_.firstname)); Assert.IsNotNull(contact.GetStringField(Fields.contact_.lastname)); if (contact.GetStringField(Fields.contact_.emailaddress1) != null) { Assert.IsTrue(contact.GetStringField(Fields.contact_.emailaddress1).Contains("@fake")); } //this one is date only Assert.AreEqual(new DateTime(1980, 11, 15), contact.GetDateTimeField(Fields.contact_.birthdate)); //this one is user local Assert.AreEqual(new DateTime(1980, 11, 15), contact.GetDateTimeField(Fields.contact_.lastonholdtime).Value.ToLocalTime()); } //okay lets do a second import and verify no creates or updates entryViewmodel = app.NavigateToDialogModuleEntryForm <ImportExcelModule, ImportExcelDialog>(); entryViewmodel.SaveButtonViewModel.Command.Execute(); dialog = app.GetNavigatedDialog <ImportExcelDialog>(); completionScreen = dialog.CompletionItem as ImportExcelResponse; if (completionScreen.HasError) { Assert.Fail(completionScreen.GetResponseItemsWithError().First().Exception.XrmDisplayString()); } Assert.IsTrue(completionScreen.ImportSummary.All(i => i.Created == 0 && i.Updated == 0)); }
private async Task InitializeTestHostAsync(string testDirName, IEnvironment environment) { var httpConfig = new HttpConfiguration(); var uniqueTestRootPath = Path.Combine(_testRootPath, testDirName, Guid.NewGuid().ToString()); var scriptRootPath = Path.Combine(uniqueTestRootPath, "wwwroot"); FileUtility.EnsureDirectoryExists(scriptRootPath); string proxyConfigPath = Path.Combine(scriptRootPath, "proxies.json"); File.WriteAllText(proxyConfigPath, "{}"); await TestHelpers.Await(() => File.Exists(proxyConfigPath)); _loggerProvider = new TestLoggerProvider(); if (environment.IsAppServiceEnvironment()) { // if the test is mocking App Service environment, we need // to also set the HOME and WEBSITE_SITE_NAME variables environment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteHomePath, uniqueTestRootPath); environment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteName, "test-host-name"); } var webHostBuilder = Program.CreateWebHostBuilder() .ConfigureAppConfiguration(c => { // This source reads from AzureWebJobsScriptRoot, which does not work // with the custom paths that these tests are using. var source = c.Sources.OfType <WebScriptHostConfigurationSource>().SingleOrDefault(); if (source != null) { c.Sources.Remove(source); } c.AddTestSettings(); }) .ConfigureLogging(c => { c.AddProvider(_loggerProvider); }) .ConfigureServices(c => { c.ConfigureAll <ScriptApplicationHostOptions>(o => { o.IsSelfHost = true; o.LogPath = Path.Combine(uniqueTestRootPath, "logs"); o.SecretsPath = Path.Combine(uniqueTestRootPath, "secrets"); o.ScriptPath = _expectedScriptPath = scriptRootPath; }); c.AddSingleton <IEnvironment>(_ => environment); c.AddSingleton <IConfigureBuilder <ILoggingBuilder> >(new DelegatedConfigureBuilder <ILoggingBuilder>(b => b.AddProvider(_loggerProvider))); }); _httpServer = new TestServer(webHostBuilder); _httpClient = _httpServer.CreateClient(); _httpClient.BaseAddress = new Uri("https://localhost/"); TestHelpers.WaitForWebHost(_httpClient); var traces = _loggerProvider.GetAllLogMessages().ToArray(); Assert.NotNull(traces.Single(p => p.FormattedMessage.StartsWith("Host is in standby mode"))); _expectedHostId = await _httpServer.Host.Services.GetService <IHostIdProvider>().GetHostIdAsync(CancellationToken.None); }
public void DeploymentImportExcelWithDistinctTest() { //imports an excel with contact spreadsheet including account column PrepareTests(); DeleteAll(Entities.account); DeleteAll(Entities.contact); var workFolder = TestingFolder + @"\ExcelImportScript"; FileUtility.CheckCreateFolder(workFolder); var sourceExcelFile = Path.Combine(workFolder, @"TestExcelImportContacts.xlsx"); File.Copy(@"TestExcelImportContacts.xlsx", sourceExcelFile); var app = CreateAndLoadTestApplication <ImportExcelModule>(); app.AddModule <SavedRequestModule>(); ClearSavedRequests(app); var entryViewmodel = app.NavigateToDialogModuleEntryForm <ImportExcelModule, ImportExcelDialog>(); //select the excel file entryViewmodel.GetFieldViewModel(nameof(ImportExcelRequest.ExcelFile)).ValueObject = new FileReference(sourceExcelFile); //okay on change trigger should have fired and populated mappings on contact var mappingGrid = entryViewmodel.GetEnumerableFieldViewModel(nameof(ImportExcelRequest.Mappings)); var contactSource = mappingGrid.GridRecords.First(r => r.GetRecordTypeFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.SourceTab)).Value.Key.ToLower().Contains("contact")); Assert.AreEqual(Entities.contact, contactSource.GetRecordTypeFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.TargetType)).Value?.Key); //add another map to create accounts for the parentcustomerid column mappingGrid.AddRow(); var accountTarget = mappingGrid.GridRecords.First(r => r.GetRecordTypeFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.SourceTab)).Value == null); accountTarget.GetRecordTypeFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.SourceTab)).Value = accountTarget.GetRecordTypeFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.SourceTab)).ItemsSource.First(); accountTarget.GetRecordTypeFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.TargetType)).Value = new RecordType(Entities.account, Entities.account); accountTarget.GetEnumerableFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.Mappings)).EditButton.Command.Execute(); var accountMapEntryModel = app.GetSubObjectEntryViewModel(entryViewmodel); var fieldMappingGrid = accountMapEntryModel.GetEnumerableFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.Mappings)); //map the account name fieldMappingGrid.AddRow(); fieldMappingGrid.DynamicGridViewModel.GridRecords.First().GetRecordFieldFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.ExcelImportFieldMapping.SourceColumn)).Value = fieldMappingGrid.DynamicGridViewModel.GridRecords.First().GetRecordFieldFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.ExcelImportFieldMapping.SourceColumn)).ItemsSource.First(p => p.Key.Contains("parent")); fieldMappingGrid.DynamicGridViewModel.GridRecords.First().GetRecordFieldFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.ExcelImportFieldMapping.TargetField)).Value = new RecordField(Fields.account_.name, Fields.account_.name); accountMapEntryModel.SaveButtonViewModel.Command.Execute(); Assert.IsFalse(entryViewmodel.ChildForms.Any()); //trigger the import entryViewmodel.SaveButtonViewModel.Command.Execute(); //since there are duplicates the validation is dsiplayed to the user so lets proceed through it var dialog = app.GetNavigatedDialog <ImportExcelDialog>(); var validationDisplay = dialog.Controller.UiItems.First() as ObjectDisplayViewModel; Assert.IsNotNull(validationDisplay); validationDisplay.SaveButtonViewModel.Invoke(); var completionScreen = dialog.CompletionItem as ImportExcelResponse; if (completionScreen.HasError) { Assert.Fail(completionScreen.GetResponseItemsWithError().First().Exception.XrmDisplayString()); } //verify the account and contact created var accounts = XrmService.RetrieveAllEntityType(Entities.account); var contacts = XrmService.RetrieveAllEntityType(Entities.contact); Assert.AreEqual(2, accounts.Count()); Assert.AreEqual(3, contacts.Count()); //okay lets run a second import which will only be for the contacts and verify the same and no errors entryViewmodel = app.NavigateToDialogModuleEntryForm <ImportExcelModule, ImportExcelDialog>(); entryViewmodel.GetFieldViewModel(nameof(ImportExcelRequest.ExcelFile)).ValueObject = new FileReference(sourceExcelFile); mappingGrid = entryViewmodel.GetEnumerableFieldViewModel(nameof(ImportExcelRequest.Mappings)); Assert.AreEqual(1, mappingGrid.DynamicGridViewModel.GridRecords.Count); //trigger the import entryViewmodel.SaveButtonViewModel.Command.Execute(); dialog = app.GetNavigatedDialog <ImportExcelDialog>(); completionScreen = dialog.CompletionItem as ImportExcelResponse; if (completionScreen.HasError) { Assert.Fail(completionScreen.GetResponseItemsWithError().First().Exception.XrmDisplayString()); } Assert.IsTrue(completionScreen.ImportSummary.All(i => i.Created == 0 && i.Updated == 0)); //verify still same number accounts = XrmService.RetrieveAllEntityType(Entities.account); contacts = XrmService.RetrieveAllEntityType(Entities.contact); Assert.AreEqual(2, accounts.Count()); Assert.AreEqual(3, contacts.Count()); //okay lets run another import only for the contacts //with match by name false //in this case we expect the records to be created again entryViewmodel = app.NavigateToDialogModuleEntryForm <ImportExcelModule, ImportExcelDialog>(); entryViewmodel.GetBooleanFieldFieldViewModel(nameof(ImportExcelRequest.MatchRecordsByName)).ValueObject = false; entryViewmodel.GetFieldViewModel(nameof(ImportExcelRequest.ExcelFile)).ValueObject = new FileReference(sourceExcelFile); mappingGrid = entryViewmodel.GetEnumerableFieldViewModel(nameof(ImportExcelRequest.Mappings)); Assert.AreEqual(1, mappingGrid.DynamicGridViewModel.GridRecords.Count); //trigger the import entryViewmodel.SaveButtonViewModel.Command.Execute(); dialog = app.GetNavigatedDialog <ImportExcelDialog>(); completionScreen = dialog.CompletionItem as ImportExcelResponse; if (completionScreen.HasError) { Assert.Fail(completionScreen.GetResponseItemsWithError().First().Exception.XrmDisplayString()); } //verify still same number accounts = XrmService.RetrieveAllEntityType(Entities.account); contacts = XrmService.RetrieveAllEntityType(Entities.contact); Assert.AreEqual(2, accounts.Count()); Assert.AreEqual(6, contacts.Count()); }
private void linkLabelHelp_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start(FileUtility.GetFileReference("Hydromet Tools User Manual.pdf")); }
public void DeploymentImportExcelMatchKeysTest() { //okay this script imports a sheet using //account number as the match key //the initial import creates new records //though one of the five rows throws error due to missing account number (key) //the subsequent one only allows updates //and I delete one of the records imported to verify //it throws an extra error due to a missing key for update in the target PrepareTests(); DeleteAll(Entities.account); var workFolder = TestingFolder + @"\ExcelImportScript"; FileUtility.CheckCreateFolder(workFolder); var sourceExcelFile = Path.Combine(workFolder, @"AccountsWithKeys.xlsx"); File.Copy(@"AccountsWithKeys.xlsx", sourceExcelFile); var app = CreateAndLoadTestApplication <ImportExcelModule>(); var dialog = app.NavigateToDialog <ImportExcelModule, ImportExcelDialog>(); var entryViewmodel = app.GetSubObjectEntryViewModel(dialog); entryViewmodel.GetBooleanFieldFieldViewModel(nameof(ImportExcelRequest.MaskEmails)).Value = true; //select the excel file entryViewmodel.GetFieldViewModel(nameof(ImportExcelRequest.ExcelFile)).ValueObject = new FileReference(sourceExcelFile); //okay on change trigger should have fired and populated mappings on contact //now add match key var tabMappingsGrid = entryViewmodel.GetEnumerableFieldViewModel(nameof(ImportExcelRequest.Mappings)); var accountMap = tabMappingsGrid.DynamicGridViewModel.GridRecords.First(); var keyMapsField = accountMap.GetEnumerableFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.AltMatchKeys)); keyMapsField.EditButton.Command.Execute(); var altMatchKeyEntryForm = entryViewmodel.ChildForms.First() as ObjectEntryViewModel; Assert.IsNotNull(altMatchKeyEntryForm); altMatchKeyEntryForm.LoadFormSections(); var mapsField = altMatchKeyEntryForm.GetEnumerableFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.AltMatchKeys)); mapsField.AddRow(); var matchKeyField = mapsField.DynamicGridViewModel.GridRecords.First().GetRecordFieldFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.ExcelImportMatchKey.TargetField)); Assert.IsTrue(matchKeyField.ItemsSource.Any()); matchKeyField.Value = matchKeyField.ItemsSource.First(f => f.Key == Fields.account_.accountnumber); altMatchKeyEntryForm.SaveButtonViewModel.Invoke(); Assert.IsFalse(entryViewmodel.ChildForms.Any()); //run the import and verify response and account count entryViewmodel.SaveButtonViewModel.Invoke(); var response = app.GetCompletionViewModel(dialog).GetObject() as ImportExcelResponse; Assert.IsNotNull(response); Assert.AreEqual(1, response.GetResponseItemsWithError().Count()); var accounts = XrmService.RetrieveAllEntityType(Entities.account); Assert.AreEqual(4, accounts.Count()); //delete one of the imported accounts XrmService.Delete(accounts.First()); //second import - this one only allows updates dialog = app.NavigateToDialog <ImportExcelModule, ImportExcelDialog>(); entryViewmodel = app.GetSubObjectEntryViewModel(dialog); entryViewmodel.GetBooleanFieldFieldViewModel(nameof(ImportExcelRequest.MaskEmails)).Value = true; entryViewmodel.GetBooleanFieldFieldViewModel(nameof(ImportExcelRequest.UpdateOnly)).Value = true; //select the excel file entryViewmodel.GetFieldViewModel(nameof(ImportExcelRequest.ExcelFile)).ValueObject = new FileReference(sourceExcelFile); //okay on change trigger should have fired and populated mappings on contact //now add match key tabMappingsGrid = entryViewmodel.GetEnumerableFieldViewModel(nameof(ImportExcelRequest.Mappings)); accountMap = tabMappingsGrid.DynamicGridViewModel.GridRecords.First(); keyMapsField = accountMap.GetEnumerableFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.AltMatchKeys)); keyMapsField.EditButton.Command.Execute(); altMatchKeyEntryForm = entryViewmodel.ChildForms.First() as ObjectEntryViewModel; Assert.IsNotNull(altMatchKeyEntryForm); altMatchKeyEntryForm.LoadFormSections(); mapsField = altMatchKeyEntryForm.GetEnumerableFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.AltMatchKeys)); mapsField.AddRow(); matchKeyField = mapsField.DynamicGridViewModel.GridRecords.First().GetRecordFieldFieldViewModel(nameof(ImportExcelRequest.ExcelImportTabMapping.ExcelImportMatchKey.TargetField)); Assert.IsTrue(matchKeyField.ItemsSource.Any()); matchKeyField.Value = matchKeyField.ItemsSource.First(f => f.Key == Fields.account_.accountnumber); altMatchKeyEntryForm.SaveButtonViewModel.Invoke(); Assert.IsFalse(entryViewmodel.ChildForms.Any()); //run the import and verify response and account count entryViewmodel.SaveButtonViewModel.Invoke(); response = app.GetCompletionViewModel(dialog).GetObject() as ImportExcelResponse; Assert.IsNotNull(response); Assert.AreEqual(2, response.GetResponseItemsWithError().Count()); accounts = XrmService.RetrieveAllEntityType(Entities.account); Assert.AreEqual(3, accounts.Count()); }
public List <File> GetFiles(object parentId, OrderBy orderBy, FilterType filterType, bool subjectGroup, Guid subjectID, string searchText, bool searchInContent, bool withSubfolders = false) { if (filterType == FilterType.FoldersOnly) { return(new List <File>()); } //Get only files var files = GetOneDriveItems(parentId, false).Select(ToFile); //Filter if (subjectID != Guid.Empty) { files = files.Where(x => subjectGroup ? CoreContext.UserManager.IsUserInGroup(x.CreateBy, subjectID) : x.CreateBy == subjectID); } switch (filterType) { case FilterType.FoldersOnly: return(new List <File>()); case FilterType.DocumentsOnly: files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Document); break; case FilterType.PresentationsOnly: files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Presentation); break; case FilterType.SpreadsheetsOnly: files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Spreadsheet); break; case FilterType.ImagesOnly: files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Image); break; case FilterType.ArchiveOnly: files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Archive); break; case FilterType.MediaOnly: files = files.Where(x => { FileType fileType; return((fileType = FileUtility.GetFileTypeByFileName(x.Title)) == FileType.Audio || fileType == FileType.Video); }); break; case FilterType.ByExtension: if (!string.IsNullOrEmpty(searchText)) { files = files.Where(x => FileUtility.GetFileExtension(x.Title).Contains(searchText)); } break; } if (!string.IsNullOrEmpty(searchText)) { files = files.Where(x => x.Title.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) != -1); } if (orderBy == null) { orderBy = new OrderBy(SortedByType.DateAndTime, false); } switch (orderBy.SortedBy) { case SortedByType.Author: files = orderBy.IsAsc ? files.OrderBy(x => x.CreateBy) : files.OrderByDescending(x => x.CreateBy); break; case SortedByType.AZ: files = orderBy.IsAsc ? files.OrderBy(x => x.Title) : files.OrderByDescending(x => x.Title); break; case SortedByType.DateAndTime: files = orderBy.IsAsc ? files.OrderBy(x => x.ModifiedOn) : files.OrderByDescending(x => x.ModifiedOn); break; case SortedByType.DateAndTimeCreation: files = orderBy.IsAsc ? files.OrderBy(x => x.CreateOn) : files.OrderByDescending(x => x.CreateOn); break; default: files = orderBy.IsAsc ? files.OrderBy(x => x.Title) : files.OrderByDescending(x => x.Title); break; } return(files.ToList()); }
private static void Getx264Line(FileConfig fileConfig, int pass, out string x264Line, out string outputpath, bool ffmpegpipe = false) { VedioConfig vedioConfig = fileConfig.VedioConfig; x264Line = Resource1.x264Line; x264Line = x264Line.Replace("$preset$", vedioConfig.preset); if (vedioConfig.depth == 10) { if (fileConfig.InputType == InputType.VapoursynthScriptFile) { x264Line = x264Line.Replace("$profile$", "--input-depth 10"); } else { x264Line = x264Line.Replace("$profile$", ""); } } else { x264Line = x264Line.Replace("$profile$", ""); } if (string.IsNullOrEmpty(vedioConfig.tune)) { x264Line = x264Line.Replace("$tune$", ""); } else { x264Line = x264Line.Replace("$tune$", "--tune " + vedioConfig.tune); } if (vedioConfig.BitType == EncoderBitrateType.crf) { x264Line = x264Line.Replace("$crf$", "--crf " + vedioConfig.crf.ToString()); } else if (vedioConfig.BitType == EncoderBitrateType.twopass) { string twopassstr = "--pass " + pass + " --bitrate " + vedioConfig.bitrate.ToString(); x264ArgsManager manager = new x264ArgsManager(x264Line); //提供索引 //if (!string.IsNullOrEmpty(fileConfig.VedioFileFullName)) // if (File.Exists(fileConfig.VedioFileFullName + ".lwi") && manager.GetArgValue("demuxer") == "lavf") // { // twopassstr += " --index \"" + fileConfig.VedioFileFullName + ".lwi\" "; // } // else if (File.Exists(fileConfig.VedioFileFullName + ".ffindex") && manager.GetArgValue("demuxer") == "ffms") // { // twopassstr += " --index \"" + fileConfig.VedioFileFullName + ".ffindex\" "; // } x264Line = x264Line.Replace("$crf$", twopassstr); } else if (vedioConfig.BitType == EncoderBitrateType.qp) { x264Line = x264Line.Replace("$crf$", "--qp " + vedioConfig.crf.ToString()); } if (fileConfig.AudioConfig.Enabled && fileConfig.AudioConfig.CopyStream && fileConfig.UseBat) { x264Line = x264Line.Replace("$acodec$", "copy"); } else { x264Line = x264Line.Replace("$acodec$", "none"); } x264Line = x264Line.Replace("$csp$", vedioConfig.csp); if (ffmpegpipe || !vedioConfig.deinterlace || !vedioConfig.Resize) { x264Line = x264Line.Replace("$resize$", ""); } else { string vf = "--vf "; List <string> vflist = new List <string>(); if (vedioConfig.deinterlace) { string deinterlace = "yadif:mode=2,order=" + (vedioConfig.scanorder ? "tff" : "bff"); vflist.Add(deinterlace); } if (vedioConfig.Resize) { string resize = string.Format("resize:width={0},height={1},method=lanczos", vedioConfig.Width, vedioConfig.Height); vflist.Add(resize); } x264Line = x264Line.Replace("$resize$", vf + string.Join("/", vflist)); } outputpath = string.Empty; string fileExtension = "." + fileConfig.Muxer; string inputArg = ""; //if (fileConfig.AudioConfig.CopyStream || !fileConfig.AudioConfig.Enabled) //{ // outputpath = fileConfig.OutputFile + fileExtension; // outputpath = FileUtility.GetNoSameNameFile(outputpath); //} //else //临时目录 outputpath = FileUtility.AppendRandomName(Config.Temp, Path.GetFileNameWithoutExtension(fileConfig.VedioFileFullName) + ".h264"); //} if (fileConfig.InputType == InputType.AvisynthScriptFile) { x264Line = x264Line.Replace("$input$", fileConfig.AvsFileFullName.Maohao()); } else if (fileConfig.InputType == InputType.AvisynthScript || fileConfig.InputType == InputType.VapoursynthScriptFile) { x264Line = x264Line.Replace("$input$", ""); } else { if (fileConfig.UseBat) { x264Line = x264Line.Replace("$input$", ""); inputArg = " --input - --y4m "; } else { x264Line = x264Line.Replace("$input$", "--input " + fileConfig.VedioFileFullName.Maohao()); } } x264Line = x264Line.Replace("$outputfile$", outputpath.Maohao()); //string log = "--log-file \"" + Path.GetFileNameWithoutExtension(fileConfig.FullName) + "_x264.log\" --log-file-level info "; if (fileConfig.InputType == InputType.AvisynthScriptFile || fileConfig.InputType == InputType.AvisynthScript || fileConfig.VedioConfig.BitType == EncoderBitrateType.twopass) { vedioConfig.UserArgs = vedioConfig.UserArgs.Replace("--demuxer lavf", ""); } if (fileConfig.UseBat) { x264Line = x264Line.Replace("$userargs$", vedioConfig.UserArgs + inputArg); } else { x264Line = x264Line.Replace("$userargs$", vedioConfig.UserArgs); } }
public List <File> GetFilesFiltered(object[] fileIds, FilterType filterType, bool subjectGroup, Guid subjectID, string searchText, bool searchInContent) { if (fileIds == null || fileIds.Length == 0 || filterType == FilterType.FoldersOnly) { return(new List <File>()); } var files = GetFiles(fileIds).AsEnumerable(); //Filter if (subjectID != Guid.Empty) { files = files.Where(x => subjectGroup ? CoreContext.UserManager.IsUserInGroup(x.CreateBy, subjectID) : x.CreateBy == subjectID); } switch (filterType) { case FilterType.FoldersOnly: return(new List <File>()); case FilterType.DocumentsOnly: files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Document); break; case FilterType.PresentationsOnly: files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Presentation); break; case FilterType.SpreadsheetsOnly: files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Spreadsheet); break; case FilterType.ImagesOnly: files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Image); break; case FilterType.ArchiveOnly: files = files.Where(x => FileUtility.GetFileTypeByFileName(x.Title) == FileType.Archive); break; case FilterType.MediaOnly: files = files.Where(x => { FileType fileType; return((fileType = FileUtility.GetFileTypeByFileName(x.Title)) == FileType.Audio || fileType == FileType.Video); }); break; case FilterType.ByExtension: if (!string.IsNullOrEmpty(searchText)) { files = files.Where(x => FileUtility.GetFileExtension(x.Title).Contains(searchText)); } break; } if (!string.IsNullOrEmpty(searchText)) { files = files.Where(x => x.Title.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) != -1); } return(files.ToList()); }
public static File SaveDocument(string envelopeId, string documentId, string documentName, object folderId) { if (string.IsNullOrEmpty(envelopeId)) { throw new ArgumentNullException("envelopeId"); } if (string.IsNullOrEmpty(documentId)) { throw new ArgumentNullException("documentId"); } var token = DocuSignToken.GetToken(); var account = GetDocuSignAccount(token); var configuration = GetConfiguration(account, token); using (var fileDao = Global.DaoFactory.GetFileDao()) using (var folderDao = Global.DaoFactory.GetFolderDao()) { if (string.IsNullOrEmpty(documentName)) { documentName = "new.pdf"; } Folder folder; if (folderId == null || (folder = folderDao.GetFolder(folderId)) == null || folder.RootFolderType == FolderType.TRASH || !Global.GetFilesSecurity().CanCreate(folder)) { if (Global.FolderMy != null) { folderId = Global.FolderMy; } else { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_Create); } } var file = new File { FolderID = folderId, Comment = FilesCommonResource.CommentCreateByDocuSign, Title = FileUtility.ReplaceFileExtension(documentName, ".pdf"), }; var envelopesApi = new EnvelopesApi(configuration); Log.Info("DocuSign webhook get stream: " + documentId); using (var stream = envelopesApi.GetDocument(account.AccountId, envelopeId, documentId)) { file.ContentLength = stream.Length; file = fileDao.SaveFile(file, stream); } FilesMessageService.Send(file, MessageInitiator.ThirdPartyProvider, MessageAction.DocumentSignComplete, "DocuSign", file.Title); FileMarker.MarkAsNew(file); return(file); } }
private Stream CompressToZip(ItemNameValueCollection entriesPathId) { var stream = TempStream.Create(); using (var zip = new Ionic.Zip.ZipOutputStream(stream, true)) { zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level3; zip.AlternateEncodingUsage = Ionic.Zip.ZipOption.AsNecessary; zip.AlternateEncoding = Encoding.UTF8; foreach (var path in entriesPathId.AllKeys) { var counter = 0; foreach (var entryId in entriesPathId[path]) { if (CancellationToken.IsCancellationRequested) { zip.Dispose(); stream.Dispose(); CancellationToken.ThrowIfCancellationRequested(); } var newtitle = path; File file = null; var convertToExt = string.Empty; if (!string.IsNullOrEmpty(entryId)) { FileDao.InvalidateCache(entryId); file = FileDao.GetFile(entryId); if (file == null) { Error = FilesCommonResource.ErrorMassage_FileNotFound; continue; } if (file.ContentLength > SetupInfo.AvailableFileSize) { Error = string.Format(FilesCommonResource.ErrorMassage_FileSizeZip, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize)); continue; } if (files.ContainsKey(file.ID.ToString())) { convertToExt = files[file.ID.ToString()]; if (!string.IsNullOrEmpty(convertToExt)) { newtitle = FileUtility.ReplaceFileExtension(path, convertToExt); } } } if (0 < counter) { var suffix = " (" + counter + ")"; if (!string.IsNullOrEmpty(entryId)) { newtitle = 0 < newtitle.IndexOf('.') ? newtitle.Insert(newtitle.LastIndexOf('.'), suffix) : newtitle + suffix; } else { break; } } zip.PutNextEntry(newtitle); if (!string.IsNullOrEmpty(entryId) && file != null) { try { if (FileConverter.EnableConvert(file, convertToExt)) { //Take from converter using (var readStream = FileConverter.Exec(file, convertToExt)) { readStream.StreamCopyTo(zip); if (!string.IsNullOrEmpty(convertToExt)) { FilesMessageService.Send(file, headers, MessageAction.FileDownloadedAs, file.Title, convertToExt); } else { FilesMessageService.Send(file, headers, MessageAction.FileDownloaded, file.Title); } } } else { using (var readStream = FileDao.GetFileStream(file)) { readStream.StreamCopyTo(zip); FilesMessageService.Send(file, headers, MessageAction.FileDownloaded, file.Title); } } } catch (Exception ex) { Error = ex.Message; Logger.Error(Error, ex); } } counter++; } ProgressStep(); } } return(stream); }
public void CustomisationExporterTestExport() { FileUtility.DeleteFiles(TestingFolder); Assert.IsFalse(FileUtility.GetFiles(TestingFolder).Any()); //okay script through generation of the three types //create test application with module loaded var testApplication = CreateAndLoadTestApplication <CustomisationExporterModule>(); //first script generation of C# entities and fields var request = new CustomisationExporterRequest(); request.IncludeAllRecordTypes = true; request.DuplicateManyToManyRelationshipSides = true; request.Entities = true; request.Fields = true; request.FieldOptionSets = true; request.Relationships = true; request.SharedOptionSets = true; request.IncludeOneToManyRelationships = true; request.SaveToFolder = new Folder(TestingFolder); var response = testApplication.NavigateAndProcessDialog <CustomisationExporterModule, CustomisationExporterDialog, CustomisationExporterResponse>(request); Assert.IsFalse(response.HasError); Assert.IsTrue(FileUtility.GetFiles(TestingFolder).Any()); request.IncludeAllRecordTypes = true; request.DuplicateManyToManyRelationshipSides = false; request.Entities = true; request.Fields = false; request.FieldOptionSets = false; request.Relationships = true; request.SharedOptionSets = false; request.IncludeOneToManyRelationships = false; Thread.Sleep(1000); FileUtility.DeleteFiles(TestingFolder); response = testApplication.NavigateAndProcessDialog <CustomisationExporterModule, CustomisationExporterDialog, CustomisationExporterResponse>(request); Assert.IsFalse(response.HasError); Assert.IsTrue(FileUtility.GetFiles(TestingFolder).Any()); request.IncludeAllRecordTypes = false; request.DuplicateManyToManyRelationshipSides = true; request.Entities = true; request.Fields = true; request.FieldOptionSets = true; request.Relationships = true; request.SharedOptionSets = true; request.IncludeOneToManyRelationships = true; request.RecordTypes = new[] { new RecordTypeSetting(Entities.account, Entities.account), new RecordTypeSetting(Entities.contact, Entities.contact) }; Thread.Sleep(1000); FileUtility.DeleteFiles(TestingFolder); }
public static Task <ZipArchiveEntry> AddFile(this ZipArchive zipArchive, string filePath, string directoryNameInArchive = "") { var fileInfo = FileUtility.FileInfoFromFileName(filePath); return(zipArchive.AddFile(fileInfo, directoryNameInArchive)); }
public static bool SetAceObject(List <AceWrapper> aceWrappers, FileEntry entry, bool notify, string message) { if (entry == null) { throw new ArgumentNullException(FilesCommonResource.ErrorMassage_BadRequest); } if (!CanSetAccess(entry)) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException); } var fileSecurity = Global.GetFilesSecurity(); var entryType = entry.FileEntryType; var recipients = new Dictionary <Guid, FileShare>(); var usersWithoutRight = new List <Guid>(); var changed = false; foreach (var w in aceWrappers.OrderByDescending(ace => ace.SubjectGroup)) { var subjects = fileSecurity.GetUserSubjects(w.SubjectId); var ownerId = entry.RootFolderType == FolderType.USER ? entry.RootFolderCreator : entry.CreateBy; if (entry.RootFolderType == FolderType.COMMON && subjects.Contains(Constants.GroupAdmin.ID) || ownerId == w.SubjectId) { continue; } var share = w.Share; if (w.SubjectId == FileConstant.ShareLinkId) { if (w.Share == FileShare.ReadWrite && CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException); } // only editable format on personal if (CoreContext.Configuration.Personal && !FileUtility.CanWebView(entry.Title) && w.Share != FileShare.Restrict) { throw new SecurityException(FilesCommonResource.ErrorMassage_BadRequest); } // only editable format on SaaS trial if (w.Share != FileShare.Restrict && !CoreContext.Configuration.Standalone && TenantExtra.GetTenantQuota().Trial&& !FileUtility.CanWebView(entry.Title)) { throw new SecurityException(FilesCommonResource.ErrorMassage_BadRequest); } share = w.Share == FileShare.Restrict ? FileShare.None : w.Share; } fileSecurity.Share(entry.ID, entryType, w.SubjectId, share); changed = true; if (w.SubjectId == FileConstant.ShareLinkId) { continue; } entry.Access = share; var listUsersId = new List <Guid>(); if (w.SubjectGroup) { listUsersId = CoreContext.UserManager.GetUsersByGroup(w.SubjectId).Select(ui => ui.ID).ToList(); } else { listUsersId.Add(w.SubjectId); } listUsersId.Remove(SecurityContext.CurrentAccount.ID); if (entryType == FileEntryType.File) { listUsersId.ForEach(uid => FileTracker.ChangeRight(entry.ID, uid, true)); } var addRecipient = share == FileShare.Read || share == FileShare.CustomFilter || share == FileShare.ReadWrite || share == FileShare.Review || share == FileShare.FillForms || share == FileShare.Comment || share == FileShare.None && entry.RootFolderType == FolderType.COMMON; var removeNew = share == FileShare.None && entry.RootFolderType == FolderType.USER || share == FileShare.Restrict; listUsersId.ForEach(id => { recipients.Remove(id); if (addRecipient) { recipients.Add(id, share); } else if (removeNew) { usersWithoutRight.Add(id); } }); } if (entryType == FileEntryType.File) { DocumentServiceHelper.CheckUsersForDrop((File)entry); } if (recipients.Any()) { if (entryType == FileEntryType.File || ((Folder)entry).TotalSubFolders + ((Folder)entry).TotalFiles > 0 || entry.ProviderEntry) { FileMarker.MarkAsNew(entry, recipients.Keys.ToList()); } if ((entry.RootFolderType == FolderType.USER || entry.RootFolderType == FolderType.Privacy) && notify) { NotifyClient.SendShareNotice(entry, recipients, message); } } usersWithoutRight.ForEach(userId => FileMarker.RemoveMarkAsNew(entry, userId)); return(changed); }
public override void Submit_OnClick(object sender, EventArgs e) { if (HifUpload.PostedFile == null || "" == HifUpload.PostedFile.FileName) { return; } var filePath = HifUpload.PostedFile.FileName; try { var fileExtName = PathUtils.GetExtension(filePath).ToLower(); var localDirectoryPath = PathUtility.GetUploadDirectoryPath(SiteInfo, fileExtName); if (!string.IsNullOrEmpty(_realtedPath)) { localDirectoryPath = PathUtility.MapPath(SiteInfo, _realtedPath); DirectoryUtils.CreateDirectoryIfNotExists(localDirectoryPath); } var localFileName = PathUtility.GetUploadFileName(filePath, TranslateUtils.ToBool(DdlIsFileUploadChangeFileName.SelectedValue)); var localFilePath = PathUtils.Combine(localDirectoryPath, localFileName); if (_uploadType == EUploadType.Image && !EFileSystemTypeUtils.IsImageOrFlashOrPlayer(fileExtName)) { FailMessage("此格式不允许上传,此文件夹只允许上传图片以及音视频文件!"); return; } if (_uploadType == EUploadType.Video && !EFileSystemTypeUtils.IsImageOrFlashOrPlayer(fileExtName)) { FailMessage("此格式不允许上传,此文件夹只允许上传图片以及音视频文件!"); return; } if (_uploadType == EUploadType.File && !PathUtility.IsFileExtenstionAllowed(SiteInfo, fileExtName)) { FailMessage("此格式不允许上传,请选择有效的文件!"); return; } if (!PathUtility.IsFileSizeAllowed(SiteInfo, HifUpload.PostedFile.ContentLength)) { FailMessage("上传失败,上传文件超出规定文件大小!"); return; } HifUpload.PostedFile.SaveAs(localFilePath); FileUtility.AddWaterMark(SiteInfo, localFilePath); var fileUrl = PageUtility.GetSiteUrlByPhysicalPath(SiteInfo, localFilePath, true); var textBoxUrl = PageUtility.GetVirtualUrl(SiteInfo, fileUrl); if (string.IsNullOrEmpty(_textBoxClientId)) { LayerUtils.Close(Page); } else { LtlScript.Text = $@" <script type=""text/javascript"" language=""javascript""> if (parent.document.getElementById('{_textBoxClientId}') != null) {{ parent.document.getElementById('{_textBoxClientId}').value = '{textBoxUrl}'; }} {LayerUtils.CloseScript} </script>"; } } catch (Exception ex) { FailMessage(ex, "文件上传失败"); } }
public void DeploymentExportXmlModuleTestExportWithBulkAddToGridAndQuery() { DeleteAll(Entities.account); var account = CreateRecordAllFieldsPopulated(Entities.account); FileUtility.DeleteFiles(TestingFolder); var accountRecord = XrmRecordService.Get(account.LogicalName, account.Id.ToString()); //okay create/navigate to a new entry form entering an ExportXmlRequest var application = CreateAndLoadTestApplication <ExportXmlModule>(); var instance = new ExportXmlRequest(); instance.IncludeNotes = true; instance.IncludeNNRelationshipsBetweenEntities = true; instance.Folder = new Folder(TestingFolder); instance.RecordTypesToExport = new[] { new ExportRecordType() { Type = ExportType.SpecificRecords, RecordType = new RecordType(Entities.account, Entities.account), SpecificRecordsToExport = new [] { new LookupSetting() { Record = accountRecord.ToLookup() } } } }; var entryForm = application.NavigateToDialogModuleEntryForm <ExportXmlModule, ExportXmlDialog>(); application.EnterObject(instance, entryForm); //get the record types subgrid var recordTypesGrid = entryForm.GetEnumerableFieldViewModel(nameof(ExportXmlRequest.RecordTypesToExport)); var row = recordTypesGrid.GridRecords.First(); //edit the accounts export record row row.EditRow(); var specificRecordEntry = entryForm.ChildForms.First() as RecordEntryFormViewModel; specificRecordEntry.LoadFormSections(); var specificRecordsGrid = specificRecordEntry.GetEnumerableFieldViewModel(nameof(ExportRecordType.SpecificRecordsToExport)); //delete the row we added specificRecordsGrid.GridRecords.First().DeleteRow(); Assert.IsFalse(specificRecordsGrid.GridRecords.Any()); //now add using the add multiple option var customFunction = specificRecordsGrid.DynamicGridViewModel.AddMultipleRowButton; customFunction.Invoke(); var bulkAddForm = specificRecordEntry.ChildForms.First() as QueryViewModel; //verify a quickfind finds a record bulkAddForm.QuickFindText = account.GetStringField(Fields.account_.name); bulkAddForm.QuickFind(); Assert.IsFalse(bulkAddForm.DynamicGridViewModel.GridLoadError, bulkAddForm.DynamicGridViewModel.ErrorMessage); Assert.IsTrue(bulkAddForm.DynamicGridViewModel.GridRecords.Any()); //now do an and query on every field in the entity and verify it works bulkAddForm.QueryTypeButton.Invoke(); var lastCondition = bulkAddForm.FilterConditions.Conditions.Last(); Assert.AreEqual(Entities.account, lastCondition.GetRecordTypeFieldViewModel(nameof(ConditionViewModel.QueryCondition.RecordType)).Value.Key); var fieldViewModel = lastCondition.GetRecordFieldFieldViewModel(nameof(ConditionViewModel.QueryCondition.FieldName)); var validSearchFields = fieldViewModel.ItemsSource.Select(i => i.Key).ToArray(); foreach (var field in validSearchFields) { var fieldvalue = accountRecord.GetField(field); if (fieldvalue != null) { lastCondition = bulkAddForm.FilterConditions.Conditions.Last(); Assert.AreEqual(Entities.account, lastCondition.GetRecordTypeFieldViewModel(nameof(ConditionViewModel.QueryCondition.RecordType)).Value.Key); fieldViewModel = lastCondition.GetRecordFieldFieldViewModel(nameof(ConditionViewModel.QueryCondition.FieldName)); fieldViewModel.Value = fieldViewModel.ItemsSource.ToArray().First(i => i.Key == field); var conditionTypeViewModel = lastCondition.GetPicklistFieldFieldViewModel(nameof(ConditionViewModel.QueryCondition.ConditionType)); conditionTypeViewModel.Value = conditionTypeViewModel.ItemsSource.First(i => i.Value == ConditionType.Equal.ToString()); var valueViewModel = lastCondition.GetFieldViewModel(nameof(ConditionViewModel.QueryCondition.Value)); valueViewModel.ValueObject = fieldvalue; //bulkAddForm.QuickFind(); //Assert.IsFalse(bulkAddForm.DynamicGridViewModel.GridLoadError, bulkAddForm.DynamicGridViewModel.ErrorMessage); //Assert.IsTrue(bulkAddForm.DynamicGridViewModel.GridRecords.Any()); } } bulkAddForm.QuickFind(); Assert.IsFalse(bulkAddForm.DynamicGridViewModel.GridLoadError, bulkAddForm.DynamicGridViewModel.ErrorMessage); Assert.IsTrue(bulkAddForm.DynamicGridViewModel.GridRecords.Any()); //select and add bulkAddForm.DynamicGridViewModel.GridRecords.First().IsSelected = true; //this triggered by the grid event bulkAddForm.DynamicGridViewModel.OnSelectionsChanged(); //this is supposed to be the add selected button bulkAddForm.DynamicGridViewModel.CustomFunctions.Last().Invoke(); //and verify the row was added to the records for export Assert.IsTrue(specificRecordsGrid.GridRecords.Any()); //okay now lets do the equivalent for a grid of fields //set this false so the selection of fields is in context specificRecordEntry.GetBooleanFieldFieldViewModel(nameof(ExportRecordType.IncludeAllFields)).Value = false; //get the fields grid and trigger bulk add function var excludeFieldsGrid = specificRecordEntry.GetEnumerableFieldViewModel(nameof(ExportRecordType.IncludeOnlyTheseFields)); //now add using the multi select dialog option excludeFieldsGrid.DynamicGridViewModel.AddMultipleRowButton.Invoke(); var multiSelectForm = specificRecordEntry.ChildForms.First() as MultiSelectDialogViewModel <PicklistOption>; Assert.IsTrue(multiSelectForm.ItemsSource.Any()); Assert.IsTrue(multiSelectForm.ItemsSource.First(i => i.PicklistItem.Key == Fields.account_.name).Select = true); multiSelectForm.ApplyButtonViewModel.Invoke(); Assert.IsFalse(specificRecordEntry.ChildForms.Any()); //and verify the row was added to the records for export Assert.IsTrue(excludeFieldsGrid.GridRecords.Any()); specificRecordEntry.SaveButtonViewModel.Invoke(); Assert.IsFalse(entryForm.ChildForms.Any()); //okay now lets to bulk add on the record types grid var subGrid = entryForm.GetEnumerableFieldViewModel(nameof(ExportXmlRequest.RecordTypesToExport)); subGrid.DynamicGridViewModel.AddMultipleRowButton.Invoke(); multiSelectForm = entryForm.ChildForms.First() as MultiSelectDialogViewModel <PicklistOption>; Assert.IsTrue(multiSelectForm.ItemsSource.Any()); Assert.IsTrue(multiSelectForm.ItemsSource.First(i => i.PicklistItem.Key == Entities.contact).Select = true); multiSelectForm.ApplyButtonViewModel.Invoke(); Assert.IsFalse(entryForm.ChildForms.Any()); }
public void GetRelativePath_ReturnsExpectedPath(string path1, string path2, string expectedPath) { string result = FileUtility.GetRelativePath(path1, path2); Assert.Equal(expectedPath, result); }