/// <summary>
        /// Разрешение типа на основе его описания в синтаксическом дереве
        /// </summary>
        /// <param name="service">Контекст разрешения типа</param>
        public override Type Resolve(TypeResolutionService service)
        {
            var typeName = BuildTypeFullName(service.Symbol);
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            var assembly = assemblies.FirstOrDefault(x => x.GetName().Name == service.Symbol.ContainingAssembly.Name);
            if (assembly == null)
            {
                return null;
            }

            return assembly.GetType(typeName, true);
        }
Ejemplo n.º 2
0
        public override Type Resolve(TypeResolutionService service)
        {
            var named = service.Symbol as INamedTypeSymbol;

            var unboundType = service.Resolve(named.ConstructUnboundGenericType());
            var arguments = named.TypeArguments.Select(service.Resolve).ToArray();

            if (arguments.Length != named.Arity)
            {
                throw new Exception("Не удалось разрешить все типы аргументов обобщенного типа");
            }

            return unboundType.MakeGenericType(arguments);
        }
        public override void CMD_list(Arguments args, Guid rootId)
        {
            types = new List <DynamicModuleType>();

            // Top root: display the types
            if (rootId == Guid.Empty)
            {
                Site site = svc.Get_Site();

                var multisiteContext = SystemManager.CurrentContext as MultisiteContext;
                var theSite          = multisiteContext.GetSiteById(site.Id);
                var dynTypes         = ModuleBuilderManager.GetManager().Provider.GetDynamicModuleTypes();

                HashSet <Guid> typeIds = new HashSet <Guid>();

                // Dynamic Modules
                foreach (var datalink in site.SiteDataSourceLinks.Where(dsl => !dsl.DataSourceName.StartsWith("Telerik.Sitefinity.")))
                {
                    foreach (var dynType in dynTypes.Where(mt => mt.ModuleName == datalink.DataSourceName))
                    {
                        if (typeIds.Contains(dynType.Id))
                        {
                            continue;
                        }
                        types.Add(dynType);
                        typeIds.Add(dynType.Id);
                    }

/*						types.Add(dynType);
 *                                              Type type = TypeResolutionService.ResolveType(dynType.GetFullTypeName());
 *                                              types.Add(type);
 *                                      }*/
                }
                return;
            }

            // Inside a specific type: display the items
            var  dynType2 = ModuleBuilderManager.GetManager().Provider.GetDynamicModuleType(rootId);
            Type type2    = TypeResolutionService.ResolveType(dynType2.GetFullTypeName());

            var dynamicContentManager = DynamicModuleManager.GetManager(svc.Get_Provider());

            dynamicContentManager.Provider.SuppressSecurityChecks = false;
            items = dynamicContentManager.GetDataItems(type2).Where(n => n.Visible && n.Status == ContentLifecycleStatus.Live).ToList();
        }
        public void CreateCityWithTenHotelsAndTenRestaurant()
        {
            DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager();
            Type           cityType = TypeResolutionService.ResolveType(HierarchicalDynamicContentTests.CityType);
            DynamicContent cityItem = dynamicModuleManager.CreateDataItem(cityType, HierarchicalDynamicContentTests.CityId, dynamicModuleManager.Provider.ApplicationName);

            cityItem.SetValue("Name", "Test Name");
            cityItem.SetValue("History", "Test History");
            cityItem.SetString("UrlName", "TestUrlName");
            cityItem.SetValue("Owner", SecurityManager.GetCurrentUserId());
            cityItem.SetValue("PublicationDate", DateTime.Now);
            cityItem.SetWorkflowStatus(dynamicModuleManager.Provider.ApplicationName, "Draft");

            Type hotelType = TypeResolutionService.ResolveType(HierarchicalDynamicContentTests.HotelType);

            for (int i = 0; i < 10; i++)
            {
                DynamicContent hotelItem = dynamicModuleManager.CreateDataItem(hotelType);
                hotelItem.SetValue("Name", "Test Name " + i);
                hotelItem.SetValue("Overview", "Test Overview " + i);
                cityItem.AddChildItem(hotelItem);
            }

            Type restaurantType = TypeResolutionService.ResolveType(HierarchicalDynamicContentTests.RestaurantType);

            for (int i = 0; i < 10; i++)
            {
                DynamicContent restaurantItem = dynamicModuleManager.CreateDataItem(restaurantType);
                restaurantItem.SetValue("Name", "Test Name " + i);
                restaurantItem.SetValue("Description", "Test Description " + i);
                cityItem.AddChildItem(restaurantItem);
            }

            dynamicModuleManager.SaveChanges();

            var actualCity = dynamicModuleManager.GetDataItem(cityType, cityItem.Id);

            Assert.IsNotNull(actualCity);

            var hotelCount      = DynamicContentExtensions.GetChildItemsCount(actualCity, HierarchicalDynamicContentTests.HotelType);
            var restaurantCount = DynamicContentExtensions.GetChildItemsCount(actualCity, HierarchicalDynamicContentTests.RestaurantType);

            Assert.AreEqual(hotelCount, 10);
            Assert.AreEqual(restaurantCount, 10);
        }
        /// <summary>
        /// This is the default Action.
        /// </summary>
        public ActionResult Index()
        {
            var model = new AuthorsWidgetModel();

            //GET AUTHORS
            var providerName = String.Empty;
            DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager(providerName);
            Type authorType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.Authors.Author");

            // This is how we get the collection of Author items
            var myCollection = dynamicModuleManager.GetDataItems(authorType).Where(i => i.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Live).Take(4);

            // At this point myCollection contains the items from type authorType
            model.AvatarEnabled = this.EnableAvatar;
            model.Authors       = myCollection.Select(i => AuthorViewModel.GetAuthorViewModel(i)).ToList();

            return(View("Default", model));
        }
        // Demonstrates how Destino content items can be retrieved through filtering
        public DynamicContent RetrieveDestinoThroughFiltering(string destinoUrl)
        {
            // Set the provider name for the DynamicModuleManager here. All available providers are listed in
            // Administration -> Settings -> Advanced -> DynamicModules -> Providers
            var providerName = String.Empty;

            DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager(providerName);
            Type destinoType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.Viagens.Destino");

            // This is how we get the destino items through filtering
            var myFilteredCollection = dynamicModuleManager.GetDataItems(destinoType)
                                       .SingleOrDefault(d => d.UrlName == destinoUrl && d.Status == ContentLifecycleStatus.Live && d.Visible);

            // At this point myFilteredCollection contains the items that match the lambda expression passed to the Where extension method
            // If you want only the first matching element you can freely get it by ".First()" extension method like this:
            // var myFirstFilteredItem = myFilteredCollection.First();
            return(myFilteredCollection);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Delete a country item by title.
        /// </summary>
        /// <param name="countryName">The title of the item.</param>
        public void DeleteCountry(string countryName)
        {
            var providerName = string.Empty;

            if (ServerOperations.MultiSite().CheckIsMultisiteMode())
            {
                providerName = "dynamicContentProvider";
            }

            DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager(providerName);

            Type           countryType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.Booking.Country");
            DynamicContent countryItem = dynamicModuleManager.GetDataItems(countryType).Where("Title = \"" + countryName + "\"").First();

            dynamicModuleManager.DeleteDataItem(countryItem);

            dynamicModuleManager.SaveChanges();
        }
Ejemplo n.º 8
0
        public IEnumerable <WebinarViewModel> GetContentList()
        {
            Type webinarType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.Webinars.Webinar");

            var dynamicModuleManager = DynamicModuleManager.GetManager();

            var webinars = dynamicModuleManager.GetDataItems(webinarType).Where(d => d.Status == ContentLifecycleStatus.Live)
                           .Select(w => new WebinarViewModel()
            {
                Title       = w.GetValue <string>("Title"),
                Description = w.GetString("Description").Value,
                StartDate   = w.GetValue <DateTime?>("Start") ?? DateTime.UtcNow,
                EndDate     = w.GetValue <DateTime?>("End") ?? DateTime.UtcNow
            });


            return(webinars.AsEnumerable());
        }
Ejemplo n.º 9
0
        public void Populate(string itemType)
        {
            var  dynamicModuleManager = DynamicModuleManager.GetManager();
            Type referenceType        = TypeResolutionService.ResolveType(itemType);

            var query = dynamicModuleManager.GetDataItems(referenceType).Where(s => s.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Live);

            Guid itemId;

            if (!string.IsNullOrWhiteSpace(this.SelectedItemId) && Guid.TryParse(this.SelectedItemId, out itemId))
            {
                this.Item = query.SingleOrDefault(n => n.Id == itemId);
            }
            else
            {
                this.Item = query.FirstOrDefault();
            }
        }
Ejemplo n.º 10
0
        public void CreatePressArticle(string title, string url, Guid tag, Guid category, string publishedBy, string providerName)
        {
            if (ServerOperations.MultiSite().CheckIsMultisiteMode() && providerName == null)
            {
                providerName = "dynamicContentProvider";
            }

            DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager(providerName);
            Type pressArticleType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.PressRelease.PressArticle");

            Telerik.Sitefinity.DynamicModules.Model.DynamicContent pressArticleItem = dynamicModuleManager.CreateDataItem(pressArticleType);

            // This is how values for the properties are set
            pressArticleItem.SetValue("Title", title);
            pressArticleItem.SetValue("Guid", Guid.NewGuid());

            if (publishedBy.IsNullOrEmpty())
            {
                pressArticleItem.SetValue("PublishedBy", "Some PublishedBy");
            }
            else
            {
                pressArticleItem.SetValue("PublishedBy", publishedBy);
            }

            if (tag != null && tag != Guid.Empty)
            {
                pressArticleItem.Organizer.AddTaxa("Tags", tag);
            }

            if (category != null && category != Guid.Empty)
            {
                pressArticleItem.Organizer.AddTaxa("Category", category);
            }

            pressArticleItem.SetString("UrlName", url);
            pressArticleItem.SetValue("Owner", SecurityManager.GetCurrentUserId());
            pressArticleItem.SetValue("PublicationDate", DateTime.Now);
            pressArticleItem.SetWorkflowStatus(dynamicModuleManager.Provider.ApplicationName, "Published");
            dynamicModuleManager.Lifecycle.Publish(pressArticleItem);

            // You need to call SaveChanges() in order for the items to be actually persisted to data store
            dynamicModuleManager.SaveChanges();
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Gets an dynamic item from page url. This method automatically updates the opengraph model.
        /// </summary>
        /// <param name="pageUrl">The page url (Without host and single segment</param>
        /// <param name="finalCurrentModuleType">The used type</param>
        /// <returns></returns>
        private bool GetDynamicItemFromPageUrl(string pageUrl, OpengraphModuleConfig ogConfigElement)
        {
            Type itemsType = null;

            //Try catched this to avoid errors for build in modules
            try {
                bool returnStatement = false;
                //Remove white spaces
                ogConfigElement.ModuleType = ogConfigElement.ModuleType.Replace(" ", "");

                //Check for multiple types
                if (ogConfigElement.ModuleType.Contains(seperator))
                {
                    //Loop all given types
                    foreach (string stringType in ogConfigElement.ModuleType.Split(seperator))
                    {
                        itemsType       = TypeResolutionService.ResolveType(stringType);
                        returnStatement = GetDataItemByType(itemsType, ogConfigElement, pageUrl);

                        if (returnStatement)
                        {
                            return(returnStatement);
                        }
                    }
                }
                else
                {
                    //Only one type, get it.
                    itemsType       = TypeResolutionService.ResolveType(ogConfigElement.ModuleType);
                    returnStatement = GetDataItemByType(itemsType, ogConfigElement, pageUrl);

                    if (returnStatement)
                    {
                        return(returnStatement);
                    }
                }
                return(returnStatement);
            }
            catch (Exception e)
            {
                _logiszLogger.LogException(ModuleName, e);
                return(false);
            }
        }
        public void DynamicWidgetsDesignerContent_VerifyAllFunctionality()
        {
            this.pageOperations = new PagesOperations();
            string testName          = System.Reflection.MethodInfo.GetCurrentMethod().Name;
            string pageNamePrefix    = testName + "DynamicPage";
            string pageTitlePrefix   = testName + "Dynamic Page";
            string urlNamePrefix     = testName + "dynamic-page";
            int    index             = 1;
            string url               = UrlPath.ResolveAbsoluteUrl("~/" + urlNamePrefix + index);
            var    dynamicCollection = ServerOperationsFeather.DynamicModulePressArticle().RetrieveCollectionOfPressArticles();

            try
            {
                for (int i = 0; i < this.dynamicTitles.Length; i++)
                {
                    ServerOperationsFeather.DynamicModulePressArticle().CreatePressArticleItem(this.dynamicTitles[i], this.dynamicUrls[i]);
                }

                dynamicCollection = ServerOperationsFeather.DynamicModulePressArticle().RetrieveCollectionOfPressArticles();

                var mvcProxy = new MvcWidgetProxy();
                mvcProxy.ControllerName = typeof(DynamicContentController).FullName;
                var dynamicController = new DynamicContentController();
                dynamicController.Model.ContentType   = TypeResolutionService.ResolveType(ResolveType);
                dynamicController.Model.SelectionMode = SelectionMode.AllItems;
                mvcProxy.Settings   = new ControllerSettings(dynamicController);
                mvcProxy.WidgetName = WidgetName;

                this.pageOperations.CreatePageWithControl(mvcProxy, pageNamePrefix, pageTitlePrefix, urlNamePrefix, index);

                string responseContent = PageInvoker.ExecuteWebRequest(url);

                for (int i = 0; i < this.dynamicTitles.Length; i++)
                {
                    Assert.IsTrue(responseContent.Contains(this.dynamicTitles[i]), "The dynamic item with this title was not found!");
                }
            }
            finally
            {
                this.pageOperations.DeletePages();
                ServerOperationsFeather.DynamicModulePressArticle().DeleteDynamicItems(dynamicCollection);
                Telerik.Sitefinity.TestUtilities.CommonOperations.ServerOperations.Taxonomies().DeleteTags(this.tagTitle);
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Gets the template.
        /// </summary>
        /// <param name="isVirtualPath">The is virtual path.</param>
        /// <param name="isHtmlTemplate">The is HTML template.</param>
        /// <param name="layout">The layout.</param>
        /// <returns></returns>
        protected virtual ITemplate GetTemplate(bool isVirtualPath, bool isHtmlTemplate, string layout)
        {
            if (isVirtualPath && isHtmlTemplate)
            {
                if (!HostingEnvironment.VirtualPathProvider.FileExists(layout))
                {
                    throw new ArgumentException(Res.Get <InfrastructureResources>("CannotFindTemplateMvcForm", layout));
                }

                using (var reader = new StreamReader(HostingEnvironment.VirtualPathProvider.GetFile(layout).Open()))
                {
                    layout = reader.ReadToEnd();
                }
            }
            else if (isVirtualPath)
            {
                return(ControlUtilities.GetTemplate(layout, null, null, null));
            }
            else if (layout != null && layout.EndsWith(".ascx", StringComparison.Ordinal))
            {
                Type assemblyInfo;

                if (string.IsNullOrEmpty(this.AssemblyInfo))
                {
                    assemblyInfo = Config.Get <ControlsConfig>().ResourcesAssemblyInfo;
                }
                else
                {
                    assemblyInfo = TypeResolutionService.ResolveType(this.AssemblyInfo, true);
                }

                return(ControlUtilities.GetTemplate(null, layout, assemblyInfo, null));
            }

            // Add sf_cols wrapper for back end pages and email campaigns.
            var currentNode         = SiteMapBase.GetActualCurrentNode();
            var rootNode            = currentNode != null ? currentNode.RootNode as PageSiteNode : null;
            var ensureSfColsWrapper = this.IsBackend() || rootNode == null || rootNode.Id == NewslettersModule.standardCampaignRootNodeId ||
                                      System.Web.HttpContext.Current.Items[SiteMapBase.CurrentNodeKey] == null;

            layout = this.ProcessLayoutString(layout, ensureSfColsWrapper);

            return(ControlUtilities.GetTemplate(null, layout.GetHashCode().ToString(System.Globalization.CultureInfo.InvariantCulture), null, layout));
        }
        private MvcWidgetProxy CreateMvcWidget(string resolveType, string widgetName, string relatedFieldName = null, string relatedItemType = null, RelationDirection relationTypeToDisplay = RelationDirection.Child)
        {
            var mvcProxy = new MvcWidgetProxy();

            mvcProxy.ControllerName = typeof(DynamicContentController).FullName;
            var dynamicController = new DynamicContentController();

            dynamicController.Model.ContentType             = TypeResolutionService.ResolveType(resolveType);
            dynamicController.Model.RelatedFieldName        = relatedFieldName;
            dynamicController.Model.RelatedItemType         = relatedItemType;
            dynamicController.Model.RelationTypeToDisplay   = relationTypeToDisplay;
            dynamicController.Model.RelatedItemProviderName = FeatherWidgets.TestUtilities.CommonOperations.DynamicModulesOperations.ProviderName;
            dynamicController.Model.ProviderName            = FeatherWidgets.TestUtilities.CommonOperations.DynamicModulesOperations.ProviderName;

            mvcProxy.Settings   = new ControllerSettings(dynamicController);
            mvcProxy.WidgetName = widgetName;

            return(mvcProxy);
        }
Ejemplo n.º 15
0
        public void DynamicWidgets_ContentLocationService_SingleItemSelectedFromWidget()
        {
            int expectedLocationsCount;

            try
            {
                for (int i = 1; i <= 3; i++)
                {
                    ServerOperationsFeather.DynamicModuleBooking().CreateCountry(CountryName + i.ToString(CultureInfo.InvariantCulture));
                }

                Type countryType = TypeResolutionService.ResolveType(ResolveTypeCountry);

                DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager();
                var countryItemId = dynamicModuleManager.GetDataItems(countryType).Where("Title = \"" + CountryName + "1\"").First().Id;

                string[] itemIds = new string[] { countryItemId.ToString() };

                var pageId = ServerOperations.Pages().CreatePage(PageName);

                var countriesWidget = this.CreateMvcWidget(ResolveTypeCountry, WidgetNameCountries, itemIds);
                var controls        = new List <System.Web.UI.Control>();
                controls.Add(countriesWidget);

                PageContentGenerator.AddControlsToPage(pageId, controls);

                var locationsService     = SystemManager.GetContentLocationService();
                var dynamicItemLocations = locationsService.GetItemLocations(countryType, dynamicModuleManager.Provider.Name, countryItemId);

                expectedLocationsCount = 1;

                Assert.AreEqual(expectedLocationsCount, dynamicItemLocations.Count(), "Unexpected locations count");
            }
            finally
            {
                ServerOperations.Pages().DeleteAllPages();

                for (int i = 1; i <= 3; i++)
                {
                    ServerOperationsFeather.DynamicModuleBooking().DeleteCountry(CountryName + i.ToString(CultureInfo.InvariantCulture));
                }
            }
        }
Ejemplo n.º 16
0
        private IEnumerable <SocSkillMatrixContentItem> GetSocSkillMatrixRelatedItems(DynamicContent childLiveItem, List <Guid> parentItemLinks, DynamicModuleManager dynamicModuleManager, string parentName)
        {
            var relatedSocSkillMatrixContentItems = new List <SocSkillMatrixContentItem>();
            var parentType = TypeResolutionService.ResolveType(ParentType);

            var socSkillsMatrixContent = new SocSkillMatrixContentItem
            {
                Id                = dynamicContentExtensions.GetFieldValue <Guid>(childLiveItem, Constants.OriginalContentId),
                Title             = dynamicContentExtensions.GetFieldValue <Lstring>(childLiveItem, nameof(SocSkillMatrixContentItem.Title)),
                Contextualised    = dynamicContentExtensions.GetFieldValue <Lstring>(childLiveItem, nameof(SocSkillMatrixContentItem.Contextualised)),
                ONetAttributeType = dynamicContentExtensions.GetFieldValue <Lstring>(childLiveItem, nameof(SocSkillMatrixContentItem.ONetAttributeType)),
                ONetRank          = dynamicContentExtensions.GetFieldValue <decimal?>(childLiveItem, nameof(SocSkillMatrixContentItem.ONetRank)).GetValueOrDefault(0),
                Rank              = dynamicContentExtensions.GetFieldValue <decimal?>(childLiveItem, nameof(SocSkillMatrixContentItem.Rank)).GetValueOrDefault(0),
                RelatedSkill      = GetRelatedSkillsData(childLiveItem, nameof(SocSkillMatrixContentItem.RelatedSkill)),
                RelatedSOC        = GetRelatedSocsData(childLiveItem, nameof(SocSkillMatrixContentItem.RelatedSOC))
            };

            if (SkillsMatrixParentItems != null)
            {
                foreach (var contentId in SkillsMatrixParentItems)
                {
                    var parentItem = dynamicModuleManager.GetDataItem(parentType, contentId);
                    if ((parentItem.ApprovalWorkflowState == Constants.WorkflowStatusPublished || parentItem.ApprovalWorkflowState == Constants.WorkflowStatusDraft) && !parentItem.IsDeleted)
                    {
                        relatedSocSkillMatrixContentItems.Add(new SocSkillMatrixContentItem
                        {
                            Id                = dynamicContentExtensions.GetFieldValue <Guid>(childLiveItem, Constants.OriginalContentId),
                            Title             = socSkillsMatrixContent.Title,
                            Contextualised    = socSkillsMatrixContent.Contextualised,
                            ONetAttributeType = socSkillsMatrixContent.ONetAttributeType,
                            ONetRank          = socSkillsMatrixContent.ONetRank,
                            Rank              = socSkillsMatrixContent.Rank,
                            RelatedSkill      = socSkillsMatrixContent.RelatedSkill,
                            RelatedSOC        = socSkillsMatrixContent.RelatedSOC,
                            JobProfileId      = dynamicContentExtensions.GetFieldValue <Guid>(parentItem, nameof(SocCodeContentItem.Id)),
                            JobProfileTitle   = dynamicContentExtensions.GetFieldValue <Lstring>(parentItem, nameof(SocCodeContentItem.Title))
                        });
                    }
                }
            }

            return(relatedSocSkillMatrixContentItems);
        }
Ejemplo n.º 17
0
        private void GetIndividualClassificationsForSocCodeData(DynamicModuleManager manager, Type dynamicType, FlatTaxon taxon, string relatedPropertyName)
        {
            IOrganizableProvider contentProvider = manager.Provider as IOrganizableProvider;
            int?totalCount = -1;

            var socCodeIds = contentProvider.GetItemsByTaxon(taxon.Id, false, relatedPropertyName, dynamicType, null, null, 0, 0, ref totalCount)
                             .Cast <DynamicContent>()
                             .Select(p => p.Id)
                             .ToList();

            DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager(Constants.DynamicProvider);
            var classificationData  = new List <SOCCodeClassificationItem>();
            var contentLinksManager = ContentLinksManager.GetManager();
            var parentType          = TypeResolutionService.ResolveType(ParentType);

            foreach (var socCodeDataId in socCodeIds)
            {
                //Get JobProfile Item
                var relatedSocData = dynamicModuleManager.GetDataItem(dynamicType, socCodeDataId);

                if (relatedSocData.Status.ToString() == Constants.ItemStatusMaster)
                {
                    var socCodeClassificationItem = new SOCCodeClassificationItem
                    {
                        SOCCodeClassificationId = dynamicContentExtensions.GetFieldValue <Guid>(relatedSocData, nameof(SOCCodeClassificationItem.Id)),
                        SOCCode     = dynamicContentExtensions.GetFieldValue <Lstring>(relatedSocData, nameof(SOCCodeClassificationItem.SOCCode)),
                        Id          = taxon.Id,
                        Title       = taxon.Title,
                        Url         = taxon.UrlName,
                        Description = taxon.Description
                    };
                    var jobProfileId = contentLinksManager.GetContentLinks()
                                       .Where(c => c.ParentItemType == ParentType && c.ChildItemId == dynamicContentExtensions.GetFieldValue <Guid>(relatedSocData, nameof(SOCCodeClassificationItem.Id)))
                                       .Select(c => c.ParentItemId).FirstOrDefault();
                    var jobProfileItem = dynamicModuleManager.GetDataItem(parentType, jobProfileId);
                    socCodeClassificationItem.JobProfileId    = jobProfileItem.Id;
                    socCodeClassificationItem.JobProfileTitle = dynamicContentExtensions.GetFieldValue <Lstring>(jobProfileItem, nameof(SOCCodeClassificationItem.Title));
                    classificationData.Add(socCodeClassificationItem);
                }
            }

            serviceBusMessageProcessor.SendOtherRelatedTypeMessages(classificationData, taxon.FlatTaxonomy.Name.Trim(), GetActionType(taxon.Status.ToString()));
        }
        /// <summary>
        /// –азрешение типа на основе его описани¤ в синтаксическом дереве
        /// </summary>
        /// <param name="service"> онтекст разрешени¤ типа</param>
        public override Type Resolve(TypeResolutionService service)
        {
            var properties = new Dictionary<string, Type>();
            foreach (var member in service.Symbol.GetMembers())
            {
                var property = member as IPropertySymbol;
                if (property == null)
                {
                    continue;
                }

                var propertyType = service.Resolve(property.Type);
                var propertyName = property.Name;

                properties[propertyName] = propertyType;
            }

            return AnonymousTypeBuilder.Build(properties);
        }
Ejemplo n.º 19
0
        private string GetTemplate(out string fileName)
        {
            // Path is always relative to package root folder.
            // WARNING: if we were to copy our files and zip them, this may not work.
            TypeResolutionService resolver = GetService(typeof(ITypeResolutionService))
                                             as TypeResolutionService;

            if (resolver == null)
            {
                throw new ArgumentNullException("TypeResolutionService");
            }
            if (resolver.BasePath == null)
            {
                throw new ArgumentNullException("TypeResolutionService.BasePath");
            }
            fileName = new FileInfo(Path.Combine(
                                        resolver.BasePath, Template)).FullName;
            return(new StreamReader(fileName).ReadToEnd());
        }
        public void DynamicWidgetsAllTypes_VerifyAllFieldsOnTheFrontendWhereSomeFieldsAreEmpty()
        {
            this.pageOperations = new PagesOperations();
            string testName          = System.Reflection.MethodInfo.GetCurrentMethod().Name;
            string pageNamePrefix    = testName + "DynamicPage";
            string pageTitlePrefix   = testName + "Dynamic Page";
            string urlNamePrefix     = testName + "dynamic-page";
            int    index             = 1;
            string url               = UrlPath.ResolveAbsoluteUrl("~/" + urlNamePrefix + index);
            var    dynamicCollection = ServerOperationsFeather.DynamicModuleAllTypes().RetrieveCollectionOfAllFields();

            try
            {
                ServerOperationsFeather.DynamicModuleAllTypes().CreateFieldWithTitle(this.dynamicTitles, this.dynamicUrls);

                dynamicCollection = ServerOperationsFeather.DynamicModuleAllTypes().RetrieveCollectionOfAllFields();

                var mvcProxy = new MvcWidgetProxy();
                mvcProxy.ControllerName = typeof(DynamicContentController).FullName;
                var dynamicController = new DynamicContentController();
                dynamicController.Model.ContentType   = TypeResolutionService.ResolveType(ResolveType);
                dynamicController.Model.SelectionMode = SelectionMode.AllItems;
                dynamicController.Model.ProviderName  = FeatherWidgets.TestUtilities.CommonOperations.DynamicModulesOperations.ProviderName;
                mvcProxy.Settings   = new ControllerSettings(dynamicController);
                mvcProxy.WidgetName = WidgetName;

                this.pageOperations.CreatePageWithControl(mvcProxy, pageNamePrefix, pageTitlePrefix, urlNamePrefix, index);

                string responseContent = PageInvoker.ExecuteWebRequest(url);

                Assert.IsTrue(responseContent.Contains(this.dynamicTitles), "The dynamic item with this title was not found!");

                string detailNewsUrl         = url + dynamicCollection[0].ItemDefaultUrl;
                string detailResponseContent = PageInvoker.ExecuteWebRequest(detailNewsUrl);

                Assert.IsTrue(detailResponseContent.Contains(this.dynamicTitles), "The title was not found!");
            }
            finally
            {
                this.pageOperations.DeletePages();
                ServerOperationsFeather.DynamicModulePressArticle().DeleteDynamicItems(dynamicCollection);
            }
        }
        public override void CMD_provider(Arguments args, Guid rootId)
        {
            List <string> providers = new List <string>();

            var dynTypes = ModuleBuilderManager.GetManager().Provider.GetDynamicModuleTypes();
            MultisiteManager msManager = MultisiteManager.GetManager();
            var links = msManager.GetSiteDataSourceLinks();

            foreach (var datalink in links.Where(l => !l.DataSourceName.StartsWith("Telerik.Sitefinity.")))
            {
                if (dynTypes.Where(mt => mt.ModuleName == datalink.DataSourceName).FirstOrDefault() != null)
                {
                    providers.Add(ProviderName(datalink.ProviderName));
                }
            }

            // Displays the list of providers
            if (args.Count == 0)
            {
                string currentProvider = ProviderName(svc.Get_Provider());
                summary = string.Join("\n", providers.Select(provider => provider + (provider == currentProvider ? " <=" : "")));
                return;
            }

            // Selects a provider
            string newProvider = providers.Where(provider => provider.ToLower() == args.FirstKey).FirstOrDefault();

            if (newProvider == null)
            {
                svc.Set_Error("Invalid provider: " + args.FirstKey);
                return;
            }

            if (rootId != Guid.Empty)
            {
                var  dynType = ModuleBuilderManager.GetManager().Provider.GetDynamicModuleType(rootId);
                Type type    = TypeResolutionService.ResolveType(dynType.GetFullTypeName());
                svc.Set_Path(newProvider + " - " + type.FullName.Substring(38));
            }
            newProvider = newProvider == "Default" ? "OpenAccessProvider" : newProvider;
            svc.Set_Provider(newProvider);
        }
        public void CreateCountry()
        {
            DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager();
            Type           countryType = TypeResolutionService.ResolveType(HierarchicalDynamicContentTests.CountryType);
            DynamicContent countryItem = dynamicModuleManager.CreateDataItem(countryType, HierarchicalDynamicContentTests.CountryId, dynamicModuleManager.Provider.ApplicationName);

            countryItem.SetValue("Name", "Test country");
            countryItem.SetValue("Description", "Test Description");

            Address location = new Address();

            location.Latitude     = 0.00;
            location.Longitude    = 0.00;
            location.MapZoomLevel = 8;
            countryItem.SetValue("Location", location);

            LibrariesManager mainPictureManager = LibrariesManager.GetManager();
            var mainPictureItem = mainPictureManager.GetImages().FirstOrDefault(i => i.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Master);

            if (mainPictureItem != null)
            {
                countryItem.CreateRelation(mainPictureItem, "MainPicture");
            }

            countryItem.SetString("UrlName", "TestUrlName");
            countryItem.SetValue("Owner", SecurityManager.GetCurrentUserId());
            countryItem.SetValue("PublicationDate", DateTime.Now);
            countryItem.SetWorkflowStatus(dynamicModuleManager.Provider.ApplicationName, "Draft");

            dynamicModuleManager.SaveChanges();

            var actualCountry = dynamicModuleManager.GetDataItem(countryType, countryItem.Id);

            Assert.IsNotNull(actualCountry);
            Assert.AreEqual(countryItem.GetValue("Name").ToString(), actualCountry.GetValue("Name").ToString());
            Assert.AreEqual(countryItem.GetValue("Description").ToString(), actualCountry.GetValue("Description").ToString());
            Assert.AreEqual(countryItem.GetValue("Location"), actualCountry.GetValue("Location"));
            Assert.AreEqual(countryItem.GetValue("MainPicture"), actualCountry.GetValue("MainPicture"));
            Assert.AreEqual(countryItem.GetValue("UrlName").ToString(), actualCountry.GetValue("UrlName").ToString());
            Assert.AreEqual(countryItem.GetValue("Owner"), actualCountry.GetValue("Owner"));
            Assert.AreEqual(countryItem.GetValue("PublicationDate"), actualCountry.GetValue("PublicationDate"));
        }
 private static void RegisterAmazonService(string typeName)
 {
     try
     {
         var serviceType = TypeResolutionService.ResolveType(typeName, false);
         if (serviceType != null)
         {
             var service = Activator.CreateInstance(serviceType);
             if (service != null)
             {
                 ServiceBus.UnregisterService <ISearchService>();
                 ServiceBus.RegisterService <ISearchService>(service);
             }
         }
     }
     catch (Exception ex)
     {
         Log.Write(ex.InnerException.Message);
     }
 }
        private void OnPet_Updated(object sender, Telerik.Sitefinity.Data.ExecutingEventArgs e)
        {
            if (e.CommandName == "CommitTransaction" || e.CommandName == "FlushTransaction")
            {
                var provider   = sender as DynamicModuleDataProvider;
                var dirtyItems = provider.GetDirtyItems();

                if (dirtyItems.Count != 0)
                {
                    PetHelper petHelper = new PetHelper();
                    foreach (var item in dirtyItems)
                    {
                        if (item.GetType() == TypeResolutionService.ResolveType(petHelper.PetTypeString))
                        {
                            petHelper.FlushCache();
                        }
                    }
                }
            }
        }
 internal static void RegisterSearchService(string typeName, params object[] constructorArgs)
 {
     try
     {
         var serviceType = TypeResolutionService.ResolveType(typeName, false);
         if (serviceType != null)
         {
             var service = Activator.CreateInstance(serviceType, constructorArgs);
             if (service != null)
             {
                 ServiceBus.UnregisterService <ISearchService>();
                 ServiceBus.RegisterService <ISearchService>(service);
             }
         }
     }
     catch (Exception ex)
     {
         Log.Write(ex.InnerException.Message);
     }
 }
        public List <DynamicContent> RetrieveCollectionOfAllFields()
        {
            // Set the provider name for the DynamicModuleManager here. All available providers are listed in
            // Administration -> Settings -> Advanced -> DynamicModules -> Providers
            var providerName = string.Empty;

            if (ServerOperations.MultiSite().CheckIsMultisiteMode())
            {
                providerName = "dynamicContentProvider";
            }

            DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager(providerName);
            Type pressArticleType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.AllTypesModule.Alltypes");

            // This is how we get the collection of Press Article items
            var myCollection = dynamicModuleManager.GetDataItems(pressArticleType).ToList();

            //// At this point myCollection contains the items from type pressArticleType
            return(myCollection);
        }
Ejemplo n.º 27
0
        public void TestAssemblyLoad1()
        {
            AddTempFiles(1);

            using (StreamWriter sw = new StreamWriter((string)CodeFiles[0]))
            {
                sw.WriteLine(@"
	public class Test
	{
	}"    );
            }

            Compile(0);

            TypeResolutionService trs = new TypeResolutionService(Path.GetTempPath());
            Assembly asm = trs.GetAssembly(Common.ReflectionHelper.ParseAssemblyName(
                                               Path.GetFileNameWithoutExtension((string)AsmFiles[0])));

            Assert.IsNotNull(asm);
        }
        public ConferenceModel GetConferenceModelById(Guid id, string provider)
        {
            if (id == Guid.Empty)
            {
                return(null);
            }
            // Construct the cache key
            string cacheKey = CacheUtilities.BuildCacheKey(ConferenceSubControl.cacheKey, id.ToString());
            var    model    = (ConferenceModel)CacheUtilities.CacheManagerGlobal[cacheKey];

            if (model == null)
            {
                lock (this.nodeDataLock)
                {
                    model = (ConferenceModel)CacheUtilities.CacheManagerGlobal[cacheKey];
                    if (model == null)
                    {
                        // Get the conference item
                        DynamicModuleManager manager = DynamicModuleManager.GetManager(provider);
                        Type latestHotTopicsType     = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.Conferences.Conference");

                        DynamicContent conference = manager.GetDataItem(latestHotTopicsType, id);
                        // Build the Model
                        model = this.PopulateModel(conference);

                        // Add the model in the cache
                        CacheUtilities.CacheManagerGlobal.Add(
                            cacheKey,
                            model,
                            CacheItemPriority.Normal,
                            null,
                            // Add cache dependency for automatic invalidation
                            new DataItemCacheDependency(typeof(DynamicContent), id),
                            // Configure sliding time
                            new SlidingTime(TimeSpan.FromMinutes(20)));
                    }
                }
            }

            return(model);
        }
Ejemplo n.º 29
0
        private IEnumerable <SkillContentItem> GetRelatedSkillTypeItems(DynamicContent childItem, List <Guid> parentItemLinks, DynamicModuleManager dynamicModuleManager, string parentName)
        {
            //When you update a skill get all the socskill matrixes that have this skill
            var relatedContentItems = new List <SkillContentItem>();
            var socSkillsMatrixType = TypeResolutionService.ResolveType(SocSkillsMatrixType);
            var parentType          = TypeResolutionService.ResolveType(ParentType);

            dynamicModuleManager = DynamicModuleManager.GetManager(Constants.DynamicProvider);
            var contentLinksManager = ContentLinksManager.GetManager();

            foreach (var contentId in parentItemLinks)
            {
                var parentItem = dynamicModuleManager.GetDataItem(socSkillsMatrixType, contentId);
                if ((parentItem.ApprovalWorkflowState == Constants.WorkflowStatusPublished || parentItem.ApprovalWorkflowState == Constants.WorkflowStatusDraft) && !parentItem.IsDeleted)
                {
                    var jobProfileId = contentLinksManager.GetContentLinks()
                                       .Where(c => c.ParentItemType == ParentType && c.ChildItemId == parentItem.Id)
                                       .Select(c => c.ParentItemId).FirstOrDefault();
                    if (jobProfileId != Guid.Empty)
                    {
                        var jobProfileItem = dynamicModuleManager.GetDataItem(parentType, jobProfileId);
                        if (jobProfileItem.ApprovalWorkflowState == Constants.WorkflowStatusPublished && !jobProfileItem.IsDeleted)
                        {
                            relatedContentItems.Add(new SkillContentItem
                            {
                                JobProfileId    = dynamicContentExtensions.GetFieldValue <Guid>(jobProfileItem, nameof(SkillContentItem.Id)),
                                JobProfileTitle = dynamicContentExtensions.GetFieldValue <Lstring>(jobProfileItem, nameof(SkillContentItem.Title)),
                                Id                  = dynamicContentExtensions.GetFieldValue <Guid>(childItem, nameof(SkillContentItem.Id)),
                                Title               = dynamicContentExtensions.GetFieldValue <Lstring>(childItem, nameof(SkillContentItem.Title)),
                                ONetElementId       = dynamicContentExtensions.GetFieldValue <Lstring>(childItem, nameof(SkillContentItem.ONetElementId)),
                                SocSkillMatrixId    = dynamicContentExtensions.GetFieldValue <Guid>(parentItem, nameof(SkillContentItem.Id)),
                                SocSkillMatrixTitle = dynamicContentExtensions.GetFieldValue <Lstring>(parentItem, nameof(SkillContentItem.Title)),
                                Description         = dynamicContentExtensions.GetFieldValue <Lstring>(childItem, nameof(SkillContentItem.Description))
                            });
                        }
                    }
                }
            }

            return(relatedContentItems);
        }
Ejemplo n.º 30
0
        public bool DeleteVacanciesPermanently(int itemCount)
        {
            var lastDeleteCall = false;

            using (var recycleBinItemsManager = RecycleBinManagerFactory.GetManager())
            {
                SystemManager.RunWithElevatedPrivilege(d =>
                {
                    var recycleBinItems = recycleBinItemsManager
                                          .GetRecycleBinItems()
                                          .Where(di => di.DeletedItemTypeName.Equals(ApprenticeVacancyDeleteTypeName))
                                          .Take(itemCount)
                                          .ToList();

                    lastDeleteCall               = itemCount > recycleBinItems.Count;
                    var providerName             = DynamicModuleManager.GetDefaultProviderName(DynamicTypes.JobProfileModuleName);
                    var dynamicModuleContentType = TypeResolutionService.ResolveType(ApprenticeVacancyDeleteTypeName);
                    using (var dynamicModuleManager = DynamicModuleManager.GetManager(providerName))
                    {
                        foreach (var recycleBinItem in recycleBinItems)
                        {
                            try
                            {
                                var dataItem = dynamicModuleManager.GetItem(dynamicModuleContentType, recycleBinItem.DeletedItemId) as IRecyclableDataItem;
                                dynamicModuleManager.RecycleBin.PermanentlyDeleteFromRecycleBin(dataItem);
                            }
                            catch (ItemNotFoundException exception)
                            {
                                recycleBinItemsManager.Delete(recycleBinItem);
                                applicationLogger.Info($"Could not delete item :  {recycleBinItem.DeletedItemTitle}, failed with error {exception.Message}");
                                recycleBinItemsManager.SaveChanges();
                            }
                        }

                        dynamicModuleManager.SaveChanges();
                    }
                });
            }

            return(lastDeleteCall);
        }
        private void CreateAuthor(string[] values)
        {
            // Set the provider name for the DynamicModuleManager here. All available providers are listed in
            // Administration -> Settings -> Advanced -> DynamicModules -> Providers
            var providerName = String.Empty;

            string name     = values[6],
                   bio      = values[8],
                   jobTitle = values[7];
            DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager(providerName);

            //Suppress permission checks to ensure code runs even by unauthorized users
            dynamicModuleManager.Provider.SuppressSecurityChecks = true;

            Type           authorType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.Authors.Author");
            DynamicContent authorItem = dynamicModuleManager.CreateDataItem(authorType);

            // This is how values for the properties are set
            authorItem.SetValue("Name", name);
            authorItem.SetValue("Bio", bio);
            authorItem.SetValue("JobTitle", jobTitle);

            LibrariesManager avatarManager = LibrariesManager.GetManager();
            var avatarItem = avatarManager.GetImages().FirstOrDefault(i => i.Title == imageTitle && i.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Master);

            if (avatarItem == null)
            {
                CreateImage();
                avatarItem = avatarManager.GetImages().FirstOrDefault(i => i.Title == imageTitle && i.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Master);
            }
            // This is how we relate an item
            authorItem.CreateRelation(avatarItem, "Avatar");

            authorItem.SetString("UrlName", "SomeUrlName");
            authorItem.SetValue("Owner", SecurityManager.GetCurrentUserId());
            authorItem.SetValue("PublicationDate", DateTime.Now);
            authorItem.SetWorkflowStatus(dynamicModuleManager.Provider.ApplicationName, "Draft");

            // You need to call SaveChanges() in order for the items to be actually persisted to data store
            dynamicModuleManager.SaveChanges();
        }
        /// <inheritdoc />
        public override void AppendPersonalizationProperties(StringBuilder output, ControlData controlData, Type controlType, Guid pageDataId, out bool appendAllProperties)
        {
            if (typeof(MvcProxyBase).IsAssignableFrom(controlType))
            {
                appendAllProperties = true;

                var controllerName = controlData.Properties.Where(p => p.Name == "ControllerName" && p.Value != null)
                                     .Select(p => p.Value).FirstOrDefault();

                if (!controllerName.IsNullOrEmpty())
                {
                    controlType = TypeResolutionService.ResolveType(controllerName, throwOnError: false);
                }

                output.Append(string.Format(" ControlDataId=\"{0}\" ControlTypeName=\"{1}\" PageDataId=\"{2}\"", controlData.Id, controlType.FullName, pageDataId));
            }
            else
            {
                base.AppendPersonalizationProperties(output, controlData, controlType, pageDataId, out appendAllProperties);
            }
        }
Ejemplo n.º 33
0
        public static string GetWebResourceUrl(ScriptRef scriptReference)
        {
            var    config       = Config.Get <PagesConfig>().ScriptManager;
            var    scriptConfig = config.ScriptReferences[scriptReference.ToString()];
            string resourceUrl  = string.Empty;

            if (config.EnableCdn || (scriptConfig.EnableCdn.HasValue && scriptConfig.EnableCdn.Value))
            {
                resourceUrl = scriptConfig.Path;
            }
            else
            {
                var page = HttpContext.Current.Handler.GetPageHandler() ?? new PageProxy(null);

                resourceUrl = page.ClientScript.GetWebResourceUrl(
                    TypeResolutionService.ResolveType("Telerik.Sitefinity.Resources.Reference"),
                    scriptConfig.Name);
            }

            return(resourceUrl);
        }
        public Microsoft.Practices.RecipeFramework.GuidancePackage InitGuidancePackage(string packageXmlFilename)
        {
            string basePath = Directory.GetParent(packageXmlFilename).FullName + "\\";

            XmlReader configReader = XmlReader.Create(packageXmlFilename);
            //Microsoft.Practices.RecipeFramework.Configuration.GuidancePackage curentConfig = Microsoft.Practices.RecipeFramework.GuidancePackage.ReadConfiguration(configReader);
            //Microsoft.Practices.RecipeFramework.GuidancePackage curentGPckg = new Microsoft.Practices.RecipeFramework.GuidancePackage(curentConfig, basePath);

            Microsoft.Practices.RecipeFramework.GuidancePackage curentGPckg = new Microsoft.Practices.RecipeFramework.GuidancePackage(configReader);

            System.IServiceProvider sp = VsIdeTestHostContext.ServiceProvider;

            TypeResolutionService _trs = new TypeResolutionService(basePath);
            TestValueGatheringService _tvs = new TestValueGatheringService();
            TestPersistenceService _tps = new TestPersistenceService();

            DTE test = GetDTE();
            testContextInstance.WriteLine("Mode: " + test.Mode);

            //curentGPckg.SetupTemporaryService(typeof(EnvDTE.DTE), GetDTE());

            //curentGPckg.AddService(typeof(ITypeResolutionService), _trs);
            curentGPckg.AddService(typeof(EnvDTE.DTE), GetDTE());
            curentGPckg.AddService(typeof(IValueGatheringService), _tvs);
            curentGPckg.AddService(typeof(IPersistenceService), _tps);


            //curentGPckg.AddService(typeof(Microsoft.VisualStudio.OLE.Interop.IOleComponentManager), sp.GetService(typeof(Microsoft.VisualStudio.OLE.Interop.IOleComponentManager)));

            curentGPckg.Site = new Microsoft.Practices.ComponentModel.Site(sp, new Microsoft.Practices.RecipeFramework.RecipeManager(), "SharePointSoftwareFactory");
            //curentGPckg.Site = (en)sp.GetService(typeof(ISite));
            configReader.Close();
            testContextInstance.WriteLine("Site: " + curentGPckg.Site.GetType().ToString());
            //testContextInstance.WriteLine("Container: " + curentGPckg.Site.Container.GetType().ToString());
            //testContextInstance.WriteLine("Component: " + curentGPckg.Site.Component.GetType().ToString());

            return curentGPckg;
        }
Ejemplo n.º 35
0
 /// <summary>
 /// Определение возможноси разрешить тип
 /// </summary>
 /// <param name="service"></param>
 /// <returns></returns>
 public override bool CanResolve(TypeResolutionService service)
 {
     return service.Symbol is IArrayTypeSymbol;
 }
Ejemplo n.º 36
0
 /// <summary>
 /// Разрешение типа на основе его описания в синтаксическом дереве
 /// </summary>
 /// <param name="service">Контекст разрешения типа</param>
 public override Type Resolve(TypeResolutionService service)
 {
     var arrayType = service.Symbol as IArrayTypeSymbol;
     var itemType = service.Resolve(arrayType.ElementType);
     return itemType.MakeArrayType();
 }
Ejemplo n.º 37
0
 /// <summary>
 /// Определение возможноси разрешить тип
 /// </summary>
 /// <param name="service"></param>
 /// <returns></returns>
 public abstract bool CanResolve(TypeResolutionService service);
Ejemplo n.º 38
0
 /// <summary>
 /// Разрешение типа на основе его описания в синтаксическом дереве
 /// </summary>
 /// <param name="service">Контекст разрешения типа</param>
 public abstract Type Resolve(TypeResolutionService service);
Ejemplo n.º 39
0
		void UnloadDesigner()
		{
			LoggingService.Debug("FormsDesigner unloading, setting ActiveDesignSurface to null");
			designSurfaceManager.ActiveDesignSurface = null;
			
			bool savedIsDirty = (this.DesignerCodeFile == null) ? false : this.DesignerCodeFile.IsDirty;
			this.UserContent = this.pleaseWaitLabel;
			if (this.DesignerCodeFile != null) {
				this.DesignerCodeFile.IsDirty = savedIsDirty;
			}
			
			if (designSurface != null) {
				designSurface.Loading -= this.DesignerLoading;
				designSurface.Loaded -= this.DesignerLoaded;
				designSurface.Flushed -= this.DesignerFlushed;
				designSurface.Unloading -= this.DesignerUnloading;
				
				IComponentChangeService componentChangeService = designSurface.GetService(typeof(IComponentChangeService)) as IComponentChangeService;
				if (componentChangeService != null) {
					componentChangeService.ComponentChanged -= ComponentChanged;
					componentChangeService.ComponentAdded   -= ComponentListChanged;
					componentChangeService.ComponentRemoved -= ComponentListChanged;
					componentChangeService.ComponentRename  -= ComponentListChanged;
				}
				if (this.Host != null) {
					this.Host.TransactionClosed -= TransactionClose;
				}
				
				ISelectionService selectionService = designSurface.GetService(typeof(ISelectionService)) as ISelectionService;
				if (selectionService != null) {
					selectionService.SelectionChanged -= SelectionChangedHandler;
				}
				
				designSurface.Unloaded += delegate {
					ServiceContainer serviceContainer = designSurface.GetService(typeof(ServiceContainer)) as ServiceContainer;
					if (serviceContainer != null) {
						// Workaround for .NET bug: .NET unregisters the designer host only if no component throws an exception,
						// but then in a finally block assumes that the designer host is already unloaded.
						// Thus we would get the confusing "InvalidOperationException: The container cannot be disposed at design time"
						// when any component throws an exception.
						
						// See http://community.sharpdevelop.net/forums/p/10928/35288.aspx
						// Reproducible with a custom control that has a designer that crashes on unloading
						// e.g. http://www.codeproject.com/KB/toolbars/WinFormsRibbon.aspx
						
						// We work around this problem by unregistering the designer host manually.
						try {
							var services = (Dictionary<Type, object>)typeof(ServiceContainer).InvokeMember(
								"Services",
								BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.NonPublic,
								null, serviceContainer, null);
							foreach (var pair in services.ToArray()) {
								if (pair.Value is IDesignerHost) {
									serviceContainer.GetType().InvokeMember(
										"RemoveFixedService",
										BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic,
										null, serviceContainer, new object[] { pair.Key });
								}
							}
						} catch (Exception ex) {
							LoggingService.Error(ex);
						}
					}
				};
				try {
					designSurface.Dispose();
				} catch (ExceptionCollection exceptions) {
					foreach (Exception ex in exceptions.Exceptions) {
						LoggingService.Error(ex);
					}
				} finally {
					designSurface = null;
				}
			}
			
			this.typeResolutionService = null;
			this.loader = null;
			UpdatePropertyPad();
			
			foreach (KeyValuePair<Type, TypeDescriptionProvider> entry in this.addedTypeDescriptionProviders) {
				TypeDescriptor.RemoveProvider(entry.Value, entry.Key);
			}
			this.addedTypeDescriptionProviders.Clear();
		}
Ejemplo n.º 40
0
		void LoadDesigner()
		{
			LoggingService.Info("Form Designer: BEGIN INITIALIZE");
			
			DefaultServiceContainer serviceContainer = new DefaultServiceContainer();
			serviceContainer.AddService(typeof(System.Windows.Forms.Design.IUIService), new UIService());
			serviceContainer.AddService(typeof(System.Drawing.Design.IToolboxService), ToolboxProvider.ToolboxService);
			
			serviceContainer.AddService(typeof(IHelpService), new HelpService());
			serviceContainer.AddService(typeof(System.Drawing.Design.IPropertyValueUIService), new PropertyValueUIService());
			
			serviceContainer.AddService(typeof(System.ComponentModel.Design.IResourceService), new DesignerResourceService(this.resourceStore));
			AmbientProperties ambientProperties = new AmbientProperties();
			serviceContainer.AddService(typeof(AmbientProperties), ambientProperties);
			this.typeResolutionService = new TypeResolutionService(this.PrimaryFileName);
			serviceContainer.AddService(typeof(ITypeResolutionService), this.typeResolutionService);
			serviceContainer.AddService(typeof(DesignerOptionService), new SharpDevelopDesignerOptionService());
			serviceContainer.AddService(typeof(ITypeDiscoveryService), new TypeDiscoveryService());
			serviceContainer.AddService(typeof(MemberRelationshipService), new DefaultMemberRelationshipService());
			serviceContainer.AddService(typeof(ProjectResourceService), CreateProjectResourceService());
			
			// Provide the ImageResourceEditor for all Image and Icon properties
			this.addedTypeDescriptionProviders.Add(typeof(Image), TypeDescriptor.AddAttributes(typeof(Image), new EditorAttribute(typeof(ImageResourceEditor), typeof(System.Drawing.Design.UITypeEditor))));
			this.addedTypeDescriptionProviders.Add(typeof(Icon), TypeDescriptor.AddAttributes(typeof(Icon), new EditorAttribute(typeof(ImageResourceEditor), typeof(System.Drawing.Design.UITypeEditor))));
			
//			if (generator.CodeDomProvider != null) {
//				serviceContainer.AddService(typeof(System.CodeDom.Compiler.CodeDomProvider), generator.CodeDomProvider);
//			}
			
			designSurface = CreateDesignSurface(serviceContainer);
			designSurface.Loading += this.DesignerLoading;
			designSurface.Loaded += this.DesignerLoaded;
			designSurface.Flushed += this.DesignerFlushed;
			designSurface.Unloading += this.DesignerUnloading;
			
			serviceContainer.AddService(typeof(System.ComponentModel.Design.IMenuCommandService), new ICSharpCode.FormsDesigner.Services.MenuCommandService(this, designSurface));
			
			this.loader = loaderProvider.CreateLoader(this);
			designSurface.BeginLoad(this.loader);
			
			if (!designSurface.IsLoaded) {
				throw new FormsDesignerLoadException(FormatLoadErrors(designSurface));
			}
			
			undoEngine = new FormsDesignerUndoEngine(Host);
			serviceContainer.AddService(typeof(UndoEngine), undoEngine);
			
			IComponentChangeService componentChangeService = (IComponentChangeService)designSurface.GetService(typeof(IComponentChangeService));
			componentChangeService.ComponentChanged += ComponentChanged;
			componentChangeService.ComponentAdded   += ComponentListChanged;
			componentChangeService.ComponentRemoved += ComponentListChanged;
			componentChangeService.ComponentRename  += ComponentListChanged;
			this.Host.TransactionClosed += TransactionClose;
			
			ISelectionService selectionService = (ISelectionService)designSurface.GetService(typeof(ISelectionService));
			selectionService.SelectionChanged  += SelectionChangedHandler;
			
			if (IsTabOrderMode) { // fixes SD2-1015
				tabOrderMode = false; // let ShowTabOrder call the designer command again
				ShowTabOrder();
			}
			
			UpdatePropertyPad();
			
			hasUnmergedChanges = false;
			
			LoggingService.Info("Form Designer: END INITIALIZE");
		}
Ejemplo n.º 41
0
        /// <summary>
        /// Register the needed services
        /// </summary>
        /// <param name="services"></param>
        /// <param name="project"></param>
        private static void RegisterNeededServices(ServiceCollection services, IProject project)
        {
            ServiceCollection rootServices = ApplicationContext.Current.RootWorkItem.Services;

            rootServices.Add<IProjectContextService>(new SimpleProjectContextService(project));
            rootServices.AddNew<ProjectLocalizationService>();
            rootServices.Add<IPortalDeploymentService>(new PortalDeploymentService());

            ITypeResolutionService resService = new TypeResolutionService();
            services.Add(typeof(ITypeResolutionService), resService);
            services.Add(typeof(ITypeDiscoveryService), resService);
        }
 /// <summary>
 /// Определение возможноси разрешить тип
 /// </summary>
 /// <param name="service"></param>
 /// <returns></returns>
 public override bool CanResolve(TypeResolutionService service)
 {
     return service.Symbol.ContainingAssembly != null;
 }
Ejemplo n.º 43
0
 /// <summary>
 /// Определение возможноси разрешить тип
 /// </summary>
 /// <param name="service"></param>
 /// <returns></returns>
 public override bool CanResolve(TypeResolutionService service)
 {
     var named = service.Symbol as INamedTypeSymbol;
     return named != null && named.Arity > 0 && named.IsGenericType && !named.IsUnboundGenericType;
 }
 /// <summary>
 /// ќпределение возможноси разрешить тип
 /// </summary>
 /// <param name="service"></param>
 /// <returns></returns>
 public override bool CanResolve(TypeResolutionService service)
 {
     return service.Symbol.IsAnonymousType;
 }