private static void ImportData <T> (ImporterCallback <T> callback, bool usesLocation) { IDataImporter importer; string filename; long? locationId; BusinessDomain.FeedbackProvider.TrackEvent("Import data", typeof(T).Name.CamelSpace()); using (ImportObjects <T> dialog = new ImportObjects <T> (usesLocation)) { if (dialog.Run() != ResponseType.Ok) { return; } importer = dialog.Importer; filename = dialog.FileName; locationId = dialog.Location != null ? dialog.Location.Id : (long?)null; } if (importer.UsesFile && !File.Exists(filename)) { MessageError.ShowDialog(Translator.GetString("Please select a valid source file to import!")); return; } try { PropertyMap propertyMap; using (ImportObjectsMapping <T> dialog = new ImportObjectsMapping <T> (importer, filename)) { if (dialog.Run() != ResponseType.Ok) { return; } propertyMap = dialog.PropertyMap; } ExchangeHelper.ImportObjects(importer, filename, propertyMap, locationId, callback); MessageError.ShowDialog(Translator.GetString("Import completed successfully."), ErrorSeverity.Information); } catch (LicenseLimitationException ex) { MessageError.ShowDialog(ex.Message, ErrorSeverity.Warning, ex); } catch (IOException ex) { MessageError.ShowDialog(Translator.GetString("The selected source file is in use by another application! Please close all other applications and try again."), ErrorSeverity.Warning, ex); } catch (Exception ex) { MessageError.ShowDialog(Translator.GetString("Error occurred while performing import."), ErrorSeverity.Warning, ex); } }
/// <summary> /// Synchronously synchronizes all local shares and media item aspect types with the MediaPortal server. /// </summary> protected async Task CompleteServerConnectionAsync() { UPnPServerControllerServiceProxy sc = ServerControllerServiceProxy; ISystemResolver systemResolver = ServiceRegistration.Get<ISystemResolver>(); if (sc != null) { try { // Check if we're attached to the server. If the server lost its state, it might have forgotten us. if (!sc.GetAttachedClients().Select(clientMetadata => clientMetadata.SystemId).Contains(systemResolver.LocalSystemId)) sc.AttachClient(systemResolver.LocalSystemId); } catch (Exception e) { ServiceRegistration.Get<ILogger>().Warn("ServerConnectionManager: Error checking attachment state at home server '{0}'", e, HomeServerSystemId); return; // This is a real error case, we don't need to try any other service calls } // Register state variables change events sc.AttachedClientsChanged += OnAttachedClientsChanged; sc.ConnectedClientsChanged += OnConnectedClientsChanged; } IImporterWorker importerWorker = ServiceRegistration.Get<IImporterWorker>(); ICollection<Share> newShares = new List<Share>(); UPnPContentDirectoryServiceProxy cd = ContentDirectoryServiceProxy; if (cd != null) { // Update shares registration try { ISettingsManager settingsManager = ServiceRegistration.Get<ISettingsManager>(); ServerConnectionSettings settings = settingsManager.Load<ServerConnectionSettings>(); ServiceRegistration.Get<ILogger>().Info("ServerConnectionManager: Synchronizing shares with home server"); IDictionary<Guid, Share> serverShares = new Dictionary<Guid, Share>(); foreach (Share share in await cd.GetSharesAsync(systemResolver.LocalSystemId, SharesFilter.All)) serverShares.Add(share.ShareId, share); IDictionary<Guid, Share> localShares = ServiceRegistration.Get<ILocalSharesManagement>().Shares; // First remove shares - if the client lost its configuration and re-registers an already present share, the server's method will throw an exception foreach (Guid serverShareId in serverShares.Keys) if (!localShares.ContainsKey(serverShareId)) await cd.RemoveShareAsync(serverShareId); foreach (Share localShare in localShares.Values) { RelocationMode relocationMode; if (!serverShares.ContainsKey(localShare.ShareId)) { await cd.RegisterShareAsync(localShare); newShares.Add(localShare); } else if (settings.CachedSharesUpdates.TryGetValue(localShare.ShareId, out relocationMode)) { await cd.UpdateShareAsync(localShare.ShareId, localShare.BaseResourcePath, localShare.Name, localShare.UseShareWatcher, localShare.MediaCategories, relocationMode); switch (relocationMode) { case RelocationMode.ClearAndReImport: importerWorker.ScheduleImport(localShare.BaseResourcePath, localShare.MediaCategories, true); break; case RelocationMode.Relocate: importerWorker.ScheduleRefresh(localShare.BaseResourcePath, localShare.MediaCategories, true); break; } } } settings.CachedSharesUpdates.Clear(); settingsManager.Save(settings); } catch (Exception e) { ServiceRegistration.Get<ILogger>().Warn("ServerConnectionManager: Could not synchronize local shares with server", e); } // Update media item aspect type registration try { IMediaItemAspectTypeRegistration miatr = ServiceRegistration.Get<IMediaItemAspectTypeRegistration>(); ServiceRegistration.Get<ILogger>().Info("ServerConnectionManager: Checking for unregistered media item aspect types at home server"); ICollection<Guid> serverMIATypes = await cd.GetAllManagedMediaItemAspectTypesAsync(); foreach (KeyValuePair<Guid, MediaItemAspectMetadata> localMiaType in miatr.LocallyKnownMediaItemAspectTypes) if (!serverMIATypes.Contains(localMiaType.Key)) { ServiceRegistration.Get<ILogger>().Info("ServerConnectionManager: Adding unregistered media item aspect type '{0}' (ID '{1}') at home server", localMiaType.Value.Name, localMiaType.Key); await cd.AddMediaItemAspectStorageAsync(localMiaType.Value); } } catch (Exception e) { ServiceRegistration.Get<ILogger>().Warn("ServerConnectionManager: Could not synchronize local media item aspect types with server", e); } // Register state variables change events cd.PlaylistsChanged += OnContentDirectoryPlaylistsChanged; cd.MIATypeRegistrationsChanged += OnContentDirectoryMIATypeRegistrationsChanged; cd.RegisteredSharesChangeCounterChanged += OnRegisteredSharesChangeCounterChanged; // Activate importer worker ServiceRegistration.Get<ILogger>().Debug("ServerConnectionManager: Activating importer worker"); ImporterCallback ic = new ImporterCallback(cd); importerWorker.Activate(ic, ic); foreach (Share share in newShares) importerWorker.ScheduleImport(share.BaseResourcePath, share.MediaCategories, true); } }
/// <summary> /// Synchronously synchronizes all local shares and media item aspect types with the MediaPortal server. /// </summary> protected void CompleteServerConnection() { UPnPServerControllerServiceProxy sc = ServerControllerServiceProxy; ISystemResolver systemResolver = ServiceRegistration.Get<ISystemResolver>(); if (sc != null) { try { // Check if we're attached to the server. If the server lost its state, it might have forgotten us. if (!sc.GetAttachedClients().Select(clientMetadata => clientMetadata.SystemId).Contains(systemResolver.LocalSystemId)) sc.AttachClient(systemResolver.LocalSystemId); } catch (Exception e) { ServiceRegistration.Get<ILogger>().Warn("ServerConnectionManager: Error checking attachment state at home server '{0}'", e, HomeServerSystemId); return; // This is a real error case, we don't need to try any other service calls } // Register state variables change events sc.AttachedClientsChanged += OnAttachedClientsChanged; sc.ConnectedClientsChanged += OnConnectedClientsChanged; } IImporterWorker importerWorker = ServiceRegistration.Get<IImporterWorker>(); ICollection<Share> newShares = new List<Share>(); UPnPContentDirectoryServiceProxy cd = ContentDirectoryServiceProxy; if (cd != null) { // Update shares registration try { ISettingsManager settingsManager = ServiceRegistration.Get<ISettingsManager>(); ServerConnectionSettings settings = settingsManager.Load<ServerConnectionSettings>(); ServiceRegistration.Get<ILogger>().Info("ServerConnectionManager: Synchronizing shares with home server"); IDictionary<Guid, Share> serverShares = new Dictionary<Guid, Share>(); foreach (Share share in cd.GetShares(systemResolver.LocalSystemId, SharesFilter.All)) serverShares.Add(share.ShareId, share); IDictionary<Guid, Share> localShares = ServiceRegistration.Get<ILocalSharesManagement>().Shares; // First remove shares - if the client lost its configuration and re-registers an already present share, the server's method will throw an exception foreach (Guid serverShareId in serverShares.Keys) if (!localShares.ContainsKey(serverShareId)) cd.RemoveShare(serverShareId); foreach (Share localShare in localShares.Values) { RelocationMode relocationMode; if (!serverShares.ContainsKey(localShare.ShareId)) { cd.RegisterShare(localShare); newShares.Add(localShare); } else if (settings.CachedSharesUpdates.TryGetValue(localShare.ShareId, out relocationMode)) { cd.UpdateShare(localShare.ShareId, localShare.BaseResourcePath, localShare.Name, localShare.MediaCategories, relocationMode); switch (relocationMode) { case RelocationMode.ClearAndReImport: importerWorker.ScheduleImport(localShare.BaseResourcePath, localShare.MediaCategories, true); break; case RelocationMode.Relocate: importerWorker.ScheduleRefresh(localShare.BaseResourcePath, localShare.MediaCategories, true); break; } } } settings.CachedSharesUpdates.Clear(); settingsManager.Save(settings); } catch (Exception e) { ServiceRegistration.Get<ILogger>().Warn("ServerConnectionManager: Could not synchronize local shares with server", e); } // Update media item aspect type registration try { IMediaItemAspectTypeRegistration miatr = ServiceRegistration.Get<IMediaItemAspectTypeRegistration>(); ServiceRegistration.Get<ILogger>().Info("ServerConnectionManager: Checking for unregistered media item aspect types at home server"); ICollection<Guid> serverMIATypes = cd.GetAllManagedMediaItemAspectTypes(); foreach (KeyValuePair<Guid, MediaItemAspectMetadata> localMiaType in miatr.LocallyKnownMediaItemAspectTypes) if (!serverMIATypes.Contains(localMiaType.Key)) { ServiceRegistration.Get<ILogger>().Info("ServerConnectionManager: Adding unregistered media item aspect type '{0}' (ID '{1}') at home server", localMiaType.Value.Name, localMiaType.Key); cd.AddMediaItemAspectStorage(localMiaType.Value); } } catch (Exception e) { ServiceRegistration.Get<ILogger>().Warn("ServerConnectionManager: Could not synchronize local media item aspect types with server", e); } // Register state variables change events cd.PlaylistsChanged += OnContentDirectoryPlaylistsChanged; cd.MIATypeRegistrationsChanged += OnContentDirectoryMIATypeRegistrationsChanged; cd.RegisteredSharesChangeCounterChanged += OnRegisteredSharesChangeCounterChanged; cd.CurrentlyImportingSharesChanged += OnCurrentlyImportingSharesChanged; // Activate importer worker ServiceRegistration.Get<ILogger>().Debug("ServerConnectionManager: Activating importer worker"); ImporterCallback ic = new ImporterCallback(cd); importerWorker.Activate(ic, ic); foreach (Share share in newShares) importerWorker.ScheduleImport(share.BaseResourcePath, share.MediaCategories, true); } }
public static void ImportObjects <T> (IDataImporter importer, string file, PropertyMap propertyMap, long?locationId, ImporterCallback <T> callback) { string [] [] data = new string [0] []; LicenseLimitationException llex = null; try { importer.Import(file, out data); } catch (LicenseLimitationException ex) { llex = ex; } for (int i = 0; i < data.Length; i++) { T obj = CreateImportedObject <T> (propertyMap, data [i]); bool cancel; callback(obj, locationId, i, data.Length, out cancel); if (cancel) { break; } } if (llex != null) { throw llex; } }
public string GenerateMetaData(string strSrcTypeLib, string outPath, byte[] PublicKey, StrongNameKeyPair KeyPair) { string str2; try { new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); } catch (Exception exception) { if ((exception is NullReferenceException) || (exception is SEHException)) { throw; } ComSoapPublishError.Report(exception.ToString()); throw; } string str = ""; if ((0 >= strSrcTypeLib.Length) || (0 >= outPath.Length)) { return(str); } if (!outPath.EndsWith("/", StringComparison.Ordinal) && !outPath.EndsWith(@"\", StringComparison.Ordinal)) { outPath = outPath + @"\"; } ITypeLib typeLib = null; typeLib = CacheInfo.GetTypeLib(strSrcTypeLib); if (typeLib == null) { return(str); } str = CacheInfo.GetMetadataName(strSrcTypeLib, typeLib, out str2); if (str.Length == 0) { return(str); } if (this._nameonly) { return(str); } string assemblyPath = outPath + str2; if (this._signed) { try { AssemblyManager manager = new AssemblyManager(); if (manager.CompareToCache(assemblyPath, strSrcTypeLib)) { new Publish().GacInstall(assemblyPath); return(str); } if (manager.GetFromCache(assemblyPath, strSrcTypeLib)) { new Publish().GacInstall(assemblyPath); return(str); } goto Label_0133; } catch (Exception exception2) { if ((exception2 is NullReferenceException) || (exception2 is SEHException)) { throw; } ComSoapPublishError.Report(exception2.ToString()); goto Label_0133; } } if (File.Exists(assemblyPath)) { return(str); } Label_0133: try { ITypeLibConverter converter = new TypeLibConverter(); ImporterCallback notifySink = new ImporterCallback { OutputDir = outPath }; AssemblyBuilder builder = converter.ConvertTypeLibToAssembly(typeLib, assemblyPath, TypeLibImporterFlags.UnsafeInterfaces, notifySink, PublicKey, KeyPair, null, null); FileInfo info = new FileInfo(assemblyPath); builder.Save(info.Name); if (this._signed) { new AssemblyManager().CopyToCache(assemblyPath, strSrcTypeLib); new Publish().GacInstall(assemblyPath); } } catch (ReflectionTypeLoadException exception3) { Exception[] loaderExceptions = exception3.LoaderExceptions; for (int i = 0; i < loaderExceptions.Length; i++) { try { ComSoapPublishError.Report(loaderExceptions[i].ToString()); } catch (Exception exception4) { if ((exception4 is NullReferenceException) || (exception4 is SEHException)) { throw; } ComSoapPublishError.Report(exception3.ToString()); } } return(string.Empty); } catch (Exception exception5) { if ((exception5 is NullReferenceException) || (exception5 is SEHException)) { throw; } ComSoapPublishError.Report(exception5.ToString()); return(string.Empty); } return(str); }
//************************************************************************** // Static importer function used by main and the callback. //************************************************************************** public static AssemblyBuilder DoImport(System.Runtime.InteropServices.ComTypes.ITypeLib TypeLib, String strAssemblyFileName, String strAssemblyNamespace, Version asmVersion, byte[] publicKey, StrongNameKeyPair keyPair, String strProduct, String strProductVersion, String strCompany, String strCopyright, String strTrademark, TypeLibImporterFlags flags, bool isVersion2, bool isPreserveSig, String ruleSetFileName) { if (TypeLib == null) throw new ArgumentNullException(nameof(TypeLib)); // Detemine the assembly file name. String asmFileName = Path.GetFileName(strAssemblyFileName); // Add this typelib to list of importing typelibs. Guid guid = Marshal.GetTypeLibGuid(TypeLib); s_ImportingLibraries.Add(guid.ToString(), guid); // If the type library is 64-bit, make sure the user specified a platform type. IntPtr pTLibAttr = IntPtr.Zero; TypeLib.GetLibAttr(out pTLibAttr); _TYPELIBATTR TLibAttr = (_TYPELIBATTR)Marshal.PtrToStructure(pTLibAttr, typeof(_TYPELIBATTR)); TypeLib.ReleaseTLibAttr(pTLibAttr); // Validate the machine options if (!ValidateMachineType(flags, TLibAttr.syskind)) return null; // Convert the typelib. ImporterCallback callback = new ImporterCallback(); tlbimp2.Process process = new Process(); AssemblyBuilder AsmBldr = process.DoProcess( TypeLib, strAssemblyFileName, flags, callback, publicKey, keyPair, strAssemblyNamespace, asmVersion, isVersion2, isPreserveSig, ruleSetFileName); if (AsmBldr == null) return null; // Remove this typelib from list of importing typelibs. s_ImportingLibraries.Remove(guid.ToString()); // Delete the output assembly. File.Delete(asmFileName); AsmBldr.DefineVersionInfoResource(strProduct, strProductVersion, strCompany, strCopyright, strTrademark); if (IsImportingToX64(flags)) { AsmBldr.Save(asmFileName, PortableExecutableKinds.ILOnly | PortableExecutableKinds.PE32Plus, ImageFileMachine.AMD64); } else if (IsImportingToItanium(flags)) { AsmBldr.Save(asmFileName, PortableExecutableKinds.ILOnly | PortableExecutableKinds.PE32Plus, ImageFileMachine.IA64); } else if (IsImportingToX86(flags)) { AsmBldr.Save(asmFileName, PortableExecutableKinds.ILOnly | PortableExecutableKinds.Required32Bit, ImageFileMachine.I386); } else { // Default is agnostic AsmBldr.Save(asmFileName); } return AsmBldr; }