private static void RegisterControllers(ContainerBuilder b, PluginAssembly assembly) { b.RegisterControllers(assembly.Assembly) .Named <IController>(t => t.Name.Replace("Controller", String.Empty)) .As(a => { var baseType = a.BaseType; while (baseType != null && baseType.Assembly != typeof(MvcApplication).Assembly) { baseType = baseType.BaseType; } return(baseType ?? a); }); }
/// <summary> /// Method to Update an Assembly Registration. /// </summary> /// <param name="xrmPluginAssembly">The Assembly to Update.</param> /// <returns>Result.</returns> internal bool UpdateAssembly(string xrmServerDetails, XrmPluginAssembly xrmPluginAssembly) { try { using (xrmService = RegistrationService.GetService(xrmServerDetails)) { PluginAssembly pluginAssembly = GetPluginAssembly(xrmPluginAssembly); xrmService.Update(pluginAssembly); } Result = true; return(Result); } catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { throw; } }
/// <summary> /// Method to retrieve the Assembly. /// </summary> /// <param name="xrmPluginAssembly">The Assembly to retrieve.</param> /// <returns>The retrieved Assembly.</returns> private PluginAssembly GetPluginAssembly(XrmPluginAssembly xrmPluginAssembly) { try { PluginAssembly = new PluginAssembly() { PluginAssemblyId = xrmPluginAssembly.AssemblyId, Name = xrmPluginAssembly.Name, SourceType = new OptionSetValue() { Value = (int)xrmPluginAssembly.SourceType }, IsolationMode = new OptionSetValue() { Value = (int)xrmPluginAssembly.IsolationMode }, Culture = xrmPluginAssembly.Culture, PublicKeyToken = xrmPluginAssembly.PublicKeyToken, Version = xrmPluginAssembly.Version, Description = xrmPluginAssembly.Description }; if (xrmPluginAssembly.SourceType == XrmAssemblySourceType.Database) { PluginAssembly.Content = Convert.ToBase64String(File.ReadAllBytes(xrmPluginAssembly.Path)); } switch (xrmPluginAssembly.SourceType) { case XrmAssemblySourceType.Disk: PluginAssembly.Path = xrmPluginAssembly.ServerFileName; break; case XrmAssemblySourceType.Database: break; case XrmAssemblySourceType.GAC: break; } ; return(PluginAssembly); } catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { throw; } }
public bool Load() { try { if (Enabled) { return(true); } PointBlankLogging.Log("Starting " + Name + "..."); Type _class = PluginAssembly.GetTypes().First(a => a.IsClass && typeof(PointBlankPlugin).IsAssignableFrom(a)); // Get the first plugin class PluginClass = Enviroment.runtimeObjects["Plugins"].AddCodeObject(_class) as PointBlankPlugin; // Instentate the plugin class Name = PluginClass.GetType().Name; // Change the name Version = PluginClass.Version; if (CheckUpdates()) { if (PluginConfiguration.NotifyUpdates) { Notify(); } if (PluginConfiguration.AutoUpdate) { Update(); } } LoadConfiguration(); // Load the configuration LoadTranslation(); // Load the translation PointBlankPluginEvents.RunPluginStart(PluginClass); // Run the start event PluginClass.Load(); // Run the load function PointBlankPluginEvents.RunPluginLoaded(PluginClass); // Run the loaded event Enabled = true; // Set the enabled to true t.Start(); // Start the thread return(true); } catch (Exception ex) { PointBlankLogging.LogError("Error starting plugin: " + Name, ex); Unload(); return(false); } }
public Guid RegisterAssembly(PluginAssembly pluginAssembly) { try { using (var orgService = (OrganizationServiceContext)_ServiceProvider.GetOrganisationService()) { var response = (CreateResponse)orgService.Execute(new CreateRequest() { Target = pluginAssembly }); return(response.id); } } catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { throw; } }
/// <summary> /// Create or update the PluginAssembly depending on the given pluginAssemblyEntity /// </summary> /// <param name="pluginAssembly">PluginAssembly or null</param> /// <returns></returns> private PluginAssembly UploadPluginAssemblyToDestination(PluginAssembly pluginAssembly) { if (AssemblyPlugin == null) { throw new InvalidOperationException("Load Assembly first"); } var dllContentBytes = File.ReadAllBytes(AssemblyPlugin.Location); var dllContent = Convert.ToBase64String(dllContentBytes); if (pluginAssembly == null) { return(CreatePluginAssembly(destinationSystem, AssemblyPlugin, dllContent)); } UpdatePluginAssembly(destinationSystem, pluginAssembly, dllContent); return(pluginAssembly); }
private static void UpdatePluginAssembly(IOrganizationService service, Guid pluginAssemblyId, string filePath) { var assemblyContentBytes = File.ReadAllBytes(filePath); var assemblyContent = Convert.ToBase64String(assemblyContentBytes); _logger.Log(LogLevel.Trace, () => "Created assembly content"); var pluginAssembly = new PluginAssembly { LogicalName = PluginAssembly.EntityLogicalName, Id = pluginAssemblyId, Content = assemblyContent }; service.Update(pluginAssembly); _logger.Log(LogLevel.Info, () => "Update was successful"); }
private async void btnNewPluginAssembly_Click(object sender, RoutedEventArgs e) { var service = await GetService(); if (service == null) { return; } var assembly = new PluginAssembly(); var form = new WindowPluginAssembly(_iWriteToOutput, service, assembly, null, null); if (form.ShowDialog().GetValueOrDefault()) { await ShowExistingPluginAssemblies(); } }
public static void UpdateAssembly(CrmOrganization org, string description, Guid assemblyId) { if (org == null) { throw new ArgumentNullException("org"); } else if (assemblyId == Guid.Empty) { throw new ArgumentNullException("assemblyId"); } // Work around as updating only description is failing with publickeytoken not null PluginAssembly pt1 = org.OrganizationService.Retrieve(PluginAssembly.EntityLogicalName, assemblyId, new ColumnSet(true)) as PluginAssembly; //PluginAssembly pt1 = new PluginAssembly(); pt1.Description = description; org.OrganizationService.Update(pt1); }
public PluginAssembly FindOrCreate(string assemblyfilename) { this.code = System.IO.File.ReadAllBytes(assemblyfilename); this.Assembly = System.Reflection.Assembly.Load(code); var publickeytoken = this.GetPublicKeyTokenFromAssembly(); var name = assemblyfilename.Split(new char[] { '\\', '/' }).Last(); if (name.ToUpper().EndsWith(".DLL")) { name = name.Substring(0, name.Length - 4); } var r = (from p in uow.PluginAssemblies.GetQuery() where p.Name == name select p).SingleOrDefault(); if (r != null) { this.pluginAssembly = r; this.isNew = false; return(r); } r = new PluginAssembly { PluginAssemblyId = Guid.NewGuid(), Content = System.Convert.ToBase64String(code), Description = name, IsolationMode = new Microsoft.Xrm.Sdk.OptionSetValue(2), Name = name, SourceType = new Microsoft.Xrm.Sdk.OptionSetValue(0), Culture = "neutral", PublicKeyToken = publickeytoken, Version = "1.0" }; uow.Create(r); this.messageService.Inform("Assembly code was created"); this.pluginAssembly = r; this.isNew = true; return(r); }
/// <summary> Retrieves all steps available in given assembly and selected type </summary> /// <param name="pluginAssembly"><see cref="PluginAssembly"/> for which steps should be /// retrieved</param> <param name="pluginType"<see cref="PluginType"/> for which steps /// should be retrieved</param> public void RetrieveSteps(PluginAssembly pluginAssembly, PluginType pluginType) { WorkAsync(new WorkAsyncInfo("Loading steps...", a => { a.Result = (pluginType != null) ? Service.GetSdkMessageProcessingSteps(pluginAssembly.Id, pluginType.Id) : Service.GetSdkMessageProcessingSteps(pluginAssembly.Id); }) { PostWorkCallBack = (a) => { PluginTypes = this.cbSourcePlugin.Items.Cast <PluginType>().ToArray(); ProcessingSteps = ((Entity[])a.Result).Select <Entity, ProcessingStep>(x => { return(new ProcessingStep(x, pluginAssembly, PluginTypes.Where(y => y.Id == ((EntityReference)x.Attributes[Constants.Crm.Attributes.PLUGIN_TYPE_ID]).Id).FirstOrDefault())); }).ToArray(); lvSteps.Items.Clear(); // var groups = new Dictionary<Guid, int>(); // If pluginType is null, so all available in current assembly types are selected //foreach (var type in this.PluginTypes) //{ // var item = new ListViewGroup // { // Header = type.FriendlyName, // }; // this.lvSteps.Groups.Add(item); groups.Add(type.Id, i++); //} foreach (var step in this.ProcessingSteps) { var item = new ListViewItem(new string[] { step.FriendlyName, step.StateCode.ToString() }); item.Tag = step; // item.Group = this.lvSteps.Groups[groups[step.ParentType.Id]]; this.lvSteps.Items.Add(item); } } }); }
public PluginAssemblyOptionsBuilder ForAssembly(Assembly assembly) { var assemblyName = assembly.GetName(); var pluginName = assemblyName.Name; string version = assemblyName.Version.ToString(); string publicKeyToken; byte[] publicKeyTokenBytes = assemblyName.GetPublicKeyToken(); if (null == publicKeyTokenBytes || 0 == publicKeyTokenBytes.Length) { publicKeyToken = null; } else { publicKeyToken = string.Join(string.Empty, publicKeyTokenBytes.Select(b => b.ToString("X2", CultureInfo.InvariantCulture))); } var pluginAssembly = new PluginAssembly() { PluginAssemblyId = Guid.NewGuid(), Name = pluginName, IsolationMode = new OptionSetValue() { Value = (int)IsolationMode.None }, Culture = "neutral", PublicKeyToken = publicKeyToken, Version = version }; //PluginAssembly = PluginAssembly; // var builder = new ComponentRegistrationBuilder(); var par = new PluginAssemblyRegistration() { Assembly = assembly, PluginAssembly = pluginAssembly, ComponentRegistration = this.ComponentRegistration }; this.ComponentRegistration.PluginAssemblyRegistrations.Add(par); return(new PluginAssemblyOptionsBuilder(this, par)); }
/// <summary> /// Create plugins / steps / images of an assembly from scratch /// Based on VS project /// </summary> /// <param name="parsedArgs"></param> /// <param name="destPluginAssembly"></param> public void CreateFromScratch(CmdArgs parsedArgs, PluginAssembly destPluginAssembly) { var uow = new CrmUnitOfWork(destinationSystem); // Delete destination assembly DeleteAllPluginTypeStepsOfAssembly(destPluginAssembly); // Create / Update assembly destPluginAssembly = UploadPluginAssemblyToDestination(destPluginAssembly); // Create NEW PluginTypes/Workflows CreateNewPluginTypesInDestination(destPluginAssembly); // Create Steps var file = new FileInfo(parsedArgs.AssemblyPath); var assemblyName = file.Name.Substring(0, file.Name.Length - 4); var plugin = (from pl in uow.PluginAssemblies.GetQuery() where pl.Name == assemblyName select pl).SingleOrDefault(); var steps = (from st in uow.SdkMessageProcessingSteps.GetQuery() join pt in uow.PluginTypes.GetQuery() on st.EventHandler.Id equals pt.PluginTypeId where pt.PluginAssemblyId.Id == plugin.PluginAssemblyId select st).ToArray().ToDictionary(s => s.UniqueName); var stepsToCreate = CreateStepsModel(assemblyName); CreateSteps(uow, plugin, steps, stepsToCreate); // Create Images var allImages = (from im in uow.SdkMessageProcessingStepImages.GetQuery() join st in uow.SdkMessageProcessingSteps.GetQuery() on im.SdkMessageProcessingStepId.Id equals st.SdkMessageProcessingStepId join pl in uow.PluginTypes.GetQuery() on st.EventHandler.Id equals pl.PluginTypeId where pl.PluginAssemblyId.Id == plugin.PluginAssemblyId select im).ToList(); CreateImages(uow, stepsToCreate, allImages, steps); logger.Log( $"Successfully created steps and images of Plugin '{AssemblyPlugin.GetName().Name}'"); }
public void Initialize(MailSettings mailSettings = null) { Scheduler = new StdSchedulerFactory(new NameValueCollection { ["quartz.scheduler.instanceName"] = SchedulerInstanceName, ["quartz.threadPool.type"] = SchedulerThreadPoolType, ["quartz.threadPool.threadCount"] = SchedulerThreadCount, ["quartz.threadPool.threadPriority"] = SchedulerThreadPriority }).GetScheduler(); Schedule.MailSettings = mailSettings; PluginAssembly.Load <IPlugin>().ForEach(x => { x.Plugins.ForEach(y => y.Schedule(Schedule)); }); Schedule.JobGroups.AsEnumerable().ToList().ForEach(x => { x.Value.Registrations.AsEnumerable().ToList().ForEach(y => { Scheduler.ScheduleJob(y.Value.JobDetail, y.Value.Trigger); }); }); }
protected override void ProcessRecord() { base.ProcessRecord(); base.WriteVerbose(string.Format("Updating Assembly: {0}", Path)); FileInfo assemblyInfo = new FileInfo(Path); String assemblyName = assemblyInfo.Name.Replace(".dll", ""); String version = FileVersionInfo.GetVersionInfo(Path).FileVersion; String content = Convert.ToBase64String(File.ReadAllBytes(Path)); base.WriteVerbose(string.Format("Assembly Name: {0}", assemblyName)); base.WriteVerbose(string.Format("Assembly Version: {0}", version)); using (var context = new CIContext(OrganizationService)) { var query = from a in context.PluginAssemblySet where a.Name == assemblyName select a.Id; Guid Id = query.FirstOrDefault(); if (Id == null || Id == Guid.Empty) { throw new ItemNotFoundException(string.Format("{0} was not found", assemblyName)); } PluginAssembly pluginAssembly = new PluginAssembly() { Id = Id, Version = version, Content = content }; OrganizationService.Update(pluginAssembly); } base.WriteVerbose(string.Format("Assembly Updated: {0}", Path)); }
private async Task ExecuteAction(PluginAssembly entity, Func<string, PluginDescription, PluginAssembly, Task> action) { string folder = txtBFolder.Text.Trim(); if (!this.IsControlsEnabled) { return; } if (string.IsNullOrEmpty(folder)) { _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportIsEmpty); folder = FileOperations.GetDefaultFolderForExportFilePath(); } else if (!Directory.Exists(folder)) { _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportDoesNotExistsFormat1, folder); folder = FileOperations.GetDefaultFolderForExportFilePath(); } await action(folder, this._pluginDescription, entity); }
public EntityReference Register(IOrganizationService client, PluginAssemblyInfo pluginAssemblyInfo = null) { if (pluginAssemblyInfo == null) { pluginAssemblyInfo = new PluginAssemblyInfo(this.Assembly); } var assemblyEntity = new PluginAssembly() { Name = this.Name, Culture = pluginAssemblyInfo.Culture, Version = pluginAssemblyInfo.Version, PublicKeyToken = pluginAssemblyInfo.PublicKeyToken, SourceType = PluginAssembly_SourceType.Database, // Only database supported for now IsolationMode = PluginAssembly_IsolationMode.Sandbox, // Only Sandbox supported for now Content = Convert.ToBase64String(_fileSystem.File.ReadAllBytes(this.Assembly)) }; var existingAssemblyQuery = this.GetExistingQuery(pluginAssemblyInfo.Version); return(assemblyEntity.CreateOrUpdate(client, existingAssemblyQuery)); }
private static bool MapPluginObject(List <Assembly> pluginAssemblyList , PluginAssembly pluginAssembly , PluginType pluginType , SdkMessageProcessingStep pluginStep , SdkMessage sdkMessage , SdkMessageFilter filter , List <SdkMessageProcessingStepImage> images) { var pluginAssemblyTemp = MapPluginAssemblyObject(pluginAssemblyList, pluginAssembly); if (pluginAssemblyTemp == null) { return(false); } var pluginAssemblyTypeTemp = MapPluginAssemblyTypeObject(pluginType, pluginAssemblyTemp); if (pluginStep != null) { MapPluginAssemblyStepObject(pluginType, pluginStep, sdkMessage, filter, images, pluginAssemblyTemp, pluginAssemblyTypeTemp); } return(true); }
public WindowPluginAssembly( IWriteToOutput iWriteToOutput , IOrganizationServiceExtented service , PluginAssembly pluginAssembly , string defaultOutputFilePath , EnvDTE.Project project ) { this.IncreaseInit(); InputLanguageManager.SetInputLanguage(this, CultureInfo.CreateSpecificCulture("en-US")); this._iWriteToOutput = iWriteToOutput; this._service = service; this._defaultOutputFilePath = defaultOutputFilePath; this._project = project; this.PluginAssembly = pluginAssembly; this._imagePluginAssembly = this.Resources["ImagePluginAssembly"] as BitmapImage; this._imagePluginType = this.Resources["ImagePluginType"] as BitmapImage; this._imageWorkflowActivity = this.Resources["ImageWorkflowActivity"] as BitmapImage; InitializeComponent(); LoadFromConfig(); this.trVPluginTreeNew.ItemsSource = _listLocalAssembly; this.trVPluginTreeMissing.ItemsSource = _listMissingCrm; this.tSSLblConnectionName.Content = _service.ConnectionData.Name; btnBuildProject.IsEnabled = this._project != null; btnBuildProject.Visibility = btnBuildProject.IsEnabled ? Visibility.Visible : Visibility.Hidden; LoadEntityPluginAssemblyProperties(); this.DecreaseInit(); }
public Guid UpsertPluginAssembly(Assembly pluginAssembly, AssemblyInfo assemblyInfo, string solutionName, RegistrationTypeEnum registrationType) { Guid Id = pluginAssembly?.Id ?? Guid.Empty; if (Id == Guid.Empty) { Id = pluginRepository.GetPluginAssemblyId(assemblyInfo.AssemblyName); logWarning?.Invoke($"Extracted id using plugin assembly name {assemblyInfo.AssemblyName}"); } var assembly = new PluginAssembly() { Version = assemblyInfo.Version, Content = assemblyInfo.Content, Name = assemblyInfo.AssemblyName, SourceTypeEnum = PluginAssembly_SourceType.Database, IsolationModeEnum = PluginAssembly_IsolationMode.Sandbox, }; if (pluginAssembly != null) { assembly.SourceTypeEnum = pluginAssembly.SourceType; assembly.IsolationModeEnum = pluginAssembly.IsolationMode; } if (!Id.Equals(Guid.Empty) && registrationType == RegistrationTypeEnum.Reset) { DeleteObjectWithDependencies(Id, ComponentType.PluginAssembly); } logVerbose?.Invoke($"Trying to upsert {assemblyInfo.AssemblyName} / {Id}"); Id = ExecuteRequest(registrationType, Id, assembly); AddComponentToSolution(Id, ComponentType.PluginAssembly, solutionName); return(Id); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //Prompt User for Plugin to load SelectPluginForm selectForm = new SelectPluginForm(); if (selectForm.ShowDialog() == DialogResult.Cancel) { return; } //Create the Framework Simulator PluginFactory.PluginRelativePath = ConfigurationManager.AppSettings["PluginRelativeLocation"]; PluginAssembly pluginAssembly = PluginFactory.GetPluginByAssemblyName(selectForm.PluginAssemblyName); InternalFrameworkSimulator simulator = new InternalFrameworkSimulator(ConfigurationManager.AppSettings["GlobalDatabase"], pluginAssembly); // Paperless mode simulator.PaperlessMode = JobMediaMode.Paperless; // Common environment values simulator.SessionId = ConfigurationManager.AppSettings["SessionId"]; simulator.UserName = ConfigurationManager.AppSettings["UserName"]; simulator.UserPassword = ConfigurationManager.AppSettings["UserPassword"]; simulator.UserDomain = ConfigurationManager.AppSettings["UserDomain"]; simulator.UserDnsDomain = ConfigurationManager.AppSettings["UserDnsDomain"]; simulator.FileRepository.DocumentShare = ConfigurationManager.AppSettings["DocumentShareLocation"]; // Less common values used by some plugins simulator.PluginSettings["sampleKey"] = "sampleValue"; simulator.EnvironmentConfiguration.OutputMonitorDestinations.Add("dss100"); simulator.EnvironmentConfiguration.ServerServices.Add("spooler"); simulator.SessionRuntime.OfficeWorkerEmailAddresses.Add("*****@*****.**"); Application.Run(new PluginFrameworkSimulatorForm(simulator)); }
/// <summary> /// Retrieves all types available in given assembly /// </summary> /// <param name="pluginAssembly"> /// <see cref="PluginAssembly"/> for which there types should be retrieved /// </param> public void RetrieveTypes(PluginAssembly pluginAssembly) { this.WorkAsync(new WorkAsyncInfo("Loading types...", a => { a.Result = this.Service.GetPluginTypes(pluginAssembly.Id); }) { PostWorkCallBack = (a) => { this.PluginTypes = ((Entity[])a.Result).Select(x => new PluginType(x, pluginAssembly)).ToArray(); this.cbSourcePlugin.Items.Clear(); this.cbSourcePlugin.Items.Add("All types"); foreach (var type in this.PluginTypes) { this.cbSourcePlugin.Items.Add(type); } // Select all types this.cbSourcePlugin.SelectedIndex = 0; } }); }
public Guid UpsertPluginAssembly(Assembly pluginAssembly, string pluginAssemblyName, string version, string content, string solutionName, bool isWorkflowActivity, string registrationType) { Guid Id = Guid.Empty; if (pluginAssembly == null || string.IsNullOrEmpty(pluginAssembly.Id) || !Guid.TryParse(pluginAssembly.Id, out Id)) { Id = GetPluginAssemblyId(pluginAssemblyName); xrmCommandBase.WriteWarning(string.Format("Extracted id using plugin assembly name {0}", pluginAssemblyName)); } var assembly = new PluginAssembly() { Version = version, Content = content, Name = pluginAssemblyName, SourceType = new OptionSetValue(0), IsolationMode = new OptionSetValue(2), }; if (pluginAssembly != null) { assembly.SourceType = new OptionSetValue((int)GetEnumValue <PluginAssembly_SourceType>(pluginAssembly.SourceType)); assembly.IsolationMode = new OptionSetValue((int)GetEnumValue <PluginAssembly_IsolationMode>(pluginAssembly.IsolationMode)); } if (!Id.Equals(Guid.Empty) && registrationType == "reset") { DeleteDependenciesAndParent(Id, PluginAssembly.EntityLogicalName, 91); } Id = ExecuteRequest(registrationType, Id, assembly); AddComponentToSolution(Id, 91, solutionName); return(Id); }
private PluginAssembly CreatePluginAssembly(IOrganizationService service, Assembly assembly, string content) { var bytes = assembly.GetName().GetPublicKeyToken(); var publicKeyToken = BitConverter.ToString(bytes).Replace("-", ""); var pluginAssembly = new PluginAssembly { LogicalName = PluginAssembly.EntityLogicalName, Content = content, Name = assembly.GetName().Name, Culture = assembly.GetName().CultureName, Version = assembly.GetName().Version.ToString(), PublicKeyToken = publicKeyToken, SourceType = new OptionSetValue((int)PluginAssembly.OptionSet.SourceType.Database), IsolationMode = new OptionSetValue((int)PluginAssembly.OptionSet.IsolationMode.None) }; var id = service.Create(pluginAssembly); logger.Log($"Successfully created PluginAssembly '{assembly.GetName().Name}' with id {id}"); pluginAssembly.Id = id; return(pluginAssembly); }
public static Guid RegisterAssembly(CrmOrganization org, string pathToAssembly, CrmPluginAssembly assembly) { if (org == null) { throw new ArgumentNullException("org"); } else if (assembly == null) { throw new ArgumentNullException("assembly"); } else if (assembly.SourceType == CrmAssemblySourceType.Database && pathToAssembly == null) { throw new ArgumentNullException("pathToAssembly", "Cannot be null when SourceType is Database"); } PluginAssembly ptl = (PluginAssembly)assembly.GenerateCrmEntities()[PluginAssembly.EntityLogicalName]; if (assembly.SourceType == CrmAssemblySourceType.Database) { ptl.Content = Convert.ToBase64String(File.ReadAllBytes(pathToAssembly)); } return(org.OrganizationService.Create(ptl)); }
private static PluginAssembly GetAssemblyToRegister(Assembly a, string assemblyPath) { var fullNameSplit = a.FullName.Split(','); var name = fullNameSplit[0]; var version = fullNameSplit[1].Substring(fullNameSplit[1].IndexOf('=') + 1); var culture = fullNameSplit[2].Substring(fullNameSplit[2].IndexOf('=') + 1); var publicKeyToken = fullNameSplit[3].Substring(fullNameSplit[3].IndexOf('=') + 1); var description = string.Format("{0} plugin assembly", name); var t = new PluginAssembly() { Name = name, SourceType = new OptionSetValue((int)pluginassembly_sourcetype.Database), IsolationMode = new OptionSetValue((int)pluginassembly_isolationmode.Sandbox), Culture = culture, PublicKeyToken = publicKeyToken, Version = version, Description = description, Content = Convert.ToBase64String(File.ReadAllBytes(assemblyPath)) }; return(t); }
public static List <PluginType> GetPluginTypes(this OrganizationServiceContext ctx, PluginAssembly plugin) { // Get existing types return((from t in ctx.CreateQuery <PluginType>() where t.PluginAssemblyId.Id == plugin.Id select new PluginType { Id = t.Id, Name = t.Name, PluginAssemblyId = t.PluginAssemblyId, TypeName = t.TypeName, FriendlyName = t.FriendlyName, Description = t.Description }).ToList()); }
private async Task PerformExportDescriptionToFile(string folder, PluginConfigurationAssemblyDescriptionHandler handler, PluginDescription pluginDescription, PluginAssembly assembly) { if (!this.IsControlsEnabled) { return; } ToggleControls(false, Properties.OutputStrings.CreatingDescription); string description = await handler.CreateDescriptionAsync(assembly); string filePath = await CreateDescriptionFileAsync(folder, pluginDescription.FilePath, assembly.Name, description); this._iWriteToOutput.PerformAction(null, filePath); ToggleControls(true, Properties.OutputStrings.CreatingDescriptionCompleted); }
private PluginAssembly RegisterAssembly(FileInfo assemblyFilePath, Assembly assembly, IEnumerable <Type> pluginTypes, bool isWorkflowActivity = false) { // Get the isolation mode of the first attribute var firstType = Reflection.GetAttributes(pluginTypes, typeof(CrmPluginRegistrationAttribute).Name).FirstOrDefault(); if (firstType == null) { return(null); } var firstTypeAttribute = firstType.CreateFromData() as CrmPluginRegistrationAttribute; // Is there any steps to register? if (firstTypeAttribute == null) { return(null); } var assemblyProperties = assembly.GetName().FullName.Split(",= ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); var assemblyName = assembly.GetName().Name; // If found then register or update it var plugin = (from p in _ctx.CreateQuery <PluginAssembly>() where p.Name == assemblyName select new PluginAssembly { Id = p.Id, Name = p.Name }).FirstOrDefault(); string assemblyBase64 = Convert.ToBase64String(File.ReadAllBytes(assemblyFilePath.FullName)); if (plugin == null) { plugin = new PluginAssembly(); } // update plugin.Content = assemblyBase64; plugin.Name = assemblyProperties[0]; plugin.Culture = assemblyProperties[4]; plugin.Version = assemblyProperties[2]; plugin.PublicKeyToken = assemblyProperties[6]; plugin.SourceType = pluginassembly_sourcetype.Database; // database plugin.IsolationMode = firstTypeAttribute.IsolationMode == IsolationModeEnum.Sandbox ? pluginassembly_isolationmode.Sandbox : pluginassembly_isolationmode.None; // 1= none, 2 = sandbox if (plugin.Id == Guid.Empty) { _trace.WriteLine("Registering Plugin '{0}' from '{1}'", plugin.Name, assemblyFilePath.FullName); // Create plugin.Id = _service.Create(plugin); } else { UnregisterRemovedPluginTypes(pluginTypes, plugin, isWorkflowActivity); _trace.WriteLine("Updating Plugin '{0}' from '{1}'", plugin.Name, assemblyFilePath.FullName); // Update _service.Update(plugin); } // Add to solution if (SolutionUniqueName != null) { _trace.WriteLine("Adding Plugin '{0}' to solution '{1}'", plugin.Name, SolutionUniqueName); AddAssemblyToSolution(SolutionUniqueName, plugin); } return(plugin); }
private void RegisterPluginSteps(IEnumerable <Type> pluginTypes, PluginAssembly plugin) { var sdkPluginTypes = ServiceLocator.Queries.GetPluginTypes(_ctx, plugin); foreach (var pluginType in pluginTypes) { // Search for the CrmPluginStepAttribute var pluginAttributes = pluginType.GetCustomAttributesData().Where(a => a.AttributeType.Name == typeof(CrmPluginRegistrationAttribute).Name); PluginType sdkPluginType = null; if (pluginAttributes.Count() > 0) { var pluginStepAttribute = pluginAttributes.First().CreateFromData() as CrmPluginRegistrationAttribute; // Check if the type is registered sdkPluginType = sdkPluginTypes.Where(t => t.TypeName == pluginType.FullName).FirstOrDefault(); if (sdkPluginType == null) { sdkPluginType = new PluginType(); } // Update values sdkPluginType.Name = pluginType.FullName; sdkPluginType.PluginAssemblyId = plugin.ToEntityReference(); sdkPluginType.TypeName = pluginType.FullName; sdkPluginType.FriendlyName = pluginType.FullName; if (sdkPluginType.Id == Guid.Empty) { _trace.WriteLine("Registering Type '{0}'", sdkPluginType.Name); // Create sdkPluginType.Id = _service.Create(sdkPluginType); } else { _trace.WriteLine("Updating Type '{0}'", sdkPluginType.Name); // Update _service.Update(sdkPluginType); } var existingSteps = GetExistingSteps(sdkPluginType); foreach (var pluginAttribute in pluginAttributes) { var attribute = pluginAttribute.CreateFromData(); if (attribute.Name == null && attribute.Message != null) { // Custom API registration RegisterCustomApi(sdkPluginType, existingSteps, attribute); } else { // Plugin Step registration RegisterStep(sdkPluginType, existingSteps, attribute); } } // Remove remaining Existing steps foreach (var step in existingSteps) { if (SupportedPluginStages.Contains(step.Stage ?? sdkmessageprocessingstep_stage.InitialPreoperation_Forinternaluseonly)) { _trace.WriteLine("Deleting step '{0}'", step.Name, step.Stage); _service.Delete(SdkMessageProcessingStep.EntityLogicalName, step.Id); } } } } }
/// <summary> /// Retrieves all types available in given assembly /// </summary> /// <param name="pluginAssembly"> /// <see cref="PluginAssembly"/> for which there types should be retrieved /// </param> public void RetrieveTypes(PluginAssembly pluginAssembly) { this.WorkAsync("Loading types...", a => { a.Result = this.Service.GetPluginTypes(pluginAssembly.Id); }, a => { this.PluginTypes = ((Entity[])a.Result).Select<Entity, PluginType>(x => new PluginType(x, pluginAssembly)).ToArray(); this.cbTypes.Items.Clear(); this.cbTypes.Items.Add("All types"); foreach (var type in this.PluginTypes) { this.cbTypes.Items.Add(type); } // Select all types this.cbTypes.SelectedIndex = 0; }); }
/// <summary> /// Called by the loader via <see cref="PluginAssembly"/>. /// </summary> internal PluginModule(PluginAssembly/*!*/ assembly) : base(assembly) { }
/// <summary> /// Fill drop-down list of assemblies in context menu /// </summary> /// <param name="selectedAssembly"></param> private void FillAssemblies(PluginAssembly selectedAssembly) { this.tscAssemblies.Items.Clear(); foreach (var assembly in this.PluginAsseblies.Where(x => x.Id != selectedAssembly.Id)) { this.tscAssemblies.Items.Add(assembly); } }
/// <summary> Retrieves all steps available in given assembly and selected type </summary> /// <param name="pluginAssembly"><see cref="PluginAssembly"/> for which steps should be /// retrieved</param> <param name="pluginType"<see cref="PluginType"/> for which steps /// should be retrieved</param> public void RetrieveSteps(PluginAssembly pluginAssembly, PluginType pluginType) { this.WorkAsync("Loading steps...", a => { a.Result = (pluginType != null) ? this.Service.GetSdkMessageProcessingSteps(pluginAssembly.Id, pluginType.Id) : this.Service.GetSdkMessageProcessingSteps(pluginAssembly.Id); }, a => { this.ProcessingSteps = ((Entity[])a.Result).Select<Entity, ProcessingStep>(x => { return new ProcessingStep(x, pluginAssembly, this.PluginTypes.Where(y => y.Id == ((EntityReference)x.Attributes[Constants.Crm.Attributes.PLUGIN_TYPE_ID]).Id).FirstOrDefault()); }).ToArray(); this.lvSteps.Items.Clear(); var groups = new Dictionary<Guid, int>(); // If pluginType is null, so all available in current assembly types are selected var i = 0; foreach (var type in this.PluginTypes) { var item = new ListViewGroup { Header = type.FriendlyName, }; this.lvSteps.Groups.Add(item); groups.Add(type.Id, i++); } foreach (var step in this.ProcessingSteps) { var item = new ListViewItem(new string[] { step.FriendlyName, step.StateCode.ToString() }); item.Tag = step; item.Group = this.lvSteps.Groups[groups[step.ParentType.Id]]; this.lvSteps.Items.Add(item); } }); }