private void button1_Click(object sender, EventArgs e) { var vaultguid = comboBox1.Text.Substring(0, 38); var vault = app.LogInToVault(vaultguid); if (RemoveGarbageData(vault)) { return; } try { var bu = new BackupJob { VaultGUID = vaultguid, BackupType = MFBackupType.MFBackupTypeFull, OverwriteExistingFiles = true, TargetFile = @"C:\privatecloud\0installersource\templates\fullbackup\cscec8.mfb" }; app.VaultManagementOperations.BackupVault(bu); richTextBox1.AppendText(Environment.NewLine + "ok"); } catch (Exception ex) { richTextBox1.AppendText(Environment.NewLine + "error:" + ex.Message); } }
public void GenerateVault() { MFilesServerApplication mfserver = new MFilesServerApplication(); mfserver.Connect(NetworkAddress: "mfbuilderdl01"); Vault vault = mfserver.LogInToVault("{1C6A118E-DD8E-411C-8E6F-DAF8805FC781}"); StructureGenerator.VaultToJsonFile(vault, "VaultStructure.json"); }
/// <summary> /// vault登录服务端 /// </summary> /// <param name="user"></param> /// <param name="vaultGuid"></param> /// <returns></returns> private Vault Connect2VaultOnServer(UserDto user, string vaultGuid) { var serverApp = new MFilesServerApplication(); serverApp.Connect(user.MfType, user.UserName, user.PassWord, user.Domain, "ncacn_ip_tcp", user.ip); Vault gVault = serverApp.LogInToVault(vaultGuid); //conn return(gVault); }
/// <summary> /// Connects to a vault on the server. /// </summary> /// <param name="vaultGuid">The Guid of the vault to connect to.</param> /// <param name="vault">The connected vault, or null if connection failed.</param> /// <param name="serverApplication">The server application</param> /// <remarks>Exceptions during connection will be thrown.</remarks> public void ConnectToVault(Guid vaultGuid, out Vault vault, out MFilesServerApplication serverApplication) { vault = null; serverApplication = new MFilesServerApplication(); // Attempt to connect to the vault using the extension method. if (serverApplication.Connect(this) == MFServerConnection.MFServerConnectionAuthenticated) { // Attempt to log into the vault. vault = serverApplication.LogInToVault(vaultGuid.ToString("B")); } }
/// <summary> /// <see cref="MFilesServerApplication"/>.Connect() extension method that accepts a class type that is decorated with a <see cref="MFVaultConnectionAttribute"/>. /// </summary> /// <param name="sa"><see cref="MFilesServerApplication"/> instance</param> /// <param name="decoratedType"><see cref="Type"/> of the class with the connection info decorations</param> /// <param name="vault">Out <see cref="Vault"/></param> /// <returns><see cref="MFVaultConnectionAttribute"/></returns> public static MFVaultConnectionAttribute Connect(this MFilesServerApplication sa, Type decoratedType, out Vault vault) { // Extract the MFVaultConnectionAttribute info attribute. MFVaultConnectionAttribute vaultConn = (MFVaultConnectionAttribute)Attribute.GetCustomAttribute(decoratedType, typeof(MFVaultConnectionAttribute)); // Connect to the server. sa.Connect(vaultConn); // Login to the vault using the GUID provided. // Set the out vault value. vault = sa.LogInToVault(vaultConn.VaultGuid); // Return the Vault Connection info. return(vaultConn); }
public static void LogIntoVault() { //Connect With M-Files Account serverApp.Connect(MFAuthType.MFAuthTypeSpecificMFilesUser, TestConstants.Username, TestConstants.Password); //Connect With Current Windows User //serverApp.Connect(MFAuthType.MFAuthTypeLoggedOnWindowsUser); //Connect With Another Windows Account //serverApp.Connect(MFAuthType.MFAuthTypeSpecificWindowsUser, "gokaykivircioglu", "1", "MECHSOFT"); //Remote Server Connection //serverApp.Connect(MFAuthType.MFAuthTypeSpecificMFilesUser, TestConstants.Username, TestConstants.Password, "", "ncacn_ip_tcp", TestConstants.ServerAddress); //See M-Files API Documantation for further server connection info. //Login to a Vault loggedInVault = serverApp.LogInToVault(TestConstants.VaultGUID); }
private bool ConnectToSelectedVault() { if (vaultComboBox.SelectedItem == null) { MessageBox.Show("Please select the target vault."); return(false); } string currentlySelectedVaultGUID = ((VaultComboBoxItem)vaultComboBox.SelectedItem).VaultGUID; // No need to re-connect if already connected to the selected vault. if (vault == null || !vault.GetGUID().Equals(currentlySelectedVaultGUID)) { vault = app.LogInToVault(currentlySelectedVaultGUID); Console.WriteLine("Connected to: " + vault.Name); } vaultComboBox.Enabled = false; // Must re-start the app if the vault needs to be changed. return(true); }
static void Main(string[] args) { MFilesServerApplication server = new MFilesServerApplication(); server.Connect(); Vault vault = server.LogInToVault("{82FB2FA4-6FBE-4546-A200-11CEF3DF2169}"); PropertyDefAdmin ownerChangeElement = vault.PropertyDefOperations.GetPropertyDefAdmin(1213); ownerChangeElement.SemanticAliases.Value = "M-Files.Property.OwnerChangeElement"; ownerChangeElement.PropertyDef.Name = "Owner (Change Element)"; vault.PropertyDefOperations.UpdatePropertyDefAdmin(ownerChangeElement); PropertyDefAdmin ownerChangeRequest = vault.PropertyDefOperations.GetPropertyDefAdmin(1229); ownerChangeRequest.SemanticAliases.Value = "M-Files.Property.OwnerChangeRequest"; ownerChangeRequest.PropertyDef.Name = "Owner (Change Request)"; vault.PropertyDefOperations.UpdatePropertyDefAdmin(ownerChangeRequest); Console.Write("Press any key to exit..."); Console.ReadKey(); }
/// <summary> /// Executes a search by display/external id using the API directly. /// </summary> static void UseApiDirectly() { // Connect to the server (localhost, tcp, current Windows user). var application = new MFilesServerApplication(); application.ConnectAdministrative(); // Get a connection to the vault. var vault = application.LogInToVault(Program.sampleVaultGuid.ToString("B")); // Create the basic search conditions collection. var searchConditions = new SearchConditions(); // Create the search condition. SearchCondition condition = new SearchCondition { ConditionType = MFConditionType.MFConditionTypeEqual, }; condition.Expression.DataStatusValueType = MFStatusType.MFStatusTypeExtID; condition.TypedValue.SetValue(MFDataType.MFDatatypeText, Program.customerDisplayId); // Add the condition to the collection. searchConditions.Add(-1, condition); // Search. var results = vault.ObjectSearchOperations.SearchForObjectsByConditions(searchConditions, MFSearchFlags.MFSearchFlagNone, SortResults: false); // Output the number of items matching (should be one in each object type, at a maximum). Console.WriteLine($"There were {results.Count} objects with the display Id of {Program.customerDisplayId}:"); Console.WriteLine($"Complete."); // Disconnect. vault.LogOutSilent(); application.Disconnect(); }
internal static Vault Create(MFilesServerApplication app, MFilesVault vault, string templateRootPath, string impersonationUserName, string impersonationPassword, MFSqlDatabase sqlDb, string vaultIndexRootPath = null, bool fullBackupOrStructure = false) { var vp = new VaultProperties { DisplayName = vault.Name, ExtendedMetadataDrivenPermissions = true, FileDataStorageType = MFFileDataStorage.MFFileDataStorageDisk, MainDataFolder = Path.Combine(@"C:\Program Files\M-Files\Server Vaults", vault.Name), VaultGUID = Guid.NewGuid().ToString() }; if (vp.SeparateLocationForFileData == null) { vp.SeparateLocationForFileData = new AdditionalFolders(); } var af = new AdditionalFolder { Folder = Path.Combine(vault.ServerPath, vault.Name), }; if (!String.IsNullOrEmpty(impersonationUserName) && !String.IsNullOrEmpty(impersonationPassword)) { af.Impersonation = new Impersonation { Account = impersonationUserName, Password = impersonationPassword, ImpersonationType = MFImpersonationType.MFImpersonationTypeSpecificAccount }; } vp.SeparateLocationForFileData.Add(-1, af); var version = app.GetServerVersion().Major; if (sqlDb != null) { var admin = new Impersonation { Account = sqlDb.AdminUserName, Password = sqlDb.AdminPassword, ImpersonationType = sqlDb.SqlserverUser ? MFImpersonationType.MFImpersonationTypeExtAccount : MFImpersonationType.MFImpersonationTypeSpecificAccount }; var mfsqldb = new SQLDatabase { Server = sqlDb.Server, Name = sqlDb.Catelog, Engine = MFDBEngine.MFDBEngineMSSQLServer }; mfsqldb.AdminUser = admin; //2015 vp.SQLDatabase = mfsqldb; } vp.FullTextSearchLanguage = version < 11 ? "other" : "chs"; if (fullBackupOrStructure) { var rj = new RestoreJob { BackupFileFull = templateRootPath, VaultProperties = vp, OverwriteExistingFiles = true }; app.VaultManagementOperations.RestoreVault(rj); vault.Guid = vp.VaultGUID; return(null); } var guid = app.VaultManagementOperations.CreateNewVault(vp); vault.Guid = guid; var import = new ImportContentJob { ActivateAutomaticPermissionsForNewOrChangedDefinitions = true, DisableImportedExternalObjectTypeConnections = true, DisableImportedExternalUserGroups = true, DisableImportedVaultEventHandlers = false, Flags = MFImportContentFlag.MFImportContentFlagNone, IgnoreAutomaticPermissionsDefinedByObjects = false, SourceLocation = Path.Combine(templateRootPath, "Index") }; if (!String.IsNullOrEmpty(impersonationUserName) && !String.IsNullOrEmpty(impersonationPassword)) { import.Impersonation = new Impersonation { Account = impersonationUserName, Password = impersonationPassword, ImpersonationType = MFImpersonationType.MFImpersonationTypeSpecificAccount }; } var newvault = app.LogInToVault(guid); //todo,会有数据超限的问题, 2015貌似没有问题,但更新模板数据时可能会有这个问题 try { newvault.ManagementOperations.ImportContent(import); } catch (Exception ex) { Log.Error("导入模版元数据出错:" + ex.Message, ex); } return(newvault); }
/// <summary> /// Installer Method - Install app to Vault. /// </summary> /// <param name="packedApp">mfappx Path</param> /// <param name="settings">Populated UXDevSettings Object</param> private static void InstallApp(string packedApp, UXDevSettings settings) { // Create a caption block for the installation. using (Logger.CaptionBlock("Connecting to Vault")) { // Connect to Vault var serverApp = new MFilesServerApplication(); // report the creation Logger.WriteLine("Server App Created => Connecting Administratively"); // Connect Administrative => As the Take Vault on/off-line requires it. serverApp.ConnectAdministrative( null, settings.AuthType, settings.Username, settings.Password, settings.Domain, settings.ProtocolSequence, settings.ServerAddress, settings.Port, settings.LocalComputerName ); // Report the successful connection. Logger.WriteLine(@"Connected to server."); // Log into the Vault Vault vault = serverApp.LogInToVault(settings.VaultGuid); // Report the successful Log On. Logger.WriteLine(@"Logged into Vault: " + vault.Name); // create a caption block to make the output more readable. using (Logger.CaptionBlock("Installing Application")) { // Try to install the application. try { Logger.WriteLine(@"Attempting Application Installation"); // Install the Application to the Vault. vault.CustomApplicationManagementOperations.InstallCustomApplication(packedApp); // If no error was thrown, report the success. Logger.WriteLine(@"Application Installed Successfully"); } catch (Exception ex) { // A common error is the already exists. Logger.WriteLine(ex.Message.StartsWith(@"Already exists") ? ex.Message.Substring(0, ex.Message.IndexOf('\n')) : ex.Message); } } // create a caption block to make the output more readable. using (Logger.CaptionBlock("Post Installation Processing")) { // Determine if a Auto-Allow Installation Registry file should be created. if (settings.GenerateAutoInstallReg) { Logger.WriteLine("Generating the Auto Installation Registry File"); // Get the Template Text and inject values string reg = StringTemplate.AllowSilentInstall; reg = reg.Replace("$VERSION", vault.GetServerVersionOfVault().Display); reg = reg.Replace("$NAME", Path.GetFileNameWithoutExtension(settings.Outputname)); reg = reg.Replace("$VAULTGUID", vault.GetGUID()); reg = reg.Replace("$APPGUID", settings.AppDef.guid); // create the registry file path. string regPath = Path.Combine(settings.DirectoryToZip, @"allow_auto_install.reg"); // Delete and destroy the existing reg file... if there is one. if (File.Exists(regPath)) { File.Delete(regPath); } // Write the reg file to disk. File.WriteAllText(regPath, reg); Logger.WriteLine("Registry File Created: " + regPath); } // Should the vault be restarted after processing? if (settings.RestartVault) { Logger.WriteLine("About to Restart the Vault"); Logger.WriteLine("\t- Logging out."); // TODO - This does not seem to work, a manual logout is recommended. vault.LogOutSilent(); // Try to take the vault on/off-line. try { Logger.WriteLine("\t- Taking Vault Offline"); serverApp.VaultManagementOperations.TakeVaultOffline(settings.VaultGuid, true); Logger.WriteLine("\t- Bringing Vault back Online"); serverApp.VaultManagementOperations.BringVaultOnline(settings.VaultGuid); Logger.WriteLine("Vault Now Online"); } catch (Exception ex) { // report the error Logger.WriteLine(ex.Message); } // TODO - I need to find a better way to close open client windows, but until then... if (settings.KillExplorerWindows) { Logger.WriteLine("Closing Open Explorer Windows."); foreach (Process p in Process.GetProcessesByName("explorer")) { p.Kill(); } } Logger.WriteLine(@"Waiting a few seconds..."); Thread.Sleep(1000 * 2); } // Determine if we should open the Vault Window for the Developer. if (Settings.OpenVault) { Logger.WriteLine(@"Opening Path: " + settings.LocalVaultPath); // Open the path in the default application. Process.Start(Settings.LocalVaultPath); } } } // Should we leave the console window open or not? if (!settings.AutoExitApp) { Logger.NewLine(); Logger.WriteLine(@"Press any key to exit..."); Console.ReadKey(); } }
public static Vault ConnectServer( ref string ErrMsg, string vautGUId, string vaultLogin, // baymain/jutta.ipsen --- split domain string vaultPWD, bool isWindowsUser, string VaultNetworkAddress, string VaultEndpoint, string VaultProtocol, string windowUser = "", string windowDomain = "" ) { Vault _vault = null; try { MFilesServerApplication _server = new MFilesServerApplication(); //MFilesClientApplication _client = new MFilesClientApplication(); splitDomain(ref windowUser, ref windowDomain, vaultLogin); if (VaultNetworkAddress.Equals("localhost")) { if (isWindowsUser == true) { if (windowDomain.Equals("")) { _server.Connect(MFAuthType.MFAuthTypeSpecificWindowsUser, windowUser, vaultPWD); } else { _server.Connect(MFAuthType.MFAuthTypeSpecificWindowsUser, windowUser, vaultPWD, windowDomain); } } else { _server.Connect(MFAuthType.MFAuthTypeSpecificMFilesUser, vaultLogin, vaultPWD); } } else// network { string Protocol; if (String.IsNullOrEmpty(VaultProtocol)) { Protocol = "ncacn_ip_tcp"; //(TCP/IP protocol) } else { Protocol = VaultProtocol; } if (isWindowsUser == true) { if (windowDomain.Equals("")) { _server.Connect(MFAuthType.MFAuthTypeSpecificWindowsUser, windowUser, vaultPWD, Type.Missing, Protocol, VaultNetworkAddress, VaultEndpoint); } else { _server.Connect(MFAuthType.MFAuthTypeSpecificWindowsUser, windowUser, vaultPWD, windowDomain, Protocol, VaultNetworkAddress, VaultEndpoint); } } else { _server.Connect(MFAuthType.MFAuthTypeSpecificMFilesUser, vaultLogin, vaultPWD, Type.Missing, Protocol, VaultNetworkAddress, VaultEndpoint); } } _vault = _server.LogInToVault(vautGUId); //var vaultConnection = _client.GetVaultConnection(vaultName); //IntPtr hwnd = Process.GetCurrentProcess().MainWindowHandle; //_vault = vaultConnection.BindToVault(hwnd, true, true); return(_vault); } catch (Exception e) { ErrMsg = e.Message; return(_vault); } }
/// <summary> /// Executes a segmented search using the API directly. /// </summary> static void UseApiDirectly() { // Connect to the server (localhost, tcp, current Windows user). var application = new MFilesServerApplication(); application.ConnectAdministrative(); // Get a connection to the vault. var vault = application.LogInToVault(Program.sampleVaultGuid.ToString("B")); // Load the object types from the vault. Console.WriteLine("Loading object types..."); var objectTypes = vault .ObjectTypeOperations .GetObjectTypes() .Cast <ObjType>() .ToList(); Console.WriteLine($"Iterating over {objectTypes.Count} object types..."); // Iterate over the object types to count the objects. foreach (var objectType in objectTypes) { // Create the basic search conditions collection. var searchConditions = new SearchConditions(); // Add a condition for the object type we're interested in. { // Create the search condition (for object type id). SearchCondition condition = new SearchCondition { ConditionType = MFConditionType.MFConditionTypeEqual }; condition.Expression.SetStatusValueExpression(MFStatusType.MFStatusTypeObjectTypeID, null); condition.TypedValue.SetValue(MFDataType.MFDatatypeLookup, objectType.ID); // Add the condition at the index provided. searchConditions.Add(-1, condition); } // Create variables for the segment information. const int itemsPerSegment = 1000; // Maximum number of items in each segment. var segment = 0; // Start; this will increment as we go. var moreItems = true; // Whether there are more items to load. var countIncludingDeleted = 0; // The count of matching items. // Whilst there are items in the results, we need to loop. while (moreItems) { // Execute a search within the object id segment. { // Clone the search conditions (so we can add current-segment condition). var internalSearchConditions = searchConditions.Clone(); // Add search condition: // Id within the range: (segment - itemsPerSegment) to ((segment + 1) * itemsPerSegment) { // Create the search condition. SearchCondition condition = new SearchCondition { ConditionType = MFConditionType.MFConditionTypeEqual }; condition.Expression.SetObjectIDSegmentExpression(itemsPerSegment); condition.TypedValue.SetValue(MFDataType.MFDatatypeInteger, segment); // Add the condition at the index provided. internalSearchConditions.Add(-1, condition); } // Execute the search and increment the count. countIncludingDeleted += vault.ObjectSearchOperations .SearchForObjectsByConditionsEx(internalSearchConditions, MFSearchFlags.MFSearchFlagDisableRelevancyRanking, SortResults: false, MaxResultCount: 0, SearchTimeoutInSeconds: 0).Count; // Move to the next segment. segment++; } // Are there any more items? { // Clone the search conditions (so we can add object id condition). var internalSearchConditions = searchConditions.Clone(); // Add search condition: // Id at least (segment * itemsPerSegment) { // Create the search condition. SearchCondition condition = new SearchCondition { ConditionType = MFConditionType.MFConditionTypeGreaterThanOrEqual }; condition.Expression.SetStatusValueExpression(MFStatusType.MFStatusTypeObjectID, null); condition.TypedValue.SetValue(MFDataType.MFDatatypeInteger, segment * itemsPerSegment); // Add the condition at the index provided. internalSearchConditions.Add(-1, condition); } // If we get one item then there's more results. moreItems = 1 == vault.ObjectSearchOperations.SearchForObjectsByConditionsEx( internalSearchConditions, // Our search conditions. MFSearchFlags.MFSearchFlagDisableRelevancyRanking, SortResults: false, // Don't bother attempting to sort them. MaxResultCount: 1, // We only need to know if there is at least one, nothing more. SearchTimeoutInSeconds: 0).Count; } } // Output the stats. Console.WriteLine($"\t{objectType.NamePlural}:"); Console.WriteLine($"\t\tTotal: {countIncludingDeleted} (included deleted)"); } Console.WriteLine($"Complete."); // Disconnect. vault.LogOutSilent(); application.Disconnect(); }
/// <summary> /// Installer Method - Install app to Vault. /// </summary> /// <param name="packedApp">mfappx Path</param> /// <param name="settings">Populated UXDevSettings Object</param> private static void InstallApp( string packedApp, UXDevSettings settings) { // Create a caption block for the installation. using( Logger.CaptionBlock( "Connecting to Vault" ) ) { // Connect to Vault var serverApp = new MFilesServerApplication(); // report the creation Logger.WriteLine("Server App Created => Connecting Administratively"); // Connect Administrative => As the Take Vault on/off-line requires it. serverApp.ConnectAdministrative( null, settings.AuthType, settings.Username, settings.Password, settings.Domain, settings.ProtocolSequence, settings.ServerAddress, settings.Port, settings.LocalComputerName ); // Report the successful connection. Logger.WriteLine(@"Connected to server."); // Log into the Vault Vault vault = serverApp.LogInToVault(settings.VaultGuid); // Report the successful Log On. Logger.WriteLine(@"Logged into Vault: " + vault.Name); // create a caption block to make the output more readable. using( Logger.CaptionBlock( "Installing Application" ) ) { // Try to install the application. try { Logger.WriteLine(@"Attempting Application Installation"); // Install the Application to the Vault. vault.CustomApplicationManagementOperations.InstallCustomApplication(packedApp); // If no error was thrown, report the success. Logger.WriteLine(@"Application Installed Successfully"); } catch (Exception ex) { // A common error is the already exists. Logger.WriteLine( ex.Message.StartsWith( @"Already exists" ) ? ex.Message.Substring( 0, ex.Message.IndexOf( '\n' ) ) : ex.Message ); } } // create a caption block to make the output more readable. using (Logger.CaptionBlock("Post Installation Processing")) { // Determine if a Auto-Allow Installation Registry file should be created. if (settings.GenerateAutoInstallReg) { Logger.WriteLine("Generating the Auto Installation Registry File"); // Get the Template Text and inject values string reg = StringTemplate.AllowSilentInstall; reg = reg.Replace("$VERSION", vault.GetServerVersionOfVault().Display); reg = reg.Replace("$NAME", Path.GetFileNameWithoutExtension(settings.Outputname)); reg = reg.Replace("$VAULTGUID", vault.GetGUID()); reg = reg.Replace("$APPGUID", settings.AppDef.guid); // create the registry file path. string regPath = Path.Combine(settings.DirectoryToZip, @"allow_auto_install.reg"); // Delete and destroy the existing reg file... if there is one. if (File.Exists(regPath)) File.Delete(regPath); // Write the reg file to disk. File.WriteAllText(regPath, reg); Logger.WriteLine("Registry File Created: " + regPath); } // Should the vault be restarted after processing? if (settings.RestartVault) { Logger.WriteLine("About to Restart the Vault"); Logger.WriteLine("\t- Logging out."); // TODO - This does not seem to work, a manual logout is recommended. vault.LogOutSilent(); // Try to take the vault on/off-line. try { Logger.WriteLine("\t- Taking Vault Offline"); serverApp.VaultManagementOperations.TakeVaultOffline(settings.VaultGuid, true); Logger.WriteLine("\t- Bringing Vault back Online"); serverApp.VaultManagementOperations.BringVaultOnline(settings.VaultGuid); Logger.WriteLine("Vault Now Online"); } catch (Exception ex) { // report the error Logger.WriteLine(ex.Message); } // TODO - I need to find a better way to close open client windows, but until then... if (settings.KillExplorerWindows) { Logger.WriteLine("Closing Open Explorer Windows."); foreach (Process p in Process.GetProcessesByName("explorer")) p.Kill(); } Logger.WriteLine(@"Waiting a few seconds..."); Thread.Sleep(1000 * 2); } // Determine if we should open the Vault Window for the Developer. if (Settings.OpenVault) { Logger.WriteLine(@"Opening Path: " + settings.LocalVaultPath); // Open the path in the default application. Process.Start(Settings.LocalVaultPath); } } } // Should we leave the console window open or not? if (!settings.AutoExitApp) { Logger.NewLine(); Logger.WriteLine(@"Press any key to exit..."); Console.ReadKey(); } }