예제 #1
0
        protected virtual PluginModel PreparePluginModel(PluginDescriptor pluginDescriptor,
            bool prepareLocales = true, bool prepareStores = true) {
            var pluginModel = pluginDescriptor.ToModel();
            //logo
            pluginModel.LogoUrl = pluginDescriptor.GetLogoUrl(_webHelper);

            if (prepareLocales) {
                //locales
                AddLocales(_languageService, pluginModel.Locales, (locale, languageId) => {
                    locale.FriendlyName = pluginDescriptor.Instance().GetLocalizedFriendlyName(_localizationService, languageId, false);
                });
            }
            if (prepareStores) {
                //stores
                pluginModel.AvailableStores = _storeService
                    .GetAllStores()
                    .Select(s => s.ToModel())
                    .ToList();
                pluginModel.SelectedStoreIds = pluginDescriptor.LimitedToStores.ToArray();
                pluginModel.LimitedToStores = pluginDescriptor.LimitedToStores.Count > 0;
            }


            //configuration URL

            return pluginModel;
        }
예제 #2
0
        public void BuildMenu(string parentMenu, PluginDescriptor pluginDescriptor)
        {
            if (pluginDescriptor.Installed) return;

            var parentResource = repository.Query<Resource>().FirstOrDefault(r => r.Name == parentMenu);

            Resource resource = new Resource()
            {
                ID = "__" + pluginDescriptor.SystemName,
                Name = pluginDescriptor.SystemName,
                Text = pluginDescriptor.FriendlyName,
                URL = pluginDescriptor.ConfigurationUrl,
                ShowToolBar = 0,
                Type = (short)ResourceType.Menu,
                ExpandIcon = "",
                ParentID = parentResource.ID,
                OpenMode = 1,
                ShowNavigation = 0,
                SortOrder = 1,
                CreateTime = DateTime.Now,
                Creator = "AgileEAP",
                Operates = new List<Operate>
                {
                    new Operate { ID="_newForm_", OperateName="新增", CommandName="newForm", Runat=(short)Runat.Ajax,SortOrder=1 },
                    new Operate { ID="_deleteForm_", OperateName="删除", CommandName="deleteForm", Runat=(short)Runat.Ajax,SortOrder=2 },
                    new Operate { ID="_designForm_", OperateName="修改", CommandName="designForm", Runat=(short)Runat.Ajax,SortOrder=3 }
                }
            };
            IAuthorizeService authService = new AuthorizeService();
            authService.SaveResource(resource);
        }
예제 #3
0
        public IGeneratorPlugin LoadPlugin(PluginDescriptor pluginDescriptor)
        {
            var generatorPluginAssemblyPath = GetGeneratorPluginAssemblies(pluginDescriptor).FirstOrDefault();
            if (generatorPluginAssemblyPath == null)
                throw new SpecFlowException(string.Format("Unable to find plugin in the plugin search path: {0}. Please check http://go.specflow.org/doc-plugins for details.", pluginDescriptor.Name));

            Assembly pluginAssembly;
            try
            {
                pluginAssembly = Assembly.LoadFrom(generatorPluginAssemblyPath);
            }
            catch(Exception ex)
            {
                throw new SpecFlowException(string.Format("Unable to load plugin assembly: {0}. Please check http://go.specflow.org/doc-plugins for details.", generatorPluginAssemblyPath), ex);
            }

            var pluginAttribute = (GeneratorPluginAttribute)Attribute.GetCustomAttribute(pluginAssembly, typeof(GeneratorPluginAttribute));
            if (pluginAttribute == null)
                throw new SpecFlowException("Missing [assembly:GeneratorPlugin] attribute in " + generatorPluginAssemblyPath);

            if (!typeof(IGeneratorPlugin).IsAssignableFrom((pluginAttribute.PluginType)))
                throw new SpecFlowException(string.Format("Invalid plugin attribute in {0}. Plugin type must implement IGeneratorPlugin. Please check http://go.specflow.org/doc-plugins for details.", generatorPluginAssemblyPath));

            IGeneratorPlugin plugin;
            try
            {
                plugin = (IGeneratorPlugin)Activator.CreateInstance(pluginAttribute.PluginType);
            }
            catch (Exception ex)
            {
                throw new SpecFlowException(string.Format("Invalid plugin in {0}. Plugin must have a default constructor that does not throw exception. Please check http://go.specflow.org/doc-plugins for details.", generatorPluginAssemblyPath), ex);
            }

            return plugin;
        }
        public void RaisePluginRemoved(PluginDescriptor descriptor)
        {
            if (this.pluginRemoved == null)
            return;

              this.pluginRemoved(this, new PluginEventArgs(descriptor));
        }
 public void ConstructionDefault()
 {
     PluginDescriptor tested = new PluginDescriptor();
       Assert.IsNotNull(tested.Interfaces);
       Assert.IsNotNull(tested.Derives);
       Assert.IsNotNull(tested.InfoValues);
       Assert.IsNotNull(tested.Settings);
 }
 private static void LoadPlugin(PluginDescriptor pluginDescriptor, IGeneratorPluginLoader pluginLoader, GeneratorPluginEvents generatorPluginEvents)
 {
     var plugin = pluginLoader.LoadPlugin(pluginDescriptor);
     var generatorPluginParameters = new GeneratorPluginParameters
     {
         Parameters = pluginDescriptor.Parameters
     };
     plugin.Initialize(generatorPluginEvents, generatorPluginParameters);
 }
        public void NotEqualToNull()
        {
            PluginDescriptor tested = new PluginDescriptor()
              {
            QualifiedName = typeof(string)
              };

              Assert.IsFalse(tested.Equals(null));
        }
        public void NotEqualIfComparedToOtherType()
        {
            PluginDescriptor tested = new PluginDescriptor()
              {
            QualifiedName = typeof(string)
              };

              object other = "object";

              Assert.IsFalse(tested.Equals(other));
        }
예제 #9
0
        public void DeleteMenu(PluginDescriptor pluginDescriptor)
        {
            if (!pluginDescriptor.Installed) return;

            Resource resource = repository.GetDomain<Resource>("__" + pluginDescriptor.SystemName);
            if (resource != null)
            {
                IAuthorizeService authService = new AuthorizeService();
                authService.DeleteResource(resource);
            }
        }
예제 #10
0
        /// <summary>
        /// Changes the plugin to use for the destination.
        /// </summary>
        /// <param name="descriptor">A descriptor for the plugin.</param>
        public void ChangePlugin(PluginDescriptor descriptor)
        {
            if (descriptor == null) throw new ArgumentNullException();

            if(descriptor.PluginTypeFullName == _pluginsettings.Type)
                return;

            // Unload old plugin and create empty settings for the new one
            PluginManager.UnloadPluginForDestination(this);
            _pluginsettings = new PluginSettings(descriptor);
        }
예제 #11
0
        public static PluginDescriptor ParsePluginDescriptionFile(string filePath)
        {
            var descriptor = new PluginDescriptor();

            var text = File.ReadAllText(filePath);
            if (String.IsNullOrEmpty(text))
                return descriptor;

            descriptor = JsonConvert.DeserializeObject<PluginDescriptor>(text);

            return descriptor;
        }
		public FileInfo CreatePluginPackage(PluginDescriptor descriptor)
		{
			var result = new PackagingResult
			{
				ExtensionType = "Plugin",
				PackageName = descriptor.FolderName,
				PackageVersion = descriptor.Version.ToString(),
				PackageStream = _packageBuilder.BuildPackage(descriptor)
			};

			return SavePackageFile(result);
		}
예제 #13
0
        public static void SavePluginDescriptionFile(PluginDescriptor plugin)
        {
            if (plugin == null)
                throw new ArgumentException("plugin");

            //get the Description.txt file path
            if (plugin.OriginalAssemblyFile == null)
                throw new Exception(string.Format("Cannot load original assembly path for {0} plugin.", plugin.SystemName));
            var filePath = Path.Combine(plugin.OriginalAssemblyFile.Directory.FullName, PluginManager.ManifestJson);
            if (!File.Exists(filePath))
                throw new Exception(string.Format("Description file for {0} plugin does not exist. {1}", plugin.SystemName, filePath));

            string pluginJson = JsonConvert.SerializeObject(plugin);

            //save the file
            File.WriteAllText(filePath, pluginJson);
        }
        public void EqualOnlyIfSameQualifiedName()
        {
            PluginDescriptor tested = new PluginDescriptor()
              {
            QualifiedName = typeof(string)
              };

              PluginDescriptor sameName = new PluginDescriptor()
              {
            QualifiedName = typeof(string)
              };

              PluginDescriptor otherName = new PluginDescriptor()
              {
            QualifiedName = typeof(int)
              };

              Assert.IsTrue(tested.Equals(sameName));
              Assert.IsFalse(tested.Equals(otherName));
        }
        public void ForgetLostPlugins()
        {
            PluginRepository tested = new PluginRepository();
              MockPluginSource pluginSource = new MockPluginSource();
              tested.AddPluginSource(pluginSource);

              PluginDescriptor thePlugin = new PluginDescriptor()
              {
            QualifiedName = typeof(UnitTest_PluginRepository)
              };

              pluginSource.RaisePluginAdded(thePlugin);

              var pluginsBefore = tested.Plugins(null).ToArray();
              pluginSource.RaisePluginRemoved(thePlugin);
              var pluginsAfter = tested.Plugins(null).ToArray();

              Assert.IsTrue(pluginsAfter.Length - pluginsBefore.Length == -1);
              Assert.IsFalse(pluginsAfter.Contains(thePlugin));
        }
        public IEnumerable<PluginDescriptor> Plugins(PluginFilter filter)
        {
            this.log.DebugFormat("Finding plugins statisfying {0}", filter);

              FindPlugin cmd = new FindPlugin() { Filter = filter };
              PluginDescriptor[] foundPlugins = new PluginDescriptor[0];
              this.bus.PublishRequest(cmd, cb =>
              {
            // cb.SetRequestExpiration(TimeSpan.FromSeconds(10)); <--- Bug that causes exception on RabbitMq (fixed in trunk but not on NuGet)
            cb.HandleTimeout(TimeSpan.FromSeconds(10), msg =>
            {
              this.log.WarnFormat("Timeout requesting {0}", filter);
            });

            cb.Handle<FindPluginResponse>((context, message) =>
            {
              foundPlugins = message.FoundPlugins;
              this.log.DebugFormat("Found {0} plugins for {1}", foundPlugins.Length, filter);
            });
              });
              return foundPlugins;
        }
예제 #17
0
        public IPlugin LoadPlugin( PluginDescriptor descriptor ) {
            string descriptorPath = Path.GetDirectoryName( descriptor.PluginDescriptorFileName );
            string fileName = Path.GetFullPath( Path.Combine( descriptorPath, descriptor.PluginFileName ) );

            ScriptSource script = ironPythonEngine.CreateScriptSourceFromFile( fileName );
            CompiledCode code = script.Compile();
            ScriptScope scope = ironPythonEngine.CreateScope();
            code.Execute( scope );

            IEnumerable<dynamic> typeList = scope.GetItems().Select( kvp => kvp.Value ).Where( item => item is PythonType );
            dynamic pluginType = typeList.FirstOrDefault( item => item.Name.Equals( descriptor ) );
            if( pluginType != null ) {
                if( PythonOps.IsSubClass( pluginType, DynamicHelpers.GetPythonTypeFromType( typeof( IPlugin ) ) ) ) {
                    IPlugin plugin = pluginType();
                    return plugin;
                } else {
                    throw new Exception( "Specified type does not implement IPlugin." );
                }
            } else {
                throw new Exception( "Specified type not found." );
            }
        }
예제 #18
0
        protected virtual PluginModel PreparePluginModel(PluginDescriptor pluginDescriptor,
                                                         bool prepareLocales = true)
        {
            var pluginModel = pluginDescriptor.ToModel();

            //logo
            pluginModel.LogoUrl = pluginDescriptor.GetLogoUrl(_webHelper);

            //if (prepareLocales)
            //{
            //    //locales
            //    AddLocales(_languageService, pluginModel.Locales, (locale, languageId) =>
            //    {
            //        locale.FriendlyName = pluginDescriptor.Instance().GetLocalizedFriendlyName(_localizationService, languageId, false);
            //    });
            //}


            //if (prepareStores)
            //{
            //    //stores
            //    pluginModel.AvailableStores = _storeService
            //        .GetAllStores()
            //        .Select(s => s.ToModel())
            //        .ToList();
            //    pluginModel.SelectedStoreIds = pluginDescriptor.LimitedToStores.ToArray();
            //    pluginModel.LimitedToStores = pluginDescriptor.LimitedToStores.Count > 0;
            //}


            //configuration URLs

            if (pluginDescriptor.IsEnabled)
            {
                //specify configuration URL only when a plugin is already installed

                //plugins do not provide a general URL for configuration
                //because some of them have some custom URLs for configuration
                //for example, discount requirement plugins require additional parameters and attached to a certain discount
                var    pluginInstance   = pluginDescriptor.Instance();
                string configurationUrl = null;
                //if (pluginInstance is IPaymentMethod)
                //{
                //    //payment plugin
                //    configurationUrl = Url.Action("ConfigureMethod", "Payment", new { systemName = pluginDescriptor.SystemName });
                //}
                //else if (pluginInstance is IShippingRateComputationMethod)
                //{
                //    //shipping rate computation method
                //    configurationUrl = Url.Action("ConfigureProvider", "Shipping", new { systemName = pluginDescriptor.SystemName });
                //}
                //else if (pluginInstance is ITaxProvider)
                //{
                //    //tax provider
                //    configurationUrl = Url.Action("ConfigureProvider", "Tax", new { systemName = pluginDescriptor.SystemName });
                //}
                //else if (pluginInstance is IExternalAuthenticationMethod)
                //{
                //    //external auth method
                //    configurationUrl = Url.Action("ConfigureMethod", "ExternalAuthentication", new { systemName = pluginDescriptor.SystemName });
                //}
                //else if (pluginInstance is IWidgetPlugin)
                //{
                //    //Misc plugins
                //    configurationUrl = Url.Action("ConfigureWidget", "Widget", new { systemName = pluginDescriptor.SystemName });
                //}
                //else if (pluginInstance is IMiscPlugin)
                //{
                //    //Misc plugins
                //    configurationUrl = Url.Action("ConfigureMiscPlugin", "Plugin", new { systemName = pluginDescriptor.SystemName });
                //}
                pluginModel.ConfigurationUrl = configurationUrl;



                ////enabled/disabled (only for some plugin types)
                //if (pluginInstance is IPaymentMethod)
                //{
                //    //payment plugin
                //    pluginModel.CanChangeEnabled = true;
                //    pluginModel.IsEnabled = ((IPaymentMethod)pluginInstance).IsPaymentMethodActive(_paymentSettings);
                //}
                //else if (pluginInstance is IShippingRateComputationMethod)
                //{
                //    //shipping rate computation method
                //    pluginModel.CanChangeEnabled = true;
                //    pluginModel.IsEnabled = ((IShippingRateComputationMethod)pluginInstance).IsShippingRateComputationMethodActive(_shippingSettings);
                //}
                //else if (pluginInstance is ITaxProvider)
                //{
                //    //tax provider
                //    pluginModel.CanChangeEnabled = true;
                //    pluginModel.IsEnabled = pluginDescriptor.SystemName.Equals(_taxSettings.ActiveTaxProviderSystemName, StringComparison.InvariantCultureIgnoreCase);
                //}
                //else if (pluginInstance is IExternalAuthenticationMethod)
                //{
                //    //external auth method
                //    pluginModel.CanChangeEnabled = true;
                //    pluginModel.IsEnabled = ((IExternalAuthenticationMethod)pluginInstance).IsMethodActive(_externalAuthenticationSettings);
                //}
                //else if (pluginInstance is IWidgetPlugin)
                //{
                //    //Misc plugins
                //    pluginModel.CanChangeEnabled = true;
                //    pluginModel.IsEnabled = ((IWidgetPlugin)pluginInstance).IsWidgetActive(_widgetSettings);
                //}
            }
            return(pluginModel);
        }
 public static PluginEntry ToEntry(this PluginDescriptor pluginDescriptor) => new(pluginDescriptor);
예제 #20
0
        protected virtual PluginModel PreparePluginModel(PluginDescriptor pluginDescriptor, 
            bool prepareLocales = true, bool prepareStores = true)
        {
            var pluginModel = pluginDescriptor.ToModel();
            //logo
            pluginModel.LogoUrl = pluginDescriptor.GetLogoUrl(_webHelper);

            if (prepareLocales)
            {
                //locales
                AddLocales(_languageService, pluginModel.Locales, (locale, languageId) =>
                {
                    locale.FriendlyName = pluginDescriptor.Instance().GetLocalizedFriendlyName(_localizationService, languageId, false);
                });
            }
            if (prepareStores)
            {
                //stores
                pluginModel.SelectedStoreIds = pluginDescriptor.LimitedToStores.ToList();
                var allStores = _storeService.GetAllStores();
                foreach (var store in allStores)
                {
                    pluginModel.AvailableStores.Add(new SelectListItem
                    {
                        Text = store.Name,
                        Value = store.Id.ToString(),
                        Selected = pluginModel.SelectedStoreIds.Contains(store.Id)
                    });
                }
            }


            //configuration URLs
            if (pluginDescriptor.Installed)
            {
                //specify configuration URL only when a plugin is already installed

                //plugins do not provide a general URL for configuration
                //because some of them have some custom URLs for configuration
                //for example, discount requirement plugins require additional parameters and attached to a certain discount
                var pluginInstance = pluginDescriptor.Instance();
                string configurationUrl = null;
                if (pluginInstance is IPaymentMethod)
                {
                    //payment plugin
                    configurationUrl = Url.Action("ConfigureMethod", "Payment", new { systemName = pluginDescriptor.SystemName });
                }
                else if (pluginInstance is IShippingRateComputationMethod)
                {
                    //shipping rate computation method
                    configurationUrl = Url.Action("ConfigureProvider", "Shipping", new { systemName = pluginDescriptor.SystemName });
                }
                else if (pluginInstance is IPickupPointProvider)
                {
                    //pickup point provider
                    configurationUrl = Url.Action("ConfigurePickupPointProvider", "Shipping", new { systemName = pluginDescriptor.SystemName });
                }
                else if (pluginInstance is ITaxProvider)
                {
                    //tax provider
                    configurationUrl = Url.Action("ConfigureProvider", "Tax", new { systemName = pluginDescriptor.SystemName });
                }
                else if (pluginInstance is IExternalAuthenticationMethod)
                {
                    //external auth method
                    configurationUrl = Url.Action("ConfigureMethod", "ExternalAuthentication", new { systemName = pluginDescriptor.SystemName });
                }
                else if (pluginInstance is IWidgetPlugin)
                {
                    //Misc plugins
                    configurationUrl = Url.Action("ConfigureWidget", "Widget", new { systemName = pluginDescriptor.SystemName });
                }
                else if (pluginInstance is IMiscPlugin)
                {
                    //Misc plugins
                    configurationUrl = Url.Action("ConfigureMiscPlugin", "Plugin", new { systemName = pluginDescriptor.SystemName });
                }
                pluginModel.ConfigurationUrl = configurationUrl;




                //enabled/disabled (only for some plugin types)
                if (pluginInstance is IPaymentMethod)
                {
                    //payment plugin
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled = ((IPaymentMethod)pluginInstance).IsPaymentMethodActive(_paymentSettings);
                }
                else if (pluginInstance is IShippingRateComputationMethod)
                {
                    //shipping rate computation method
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled = ((IShippingRateComputationMethod)pluginInstance).IsShippingRateComputationMethodActive(_shippingSettings);
                }
                else if (pluginInstance is IPickupPointProvider)
                {
                    //pickup point provider
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled = ((IPickupPointProvider)pluginInstance).IsPickupPointProviderActive(_shippingSettings);
                }
                else if (pluginInstance is ITaxProvider)
                {
                    //tax provider
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled = pluginDescriptor.SystemName.Equals(_taxSettings.ActiveTaxProviderSystemName, StringComparison.InvariantCultureIgnoreCase);
                }
                else if (pluginInstance is IExternalAuthenticationMethod)
                {
                    //external auth method
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled = ((IExternalAuthenticationMethod)pluginInstance).IsMethodActive(_externalAuthenticationSettings);
                }
                else if (pluginInstance is IWidgetPlugin)
                {
                    //Misc plugins
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled = ((IWidgetPlugin)pluginInstance).IsWidgetActive(_widgetSettings);
                }

            }
            return pluginModel;
        }
예제 #21
0
        /// <summary>
        /// 上传plugin zip文件
        /// </summary>
        /// <returns></returns>
        public ActionResult PostFile(string systemName)
        {
            string strErrorMsg = "";
            string strName     = "";

            try
            {
                string strPath = "";
                if (Request.Files.Count > 0)
                {
                    if (!System.IO.Directory.Exists(string.Format("{0}\\BackUp", Server.MapPath("~/"))))
                    {
                        System.IO.Directory.CreateDirectory(string.Format("{0}\\BackUp", Server.MapPath("~/")));
                    }

                    HttpPostedFileBase objFile = Request.Files[0];
                    var pad = DateTime.Now.ToString("yyyyMMddHHmmss");
                    strPath = string.Format("{0}\\{1}{2}", Server.MapPath("~/pluginsTemp"),
                                            pad, System.IO.Path.GetExtension(objFile.FileName));
                    //  dic.Add(objFile.FileName, objFile.InputStream);
                    objFile.SaveAs(strPath);


                    //System.IO.MemoryStream stream = new System.IO.MemoryStream(objZip.ZipContent);
                    SharpZip.UnpackFiles(strPath, string.Format("{0}\\{1}\\", Server.MapPath("~/pluginsTemp"), pad));

                    var strPathTemp = strPath.Replace(System.IO.Path.GetExtension(objFile.FileName), "\\");

                    var bolCheck = CheckModule(objFile.FileName, strPathTemp);
                    PluginDescriptor plugTemp = null;
                    if (bolCheck)
                    {
                        plugTemp = PluginFileParser.ParsePluginDescriptionFile(strPathTemp + "\\Description.txt");
                        if (!string.IsNullOrEmpty(systemName) && systemName != "0" && plugTemp.SystemName != systemName)
                        {
                            throw new Exception("System Name不对,插件不兼容!");
                        }
                        if (!string.IsNullOrEmpty(systemName) && systemName != "0")  //编辑时先删除以前的
                        {
                            var plugTemp1 = ((List <PluginDescriptor>)PluginManager.AllPlugins)
                                            .Find(a => a.SystemName == plugTemp.SystemName);

                            // 如果前后名字对不上,不能装啊
                            if (plugTemp1 == null)

                            {
                                // 对不上了,看systemName,如果空的话就是添加,否则不让操作
                                if (!string.IsNullOrEmpty(systemName))
                                {
                                    throw new Exception("System Name不对,插件不兼容!");
                                }
                            }
                        }
                        else
                        {
                            //是否存在相同的
                            // plugTemp = PluginManager.GetPluginDescriptor(new DirectoryInfo(System.IO.Path.GetDirectoryName(strPath)));
                            if (((List <PluginDescriptor>)PluginManager.AllPlugins)
                                .Exists(a => a.PluginFileName == plugTemp.PluginFileName))
                            {
                                strErrorMsg = "the Module has existed!";
                                bolCheck    = false;
                            }
                            else
                            {
                            }
                        }

                        var pluginsVersions = plugTemp.Version.Split('.');
                        if (pluginsVersions.Length < 4)
                        {
                            strErrorMsg = "the Module's Version format is error! Correct is '40.1.20160911.01'";
                            bolCheck    = false;
                        }
                    }
                    else
                    {
                        System.IO.Directory.Delete(strPathTemp, true);
                        strErrorMsg = "Zip File is not a Module!";
                    }


                    if (bolCheck)
                    {
                        string strPathTo = string.Format("{0}Plugins\\{1}", Server.MapPath("~/"), plugTemp.SystemName);

                        var plug = plugTemp;
                        if (!Directory.Exists(strPathTo))
                        {
                            Directory.CreateDirectory(strPathTo);
                            System.IO.File.Copy(strPathTemp + "\\Description.txt", strPathTo + "\\Description.txt");
                        }
                        plug.InstallFrom   = pad;
                        plug.NeedInstalled = false;
                        plug.Installed     = false;
                        plug.PluginPath    = strPathTo;

                        PluginFileParser.SavePluginDescriptionFile(plug);
                        PluginManager.SavePlugins(plug);
                    }
                }

                strName = System.IO.Path.GetFileName(strPath);
            }
            catch (Exception ex)
            {
                strErrorMsg = "Server Error:" + ex.Message;
            }

            if (strErrorMsg != "")
            {
                return(Json(new UploadMessageError("1", strErrorMsg, Request["id"]), JsonRequestBehavior.AllowGet));
            }
            else
            {
                return(Json(new UploadMessageSuccess(new UploadMessageSuccessMsg(strName, "/pluginsTemp/" + strName), Request["id"]), JsonRequestBehavior.AllowGet));
            }
        }
        protected PluginModel PreparePluginModel(PluginDescriptor pluginDescriptor, bool forList = true)
        {
            var pluginModel = pluginDescriptor.ToModel();

            pluginModel.Group = _localizationService.GetResource("Plugins.KnownGroup." + pluginDescriptor.Group);

			if (forList)
			{
				pluginModel.FriendlyName = pluginDescriptor.GetLocalizedValue(_localizationService, "FriendlyName");
				pluginModel.Description = pluginDescriptor.GetLocalizedValue(_localizationService, "Description");
			}

            //locales
            AddLocales(_languageService, pluginModel.Locales, (locale, languageId) =>
            {
				locale.FriendlyName = pluginDescriptor.GetLocalizedValue(_localizationService, "FriendlyName", languageId, false);
				locale.Description = pluginDescriptor.GetLocalizedValue(_localizationService, "Description", languageId, false);
            });
			//stores
			pluginModel.AvailableStores = _storeService
				.GetAllStores()
				.Select(s => s.ToModel())
				.ToList();
			pluginModel.SelectedStoreIds = _settingService.GetSettingByKey<string>(pluginDescriptor.GetSettingKey("LimitedToStores")).ToIntArray();
			pluginModel.LimitedToStores = pluginModel.SelectedStoreIds.Count() > 0;

            // codehint: sm-add
            if (System.IO.File.Exists(Path.Combine(pluginDescriptor.PhysicalPath, "icon.png")))
            {
                pluginModel.IconUrl = "~/Plugins/{0}/icon.png".FormatInvariant(pluginDescriptor.SystemName);
            }
            else
            {
                pluginModel.IconUrl = GetDefaultPluginUrl(pluginDescriptor);
            }
            
            if (pluginDescriptor.Installed)
            {
                //specify configuration URL only when a plugin is already installed

                //plugins do not provide a general URL for configuration
                //because some of them have some custom URLs for configuration
                //for example, discount requirement plugins require additional parameters and attached to a certain discount
                var pluginInstance = pluginDescriptor.Instance();
                string configurationUrl = null;
                bool canChangeEnabled = false;
                bool isEnabled = false;

                if (pluginInstance is IPaymentMethod)
                {
                    //payment plugin
                    configurationUrl = Url.Action("ConfigureMethod", "Payment", new { systemName = pluginDescriptor.SystemName });
                    canChangeEnabled = true;
                    isEnabled = ((IPaymentMethod)pluginInstance).IsPaymentMethodActive(_paymentSettings);
                }
                else if (pluginInstance is IShippingRateComputationMethod)
                {
                    //shipping rate computation method
                    configurationUrl = Url.Action("ConfigureProvider", "Shipping", new { systemName = pluginDescriptor.SystemName });
                    canChangeEnabled = true;
                    isEnabled = ((IShippingRateComputationMethod)pluginInstance).IsShippingRateComputationMethodActive(_shippingSettings);
                }
                else if (pluginInstance is ITaxProvider)
                {
                    //tax provider
                    configurationUrl = Url.Action("ConfigureProvider", "Tax", new { systemName = pluginDescriptor.SystemName });
                    canChangeEnabled = true;
                    isEnabled = pluginDescriptor.SystemName.Equals(_taxSettings.ActiveTaxProviderSystemName, StringComparison.InvariantCultureIgnoreCase);
                }
                else if (pluginInstance is IExternalAuthenticationMethod)
                {
                    //external auth method
                    configurationUrl = Url.Action("ConfigureMethod", "ExternalAuthentication", new { systemName = pluginDescriptor.SystemName });
                    canChangeEnabled = true;
                    isEnabled = ((IExternalAuthenticationMethod)pluginInstance).IsMethodActive(_externalAuthenticationSettings);
                }
                else if (pluginInstance is IWidgetPlugin)
                {
                    // Widgets plugins
                    configurationUrl = Url.Action("ConfigureWidget", "Widget", new { systemName = pluginDescriptor.SystemName });
                    canChangeEnabled = true;
                    isEnabled = ((IWidgetPlugin)pluginInstance).IsWidgetActive(_widgetSettings);
                }
                else if (pluginInstance is IMiscPlugin)
                {
                    //Misc plugins
                    configurationUrl = Url.Action("ConfigureMiscPlugin", "Plugin", new { systemName = pluginDescriptor.SystemName });
                }
                pluginModel.ConfigurationUrl = configurationUrl;
                pluginModel.CanChangeEnabled = canChangeEnabled;
                pluginModel.IsEnabled = isEnabled;

            }
            return pluginModel;
        }
예제 #23
0
        private IEnumerable<string> GetGeneratorPluginAssemblies(PluginDescriptor pluginDescriptor)
        {
            foreach (var pluginGeneratorFolder in GetPluginGeneratorFolders(pluginDescriptor))
            {
                string generatorSpecificAssembly = Path.GetFullPath(Path.Combine(pluginGeneratorFolder, string.Format("{0}.Generator.SpecFlowPlugin.dll", pluginDescriptor.Name)));
                if (File.Exists(generatorSpecificAssembly))
                    yield return generatorSpecificAssembly;

                string genericAssembly = Path.GetFullPath(Path.Combine(pluginGeneratorFolder, string.Format("{0}.SpecFlowPlugin.dll", pluginDescriptor.Name)));
                if (File.Exists(genericAssembly))
                    yield return genericAssembly;
            }
        }
예제 #24
0
        private IEnumerable<string> GetPluginFolders(PluginDescriptor pluginDescriptor)
        {
            if (pluginDescriptor.Path != null)
            {
                yield return Path.Combine(projectSettings.ProjectFolder, pluginDescriptor.Path);
                yield break;
            }

            yield return generatorFolder;

            foreach (var nuGetPluginFolder in GetNuGetPluginFolders(pluginDescriptor))
                yield return nuGetPluginFolder;
        }
예제 #25
0
        public static PluginDescriptor ParsePluginDescriptionFile(string filePath)
        {
            var descriptor = new PluginDescriptor();
            var text = File.ReadAllText(filePath);
            if (String.IsNullOrEmpty(text))
                return descriptor;

            var settings = new List<string>();
            using (var reader = new StringReader(text))
            {
                string str;
                while ((str = reader.ReadLine()) != null)
                {
                    if (String.IsNullOrWhiteSpace(str))
                        continue;
                    settings.Add(str.Trim());
                }
            }

            //Old way of file reading. This leads to unexpected behavior when a user's FTP program transfers these files as ASCII (\r\n becomes \n).
            //var settings = text.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var setting in settings)
            {
                var separatorIndex = setting.IndexOf(':');
                if (separatorIndex == -1)
                {
                    continue;
                }
                string key = setting.Substring(0, separatorIndex).Trim();
                string value = setting.Substring(separatorIndex + 1).Trim();

                switch (key)
                {
                    case "Group":
                        descriptor.Group = value;
                        break;
                    case "FriendlyName":
                        descriptor.FriendlyName = value;
                        break;
                    case "SystemName":
                        descriptor.SystemName = value;
                        break;
                    case "Version":
                        descriptor.Version = value;
                        break;
                    case "SupportedVersions":
                        {
                            //parse supported versions
                            descriptor.SupportedVersions = value.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                .Select(x => x.Trim())
                                .ToList();
                        }
                        break;
                    case "Author":
                        descriptor.Author = value;
                        break;
                    case "DisplayOrder":
                        {
                            int displayOrder;
                            int.TryParse(value, out displayOrder);
                            descriptor.DisplayOrder = displayOrder;
                        }
                        break;
                    case "FileName":
                        descriptor.PluginFileName = value;
                        break;
                    case "LimitedToStores":
                        {
                            //parse list of store IDs
                            foreach (var str1 in value.Split(new [] {','}, StringSplitOptions.RemoveEmptyEntries)
                                                      .Select(x => x.Trim()))
                            {
                                int storeId;
                                if (int.TryParse(str1, out storeId))
                                {
                                    descriptor.LimitedToStores.Add(storeId);
                                }
                            }
                        }
                        break;
                    default:
                        break;
                }
            }

            //nopCommerce 2.00 didn't have 'SupportedVersions' parameter
            //so let's set it to "2.00"
            if (descriptor.SupportedVersions.Count == 0)
                descriptor.SupportedVersions.Add("2.00");

            return descriptor;
        }
예제 #26
0
        protected PluginModel PreparePluginModel(PluginDescriptor pluginDescriptor, bool forList = true)
        {
            var model = pluginDescriptor.ToModel();

            model.Group = T("Admin.Plugins.KnownGroup." + pluginDescriptor.Group);

            if (forList)
            {
                model.FriendlyName = pluginDescriptor.GetLocalizedValue(_services.Localization, "FriendlyName");
                model.Description = pluginDescriptor.GetLocalizedValue(_services.Localization, "Description");
            }

            //locales
            AddLocales(_languageService, model.Locales, (locale, languageId) =>
            {
                locale.FriendlyName = pluginDescriptor.GetLocalizedValue(_services.Localization, "FriendlyName", languageId, false);
                locale.Description = pluginDescriptor.GetLocalizedValue(_services.Localization, "Description", languageId, false);
            });

            // Stores
            model.SelectedStoreIds = _services.Settings.GetSettingByKey<string>(pluginDescriptor.GetSettingKey("LimitedToStores")).ToIntArray();

            // Icon
            model.IconUrl = _pluginMediator.GetIconUrl(pluginDescriptor);

            if (pluginDescriptor.Installed)
            {
                // specify configuration URL only when a plugin is already installed
                if (pluginDescriptor.IsConfigurable)
                {
                    model.ConfigurationUrl = Url.Action("ConfigurePlugin", new { systemName = pluginDescriptor.SystemName });

                    if (!forList)
                    {
                        var configurable = pluginDescriptor.Instance() as IConfigurable;

                        string actionName;
                        string controllerName;
                        RouteValueDictionary routeValues;
                        configurable.GetConfigurationRoute(out actionName, out controllerName, out routeValues);

                        if (actionName.HasValue() && controllerName.HasValue())
                        {
                            model.ConfigurationRoute = new RouteInfo(actionName, controllerName, routeValues);
                        }
                    }
                }

                if (LicenseChecker.IsLicensablePlugin(pluginDescriptor))
                {
                    // we always show license button to serve ability to delete a key
                    model.IsLicensable = true;
                    model.LicenseUrl = Url.Action("LicensePlugin", new { systemName = pluginDescriptor.SystemName });

                    var license = LicenseChecker.GetLicense(pluginDescriptor.SystemName);

                    if (license != null)	// license\plugin has been used
                    {
                        model.LicenseState = license.State;
                        model.TruncatedLicenseKey = license.TruncatedLicenseKey;
                        model.RemainingDemoUsageDays = license.RemainingDemoDays;
                    }
                }
            }
            return model;
        }
예제 #27
0
 public static PluginModel ToModel(this PluginDescriptor entity)
 {
     return(entity.MapTo <PluginDescriptor, PluginModel>());
 }
예제 #28
0
 public void DisablePlugin(PluginDescriptor plugin)
 {
     DisablePlugin(plugin, new HashSet <PluginDescriptor>(), false);
 }
예제 #29
0
    FileReference[] CompilePlugin(FileReference HostProjectFile, FileReference HostProjectPluginFile, PluginDescriptor Plugin, List <UnrealTargetPlatform> HostPlatforms, List <UnrealTargetPlatform> TargetPlatforms, string AdditionalArgs)
    {
        List <FileReference> ManifestFileNames = new List <FileReference>();

        // Build the host platforms
        if (HostPlatforms.Count > 0)
        {
            CommandUtils.LogInformation("Building plugin for host platforms: {0}", String.Join(", ", HostPlatforms));
            foreach (UnrealTargetPlatform HostPlatform in HostPlatforms)
            {
                if (Plugin.SupportedPrograms != null && Plugin.SupportedPrograms.Contains("UnrealHeaderTool"))
                {
                    CompilePluginWithUBT(HostProjectFile, HostProjectPluginFile, Plugin, "UnrealHeaderTool", TargetType.Program, HostPlatform, UnrealTargetConfiguration.Development, ManifestFileNames, String.Format("{0} -plugin={1}", AdditionalArgs, CommandUtils.MakePathSafeToUseWithCommandLine(HostProjectPluginFile.FullName)));
                }
                CompilePluginWithUBT(HostProjectFile, HostProjectPluginFile, Plugin, "UE4Editor", TargetType.Editor, HostPlatform, UnrealTargetConfiguration.Development, ManifestFileNames, AdditionalArgs);
            }
        }

        // Add the game targets
        if (TargetPlatforms.Count > 0)
        {
            CommandUtils.LogInformation("Building plugin for target platforms: {0}", String.Join(", ", TargetPlatforms));
            foreach (UnrealTargetPlatform TargetPlatform in TargetPlatforms)
            {
                if (Plugin.SupportsTargetPlatform(TargetPlatform))
                {
                    CompilePluginWithUBT(HostProjectFile, HostProjectPluginFile, Plugin, "UE4Game", TargetType.Game, TargetPlatform, UnrealTargetConfiguration.Development, ManifestFileNames, AdditionalArgs);
                    CompilePluginWithUBT(HostProjectFile, HostProjectPluginFile, Plugin, "UE4Game", TargetType.Game, TargetPlatform, UnrealTargetConfiguration.Shipping, ManifestFileNames, AdditionalArgs);
                }
            }
        }

        // Package the plugin to the output folder
        HashSet <FileReference> BuildProducts = new HashSet <FileReference>();

        foreach (FileReference ManifestFileName in ManifestFileNames)
        {
            BuildManifest Manifest = CommandUtils.ReadManifest(ManifestFileName);
            BuildProducts.UnionWith(Manifest.BuildProducts.Select(x => new FileReference(x)));
        }
        return(BuildProducts.ToArray());
    }
예제 #30
0
    void CompilePluginWithUBT(FileReference HostProjectFile, FileReference HostProjectPluginFile, PluginDescriptor Plugin, string TargetName, TargetType TargetType, UnrealTargetPlatform Platform, UnrealTargetConfiguration Configuration, List <FileReference> ManifestFileNames, string InAdditionalArgs)
    {
        // Find a list of modules that need to be built for this plugin
        bool bCompilePlatform = false;

        if (Plugin.Modules != null)
        {
            foreach (ModuleDescriptor Module in Plugin.Modules)
            {
                bool bBuildDeveloperTools     = (TargetType == TargetType.Editor || TargetType == TargetType.Program);
                bool bBuildEditor             = (TargetType == TargetType.Editor);
                bool bBuildRequiresCookedData = (TargetType != TargetType.Editor && TargetType != TargetType.Program);
                if (Module.IsCompiledInConfiguration(Platform, Configuration, TargetName, TargetType, bBuildDeveloperTools, bBuildEditor, bBuildRequiresCookedData))
                {
                    bCompilePlatform = true;
                }
            }
        }

        // Add these modules to the build agenda
        if (bCompilePlatform)
        {
            FileReference ManifestFileName = FileReference.Combine(HostProjectFile.Directory, "Saved", String.Format("Manifest-{0}-{1}-{2}.xml", TargetName, Platform, Configuration));
            ManifestFileNames.Add(ManifestFileName);

            string Arguments = String.Format("-plugin={0} -iwyu -noubtmakefiles -manifest={1} -nohotreload", CommandUtils.MakePathSafeToUseWithCommandLine(HostProjectPluginFile.FullName), CommandUtils.MakePathSafeToUseWithCommandLine(ManifestFileName.FullName));
            if (!String.IsNullOrEmpty(InAdditionalArgs))
            {
                Arguments += InAdditionalArgs;
            }

            CommandUtils.RunUBT(CmdEnv, UE4Build.GetUBTExecutable(), String.Format("{0} {1} {2} {3}", TargetName, Platform, Configuration, Arguments));
        }
    }
예제 #31
0
    public override void ExecuteBuild()
    {
        // Get the plugin filename
        string PluginParam = ParseParamValue("Plugin");

        if (PluginParam == null)
        {
            throw new AutomationException("Missing -Plugin=... argument");
        }

        // Check it exists
        FileReference PluginFile = new FileReference(PluginParam);

        if (!FileReference.Exists(PluginFile))
        {
            throw new AutomationException("Plugin '{0}' not found", PluginFile.FullName);
        }

        // Get the output directory
        string PackageParam = ParseParamValue("Package");

        if (PackageParam == null)
        {
            throw new AutomationException("Missing -Package=... argument");
        }

        // Option for verifying that all include directive s
        bool bStrictIncludes = ParseParam("StrictIncludes");

        // Make sure the packaging directory is valid
        DirectoryReference PackageDir = new DirectoryReference(PackageParam);

        if (PluginFile.IsUnderDirectory(PackageDir))
        {
            throw new AutomationException("Packaged plugin output directory must be different to source");
        }
        if (PackageDir.IsUnderDirectory(DirectoryReference.Combine(CommandUtils.RootDirectory, "Engine")))
        {
            throw new AutomationException("Output directory for packaged plugin must be outside engine directory");
        }

        // Clear the output directory of existing stuff
        if (DirectoryReference.Exists(PackageDir))
        {
            CommandUtils.DeleteDirectoryContents(PackageDir.FullName);
        }
        else
        {
            DirectoryReference.CreateDirectory(PackageDir);
        }

        // Create a placeholder FilterPlugin.ini with instructions on how to use it
        FileReference SourceFilterFile = FileReference.Combine(PluginFile.Directory, "Config", "FilterPlugin.ini");

        if (!FileReference.Exists(SourceFilterFile))
        {
            List <string> Lines = new List <string>();
            Lines.Add("[FilterPlugin]");
            Lines.Add("; This section lists additional files which will be packaged along with your plugin. Paths should be listed relative to the root plugin directory, and");
            Lines.Add("; may include \"...\", \"*\", and \"?\" wildcards to match directories, files, and individual characters respectively.");
            Lines.Add(";");
            Lines.Add("; Examples:");
            Lines.Add(";    /README.txt");
            Lines.Add(";    /Extras/...");
            Lines.Add(";    /Binaries/ThirdParty/*.dll");
            DirectoryReference.CreateDirectory(SourceFilterFile.Directory);
            CommandUtils.WriteAllLines_NoExceptions(SourceFilterFile.FullName, Lines.ToArray());
        }

        // Create a host project for the plugin. For script generator plugins, we need to have UHT be able to load it, which can only happen if it's enabled in a project.
        FileReference HostProjectFile       = FileReference.Combine(PackageDir, "HostProject", "HostProject.uproject");
        FileReference HostProjectPluginFile = CreateHostProject(HostProjectFile, PluginFile);

        // Read the plugin
        CommandUtils.LogInformation("Reading plugin from {0}...", HostProjectPluginFile);
        PluginDescriptor Plugin = PluginDescriptor.FromFile(HostProjectPluginFile);

        // Get the arguments for the compile
        StringBuilder AdditionalArgs = new StringBuilder();

        if (bStrictIncludes)
        {
            CommandUtils.LogInformation("Building with precompiled headers and unity disabled");
            AdditionalArgs.Append(" -NoPCH -NoSharedPCH -DisableUnity");
        }

        // Compile the plugin for all the target platforms
        List <UnrealTargetPlatform> HostPlatforms = ParseParam("NoHostPlatform")? new List <UnrealTargetPlatform>() : new List <UnrealTargetPlatform> {
            BuildHostPlatform.Current.Platform
        };
        List <UnrealTargetPlatform> TargetPlatforms = GetTargetPlatforms(this, BuildHostPlatform.Current.Platform);

        FileReference[] BuildProducts = CompilePlugin(HostProjectFile, HostProjectPluginFile, Plugin, HostPlatforms, TargetPlatforms, AdditionalArgs.ToString());

        // Package up the final plugin data
        PackagePlugin(HostProjectPluginFile, BuildProducts, PackageDir, ParseParam("unversioned"));

        // Remove the host project
        if (!ParseParam("NoDeleteHostProject"))
        {
            CommandUtils.DeleteDirectory(HostProjectFile.Directory.FullName);
        }
    }
예제 #32
0
 public void HandleException(Exception e, PluginDescriptor descriptor)
 {
     IExceptionReporter reporter = plugin as IExceptionReporter ?? (plugin == null ? (IExceptionReporter)null : (IExceptionReporter)this);
     ErrorDialog.PresentModal(e, reporter, String.Format(TextResources.MsgBox_Formatable1_Text_ModuleError, plugin), false);
 }
예제 #33
0
        /// <summary>
        /// Import plugin resources from xml files in plugin's localization directory.
        /// </summary>
        /// <param name="pluginDescriptor">Descriptor of the plugin</param>
        /// <param name="forceToList">Load them into list rather than into database</param>
        /// <param name="updateTouchedResources">Specifies whether user touched resources should also be updated</param>
        /// <param name="filterLanguages">Import only files for particular languages</param>
        public virtual void ImportPluginResourcesFromXml(PluginDescriptor pluginDescriptor,
                                                         List <LocaleStringResource> forceToList = null, bool updateTouchedResources = true, IList <Language> filterLanguages = null)
        {
            string pluginDir       = pluginDescriptor.OriginalAssemblyFile.Directory.FullName;
            string localizationDir = Path.Combine(pluginDir, "Localization");

            if (!System.IO.Directory.Exists(localizationDir))
            {
                return;
            }

            if (forceToList == null && updateTouchedResources)
            {
                DeleteLocaleStringResources(pluginDescriptor.ResourceRootKey);
            }

            var languages = _languageService.GetAllLanguages(true);
            var doc       = new XmlDocument();

            foreach (var filePath in System.IO.Directory.EnumerateFiles(localizationDir, "*.xml"))
            {
                Match  match        = Regex.Match(Path.GetFileName(filePath), Regex.Escape("resources.") + "(.*?)" + Regex.Escape(".xml"));
                string languageCode = match.Groups[1].Value;

                Language language = languages.Where(l => l.LanguageCulture.IsCaseInsensitiveEqual(languageCode)).FirstOrDefault();
                if (language != null)
                {
                    language = _languageService.GetLanguageById(language.Id);
                }

                if (languageCode.HasValue() && language != null)
                {
                    if (filterLanguages != null && !filterLanguages.Exists(x => x.Id == language.Id))
                    {
                        continue;
                    }

                    doc.Load(filePath);

                    if (forceToList == null)
                    {
                        ImportResourcesFromXml(language, doc, pluginDescriptor.ResourceRootKey, true, updateTouchedResources: updateTouchedResources);
                    }
                    else
                    {
                        var nodes = doc.SelectNodes(@"//Language/LocaleResource");
                        foreach (XmlNode node in nodes)
                        {
                            var valueNode = node.SelectSingleNode("Value");
                            var res       = new LocaleStringResource()
                            {
                                ResourceName  = node.Attributes["Name"].InnerText.Trim(),
                                ResourceValue = (valueNode == null ? "" : valueNode.InnerText),
                                LanguageId    = language.Id,
                                IsFromPlugin  = true
                            };

                            if (res.ResourceName.HasValue())
                            {
                                forceToList.Add(res);
                            }
                        }
                    }
                }
            }
        }
예제 #34
0
        private IEnumerable<string> GetNuGetPluginFolders(PluginDescriptor pluginDescriptor)
        {
            string nuGetPackagesFolder = GetNuGetPackagesFolder();

            return pluginPostfixes
                .Select(pluginPostfix => pluginDescriptor.Name + pluginPostfix)
                .Select(packageName => GetLatestPackage(nuGetPackagesFolder, packageName))
                .Where(pluginFolder => pluginFolder != null);
        }
예제 #35
0
 /// <summary>
 /// Ctor
 /// </summary>
 /// <param name="plugin">Updated plugin</param>
 public PluginUpdatedEvent(PluginDescriptor plugin)
 {
     this.Plugin = plugin;
 }
예제 #36
0
        private IEnumerable<string> GetPluginGeneratorFolders(PluginDescriptor pluginDescriptor)
        {
            var pluginGeneratorFolders = (new[] { @"" })
                .Concat(GetSpecFlowVersionSpecifiers().Select(v => @"tools\SpecFlowPlugin" + v))
                .Concat(new[] { @"tools", @"lib\net45", @"lib\net40", @"lib\net35", @"lib"});

            return GetPluginFolders(pluginDescriptor).SelectMany(pluginFolder => pluginGeneratorFolders, Path.Combine);
        }
예제 #37
0
        public virtual void ImportPluginResourcesFromXml(
            PluginDescriptor pluginDescriptor,
            IList <LocaleStringResource> targetList = null,
            bool updateTouchedResources             = true,
            IList <Language> filterLanguages        = null)
        {
            var directory = new DirectoryInfo(Path.Combine(pluginDescriptor.PhysicalPath, "Localization"));

            if (!directory.Exists)
            {
                return;
            }

            if (targetList == null && updateTouchedResources)
            {
                DeleteLocaleStringResources(pluginDescriptor.ResourceRootKey);
            }

            var unprocessedLanguages = new List <Language>();

            var defaultLanguageId = _languageService.GetDefaultLanguageId();
            var languages         = filterLanguages ?? _languageService.GetAllLanguages(true);

            string code = null;

            foreach (var language in languages)
            {
                code = ImportPluginResourcesForLanguage(
                    language,
                    null,
                    directory,
                    pluginDescriptor.ResourceRootKey,
                    targetList,
                    updateTouchedResources,
                    false);

                if (code == null)
                {
                    unprocessedLanguages.Add(language);
                }
            }

            if (filterLanguages == null && unprocessedLanguages.Count > 0)
            {
                // There were unprocessed languages (no corresponding resource file could be found).
                // In order for GetResource() to be able to gracefully fallback to the default language's resources,
                // we need to import resources for the current default language....
                var processedLanguages = languages.Except(unprocessedLanguages).ToList();
                if (!processedLanguages.Any(x => x.Id == defaultLanguageId))
                {
                    // ...but only if no resource file could be mapped to the default language before,
                    // namely because in this case the following operation would be redundant.
                    var defaultLanguage = _languageService.GetLanguageById(_languageService.GetDefaultLanguageId());
                    if (defaultLanguage != null)
                    {
                        ImportPluginResourcesForLanguage(
                            defaultLanguage,
                            "en-us",
                            directory,
                            pluginDescriptor.ResourceRootKey,
                            targetList,
                            updateTouchedResources,
                            true);
                    }
                }
            }

            try
            {
                var hasher = CreatePluginResourcesHasher(pluginDescriptor);
                hasher.Persist();
            }
            catch { }
        }
        private string GetDefaultPluginUrl(PluginDescriptor plugin)
        {
            string path = "~/Administration/Content/images/icon-plugin-{0}.png".FormatInvariant(plugin.Group);

            if (System.IO.File.Exists(Server.MapPath(path)))
            {
                return path;
            }

            return "~/Administration/Content/images/icon-plugin-default.png";
        }
예제 #39
0
 public DirectoryHasher CreatePluginResourcesHasher(PluginDescriptor pluginDescriptor)
 {
     return(new DirectoryHasher(Path.Combine(pluginDescriptor.PhysicalPath, "Localization"), "resources.*.xml"));
 }
        protected PluginModel PreparePluginModel(PluginDescriptor pluginDescriptor)
        {
            var pluginModel = pluginDescriptor.ToModel();

            //locales
            AddLocales(_languageService, pluginModel.Locales, (locale, languageId) =>
            {
                locale.FriendlyName = pluginDescriptor.Instance().GetLocalizedFriendlyName(_localizationService, languageId, false);
            });

            if (pluginDescriptor.Installed)
            {
                //specify configuration URL only when a plugin is already installed

                //plugins do not provide a general URL for configuration
                //because some of them have some custom URLs for configuration
                //for example, discount requirement plugins require additional parameters and attached to a certain discount
                var pluginInstance = pluginDescriptor.Instance();
                string configurationUrl = null;
                if (pluginInstance is IPaymentMethod)
                {
                    //payment plugin
                    configurationUrl = Url.Action("ConfigureMethod", "Payment", new { systemName = pluginDescriptor.SystemName });
                }
                else if (pluginInstance is IShippingRateComputationMethod)
                {
                    //shipping rate computation method
                    configurationUrl = Url.Action("ConfigureProvider", "Shipping", new { systemName = pluginDescriptor.SystemName });
                }
                else if (pluginInstance is ITaxProvider)
                {
                    //tax provider
                    configurationUrl = Url.Action("ConfigureProvider", "Tax", new { systemName = pluginDescriptor.SystemName });
                }
                else if (pluginInstance is IExternalAuthenticationMethod)
                {
                    //external auth method
                    configurationUrl = Url.Action("ConfigureMethod", "ExternalAuthentication", new { systemName = pluginDescriptor.SystemName });
                }
                else if (pluginInstance is IWidgetPlugin)
                {
                    //Misc plugins
                    configurationUrl = Url.Action("ConfigureWidget", "Widget", new { systemName = pluginDescriptor.SystemName });
                }
                else if (pluginInstance is IMiscPlugin)
                {
                    //Misc plugins
                    configurationUrl = Url.Action("ConfigureMiscPlugin", "Plugin", new { systemName = pluginDescriptor.SystemName });
                }
                pluginModel.ConfigurationUrl = configurationUrl;

                //enabled/disabled (only for some plugin types)
                if (pluginInstance is IPaymentMethod)
                {
                    //payment plugin
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled = ((IPaymentMethod)pluginInstance).IsPaymentMethodActive(_paymentSettings);
                }
                else if (pluginInstance is IShippingRateComputationMethod)
                {
                    //shipping rate computation method
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled = ((IShippingRateComputationMethod)pluginInstance).IsShippingRateComputationMethodActive(_shippingSettings);
                }
                else if (pluginInstance is ITaxProvider)
                {
                    //tax provider
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled = pluginDescriptor.SystemName.Equals(_taxSettings.ActiveTaxProviderSystemName, StringComparison.InvariantCultureIgnoreCase);
                }
                else if (pluginInstance is IExternalAuthenticationMethod)
                {
                    //external auth method
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled = ((IExternalAuthenticationMethod)pluginInstance).IsMethodActive(_externalAuthenticationSettings);
                }
                else if (pluginInstance is IWidgetPlugin)
                {
                    //Misc plugins
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled = ((IWidgetPlugin)pluginInstance).IsWidgetActive(_widgetSettings);
                }

            }
            return pluginModel;
        }
예제 #41
0
        protected virtual PluginModel PreparePluginModel(PluginDescriptor pluginDescriptor,
                                                         bool prepareLocales = true, bool prepareStores = true, bool prepareAcl = true)
        {
            var pluginModel = pluginDescriptor.ToModel();

            //logo
            pluginModel.LogoUrl = pluginDescriptor.GetLogoUrl(_webHelper);

            if (prepareLocales)
            {
                //locales
                AddLocales(_languageService, pluginModel.Locales, (locale, languageId) =>
                {
                    locale.FriendlyName = pluginDescriptor.Instance().GetLocalizedFriendlyName(_localizationService, languageId, false);
                });
            }
            if (prepareStores)
            {
                //stores
                pluginModel.SelectedStoreIds = pluginDescriptor.LimitedToStores;
                var allStores = _storeService.GetAllStores();
                foreach (var store in allStores)
                {
                    pluginModel.AvailableStores.Add(new SelectListItem
                    {
                        Text     = store.Name,
                        Value    = store.Id.ToString(),
                        Selected = pluginModel.SelectedStoreIds.Contains(store.Id)
                    });
                }
            }

            if (prepareAcl)
            {
                //acl
                pluginModel.SelectedCustomerRoleIds = pluginDescriptor.LimitedToCustomerRoles;
                foreach (var role in _customerService.GetAllCustomerRoles(true))
                {
                    pluginModel.AvailableCustomerRoles.Add(new SelectListItem
                    {
                        Text     = role.Name,
                        Value    = role.Id.ToString(),
                        Selected = pluginModel.SelectedCustomerRoleIds.Contains(role.Id)
                    });
                }
            }

            //configuration URLs
            if (pluginDescriptor.Installed)
            {
                //display configuration URL only when a plugin is already installed
                var pluginInstance = pluginDescriptor.Instance();
                pluginModel.ConfigurationUrl = pluginInstance.GetConfigurationPageUrl();


                //enabled/disabled (only for some plugin types)
                if (pluginInstance is IPaymentMethod)
                {
                    //payment plugin
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled        = ((IPaymentMethod)pluginInstance).IsPaymentMethodActive(_paymentSettings);
                }
                else if (pluginInstance is IShippingRateComputationMethod)
                {
                    //shipping rate computation method
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled        = ((IShippingRateComputationMethod)pluginInstance).IsShippingRateComputationMethodActive(_shippingSettings);
                }
                else if (pluginInstance is IPickupPointProvider)
                {
                    //pickup point provider
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled        = ((IPickupPointProvider)pluginInstance).IsPickupPointProviderActive(_shippingSettings);
                }
                else if (pluginInstance is ITaxProvider)
                {
                    //tax provider
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled        = pluginDescriptor.SystemName.Equals(_taxSettings.ActiveTaxProviderSystemName, StringComparison.InvariantCultureIgnoreCase);
                }
                else if (pluginInstance is IExternalAuthenticationMethod)
                {
                    //external auth method
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled        = ((IExternalAuthenticationMethod)pluginInstance).IsMethodActive(_externalAuthenticationSettings);
                }
                else if (pluginInstance is IWidgetPlugin)
                {
                    //Misc plugins
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled        = ((IWidgetPlugin)pluginInstance).IsWidgetActive(_widgetSettings);
                }
            }
            return(pluginModel);
        }
예제 #42
0
        public static void SavePluginDescriptionFile(PluginDescriptor plugin)
        {
            if (plugin == null)
                throw new ArgumentException("plugin");

            //get the Description.txt file path
            if (plugin.OriginalAssemblyFile == null)
                throw new Exception(string.Format("Cannot load original assembly path for {0} plugin.", plugin.SystemName));
            var filePath = Path.Combine(plugin.OriginalAssemblyFile.Directory.FullName, "Description.txt");
            if (!File.Exists(filePath))
                throw new Exception(string.Format("Description file for {0} plugin does not exist. {1}", plugin.SystemName, filePath));

            var keyValues = new List<KeyValuePair<string, string>>();
            keyValues.Add(new KeyValuePair<string, string>("Group", plugin.Group));
            keyValues.Add(new KeyValuePair<string, string>("FriendlyName", plugin.FriendlyName));
            keyValues.Add(new KeyValuePair<string, string>("SystemName", plugin.SystemName));
            keyValues.Add(new KeyValuePair<string, string>("Version", plugin.Version));
            keyValues.Add(new KeyValuePair<string, string>("SupportedVersions", string.Join(",", plugin.SupportedVersions)));
            keyValues.Add(new KeyValuePair<string, string>("Author", plugin.Author));
            keyValues.Add(new KeyValuePair<string, string>("DisplayOrder", plugin.DisplayOrder.ToString()));
            keyValues.Add(new KeyValuePair<string, string>("FileName", plugin.PluginFileName));
            if (plugin.LimitedToStores.Count > 0)
            {
                var storeList = "";
                for (int i = 0; i < plugin.LimitedToStores.Count; i++)
                {
                    storeList += plugin.LimitedToStores[i];
                    if (i != plugin.LimitedToStores.Count - 1)
                        storeList += ",";
                }
                keyValues.Add(new KeyValuePair<string, string>("LimitedToStores", storeList));
            }

            var sb = new StringBuilder();
            for (int i = 0; i < keyValues.Count; i++)
            {
                var key = keyValues[i].Key;
                var value = keyValues[i].Value;
                sb.AppendFormat("{0}: {1}", key, value);
                if (i != keyValues.Count -1)
                    sb.Append(Environment.NewLine);
            }
            //save the file
            File.WriteAllText(filePath, sb.ToString());
        }
예제 #43
0
 public static PluginModel ToModel(this PluginDescriptor entity)
 {
     return(Mapper.Map <PluginDescriptor, PluginModel>(entity));
 }
        /// <summary>
        /// Gets a value indicating whether a plugin is assumed
        /// to be compatible with the current app version
        /// </summary>
        /// <remarks>
        /// A plugin is generally compatible when both app version and plugin's 
        /// <c>MinorAppVersion</c> are equal, OR - when app version is greater - it is 
        /// assumed to be compatible when no breaking changes occured since <c>MinorAppVersion</c>.
        /// </remarks>
        /// <param name="descriptor">The plugin to check</param>
        /// <returns><c>true</c> when the plugin is assumed to be compatible</returns>
        public static bool IsAssumedCompatible(PluginDescriptor descriptor)
        {
			Guard.ArgumentNotNull(() => descriptor);

			return IsAssumedCompatible(descriptor.MinAppVersion);
        }
예제 #45
0
        protected virtual PluginModel PreparePluginModel(PluginDescriptor pluginDescriptor,
                                                         bool prepareLocales = true, bool prepareStores = true, bool prepareAcl = true)
        {
            var pluginModel = pluginDescriptor.ToModel();

            //logo
            pluginModel.LogoUrl = pluginDescriptor.GetLogoUrl(_webHelper);

            if (prepareLocales)
            {
                //locales
                AddLocales(_languageService, pluginModel.Locales, (locale, languageId) =>
                {
                    locale.FriendlyName = pluginDescriptor.Instance().GetLocalizedFriendlyName(_localizationService, languageId, false);
                });
            }
            if (prepareStores)
            {
                //stores
                pluginModel.SelectedStoreIds = pluginDescriptor.LimitedToStores;
                var allStores = _storeService.GetAllStores();
                foreach (var store in allStores)
                {
                    pluginModel.AvailableStores.Add(new SelectListItem
                    {
                        Text     = store.Name,
                        Value    = store.Id.ToString(),
                        Selected = pluginModel.SelectedStoreIds.Contains(store.Id)
                    });
                }
            }

            if (prepareAcl)
            {
                //acl
                pluginModel.SelectedCustomerRoleIds = pluginDescriptor.LimitedToCustomerRoles;
                foreach (var role in _customerService.GetAllCustomerRoles(true))
                {
                    pluginModel.AvailableCustomerRoles.Add(new SelectListItem
                    {
                        Text     = role.Name,
                        Value    = role.Id.ToString(),
                        Selected = pluginModel.SelectedCustomerRoleIds.Contains(role.Id)
                    });
                }
            }

            //configuration URLs
            if (pluginDescriptor.Installed)
            {
                //specify configuration URL only when a plugin is already installed

                //plugins do not provide a general URL for configuration
                //because some of them have some custom URLs for configuration
                //for example, discount requirement plugins require additional parameters and attached to a certain discount
                var    pluginInstance   = pluginDescriptor.Instance();
                string configurationUrl = null;
                if (pluginInstance is IPaymentMethod)
                {
                    //payment plugin
                    configurationUrl = Url.Action("ConfigureMethod", "Payment", new { systemName = pluginDescriptor.SystemName });
                }
                else if (pluginInstance is IShippingRateComputationMethod)
                {
                    //shipping rate computation method
                    configurationUrl = Url.Action("ConfigureProvider", "Shipping", new { systemName = pluginDescriptor.SystemName });
                }
                else if (pluginInstance is IPickupPointProvider)
                {
                    //pickup point provider
                    configurationUrl = Url.Action("ConfigurePickupPointProvider", "Shipping", new { systemName = pluginDescriptor.SystemName });
                }
                else if (pluginInstance is ITaxProvider)
                {
                    //tax provider
                    configurationUrl = Url.Action("ConfigureProvider", "Tax", new { systemName = pluginDescriptor.SystemName });
                }
                else if (pluginInstance is IExternalAuthenticationMethod)
                {
                    //external auth method
                    configurationUrl = Url.Action("ConfigureMethod", "ExternalAuthentication", new { systemName = pluginDescriptor.SystemName });
                }
                else if (pluginInstance is IWidgetPlugin)
                {
                    //Misc plugins
                    configurationUrl = Url.Action("ConfigureWidget", "Widget", new { systemName = pluginDescriptor.SystemName });
                }
                else if (pluginInstance is IMiscPlugin)
                {
                    //Misc plugins
                    configurationUrl = Url.Action("ConfigureMiscPlugin", "Plugin", new { systemName = pluginDescriptor.SystemName });
                }
                pluginModel.ConfigurationUrl = configurationUrl;



                //enabled/disabled (only for some plugin types)
                if (pluginInstance is IPaymentMethod)
                {
                    //payment plugin
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled        = ((IPaymentMethod)pluginInstance).IsPaymentMethodActive(_paymentSettings);
                }
                else if (pluginInstance is IShippingRateComputationMethod)
                {
                    //shipping rate computation method
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled        = ((IShippingRateComputationMethod)pluginInstance).IsShippingRateComputationMethodActive(_shippingSettings);
                }
                else if (pluginInstance is IPickupPointProvider)
                {
                    //pickup point provider
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled        = ((IPickupPointProvider)pluginInstance).IsPickupPointProviderActive(_shippingSettings);
                }
                else if (pluginInstance is ITaxProvider)
                {
                    //tax provider
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled        = pluginDescriptor.SystemName.Equals(_taxSettings.ActiveTaxProviderSystemName, StringComparison.InvariantCultureIgnoreCase);
                }
                else if (pluginInstance is IExternalAuthenticationMethod)
                {
                    //external auth method
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled        = ((IExternalAuthenticationMethod)pluginInstance).IsMethodActive(_externalAuthenticationSettings);
                }
                else if (pluginInstance is IWidgetPlugin)
                {
                    //Misc plugins
                    pluginModel.CanChangeEnabled = true;
                    pluginModel.IsEnabled        = ((IWidgetPlugin)pluginInstance).IsWidgetActive(_widgetSettings);
                }
            }
            return(pluginModel);
        }