Exemplo n.º 1
0
 public XmlExport(int zoneId, int appId, bool appExport)
 {
     _zoneId      = zoneId;
     _appId       = appId;
     _isAppExport = appExport;
     Sexy         = new SexyContent(_zoneId, _appId);
 }
Exemplo n.º 2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                return;
            }

            ApplicationId = Request["AppID"] != null?int.Parse(Request["AppID"]) : 0;

            var sexyContent = new SexyContent(ZoneId.Value, ApplicationId);

            Languages = sexyContent.ContentContext.GetLanguages()
                        .Where(language => language.Active)
                        .Select(language => language.ExternalKey)
                        .OrderBy(language => language != LanguageFallback)
                        .ThenBy(language => language)
                        .ToList();
            FileTemporaryDirectory = CreatePhysicalDirectory(SexyContent.TemporaryDirectory);

            ddlContentType.DataSource = sexyContent.GetAvailableAttributeSets(SexyContent.AttributeSetScope);
            ddlContentType.DataBind();

            rblEntityClear.DataSource = EnumToDataSource <EntityClearImport>();
            rblEntityClear.DataBind();
            rblEntityClear.SelectedValue = EntityClearImport.None.ToString();

            rblResourceReference.DataSource = EnumToDataSource <ResourceReferenceImport>();
            rblResourceReference.DataBind();
            rblResourceReference.SelectedValue = ResourceReferenceImport.Resolve.ToString();
        }
Exemplo n.º 3
0
 public ZipExport(int zoneId, int appId)
 {
     _appId = appId;
     _zoneId = zoneId;
     _sexy = new SexyContent(_zoneId, _appId);
     FileManager = new FileManager(_sexy.App.PhysicalPath);
 }
Exemplo n.º 4
0
        /// <summary>
        /// Initialize EAVManagement Control and add it to the page
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["ManagementMode"] == "NewItem" ||
                Request.QueryString["ManagementMode"] == "EditItem")
            {
                ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/ToSIC_SexyContent/SexyContent/EAV/Controls/ItemForm.js", 100);
                ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/ToSIC_SexyContent/SexyContent/EAV/AngularServices/EavGlobalConfigurationProvider.js", 101);
                ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/ToSIC_SexyContent/SexyContent/EAV/AngularServices/EavApiService.js", 102);
                ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/ToSIC_SexyContent/SexyContent/EAV/AngularServices/EavDialogService.js", 103);

                ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/ToSIC_SexyContent/SexyContent/EAV/Controls/ItemFormEntityModelCreator.js", 200);
                ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/ToSIC_SexyContent/Js/ItemForm.js", 300);
                ClientResourceManager.RegisterStyleSheet(this.Page, "~/DesktopModules/ToSIC_SexyContent/SexyContent/EAV/Controls/ItemForm.css", 150);
            }


            // Register Stylesheet & Script
            ClientResourceManager.RegisterStyleSheet(this.Page, "~/DesktopModules/ToSIC_SexyContent/Styles/Edit.css", 200);

            // Add DNN Version to body class
            SexyContent.AddDNNVersionToBodyClass(this);

            var eavManagement = (ToSic.Eav.ManagementUI.EavManagement)Page.LoadControl(TemplateControl.TemplateSourceDirectory + "/../SexyContent/EAV/Controls/EAVManagement.ascx");

            eavManagement.BaseUrl = DotNetNuke.Common.Globals.NavigateURL(TabId, SexyContent.ControlKeys.EavManagement, "mid=" + ModuleId.ToString() + "&popUp=true&" + "AppID=" + AppId.ToString());
            eavManagement.Scope   = SexyContent.AttributeSetScope;
            eavManagement.AssignmentObjectTypeId  = SexyContent.AssignmentObjectTypeIDDefault;
            eavManagement.DefaultCultureDimension = SexyContent.GetLanguageId(ZoneId.Value, PortalSettings.DefaultLanguage);
            eavManagement.ZoneId = ZoneId;
            eavManagement.AppId  = AppId;
            eavManagement.AddFormClientScriptAndCss = false;
            eavManagement.EntityDeleting           += EavManagementEntityDeleting;
            pnlEAV.Controls.Add(eavManagement);
        }
Exemplo n.º 5
0
        internal static SexyContent GetUncachedSxcOfModuleContext(this HttpRequestMessage request)
        {
            var moduleInfo = request.FindModuleInfo();
            var appId      = SexyContent.GetAppIdFromModule(moduleInfo);
            var zoneId     = SexyContent.GetZoneID(moduleInfo.PortalID);

            return(new SexyContent(zoneId.Value, appId.Value, false, moduleInfo.OwnerPortalID));
        }
Exemplo n.º 6
0
 protected void btnCreateApp_Click(object sender, EventArgs e)
 {
     if (!String.IsNullOrEmpty(hfNewAppName.Value))
     {
         SexyContent.AddApp(ZoneId.Value, hfNewAppName.Value, new PortalSettings(ModuleConfiguration.OwnerPortalID));
         Response.Redirect(Request.RawUrl);
     }
 }
        protected void UpdateModuleTitleIfNecessary(ToSic.Eav.Entity entity, ContentGroupItem groupItem)
        {
            // Creating new Context, because EntityTitle gets not refreshed otherwise
            var sexyContext = new SexyContent(ZoneId, AppId, true);

            // Get ContentGroup
            var listContentGroupItem = sexyContext.TemplateContext.GetListContentGroupItem(groupItem.ContentGroupID, UserId);
            var entityModel          = sexyContext.ContentContext.GetEntityModel(entity.EntityID);

            // If this is the list title, or no list-title exists, set module title
            if (groupItem.ItemType == ContentGroupItemType.ListContent || (listContentGroupItem == null && groupItem.ItemType == ContentGroupItemType.Content && groupItem.SortOrder == 0) && entityModel.IsPublished)
            {
                var languages = Sexy.ContentContext.GetLanguages();
                // Find Module for default language
                var moduleController = new ModuleController();
                var originalModule   = moduleController.GetModule(ModuleID);

                // Update Original Module if no languages active
                if (languages.Count == 0)
                {
                    // Get Title value of Entitiy in current language
                    string titleValue = entityModel.Title[0].ToString();

                    originalModule.ModuleTitle = titleValue;
                    moduleController.UpdateModule(originalModule);
                }

                foreach (var dimension in languages)
                {
                    // Get Title value of Entitiy in current language
                    string titleValue = entityModel.Title[dimension.DimensionID].ToString();

                    if (!originalModule.IsDefaultLanguage)
                    {
                        originalModule = originalModule.DefaultLanguageModule;
                    }

                    // Break if default language module is null
                    if (originalModule == null)
                    {
                        return;
                    }

                    // Find module for given Culture
                    var moduleByCulture = moduleController.GetModuleByCulture(originalModule.ModuleID, originalModule.TabID, PortalId, LocaleController.Instance.GetLocale(dimension.ExternalKey));

                    // Break if no module found
                    if (moduleByCulture == null)
                    {
                        return;
                    }

                    moduleByCulture.ModuleTitle = titleValue;
                    moduleController.UpdateModule(moduleByCulture);
                }
            }
        }
Exemplo n.º 8
0
 public XmlExporter(int zoneId, int appId, bool appExport, string[] attrSetIds, string[] entityIds)
 {
     _zoneId = zoneId;
     _appId = appId;
     _isAppExport = appExport;
     Sexy = new SexyContent(_zoneId, _appId);
     AttributeSetIDs = attrSetIds;
     EntityIDs = entityIds;
 }
Exemplo n.º 9
0
        protected void btnCreateZone_Click(object sender, EventArgs e)
        {
            var NewZone = SexyContent.AddZone(hfZoneName.Value);

            SexyContent.SetZoneID(NewZone.ZoneID, PortalId);
            BindZones();
            ddlZones.SelectedValue = NewZone.ZoneID.ToString();
            grdCultures.Rebind();
        }
Exemplo n.º 10
0
        public void DeleteApp(int zoneId, int appId)
        {
            if (zoneId != SexyContent.GetZoneID(this.PortalSettings.PortalId))
                throw new Exception("This app does not belong to portal " + this.PortalSettings.PortalId);

            var sexy = new SexyContent(zoneId, appId, false);
            var userId = PortalSettings.Current.UserId;
            sexy.RemoveApp(appId, userId);
        }
Exemplo n.º 11
0
        public object DeletePipeline(int appId, int id)
        {
            // Stop if a Template uses this Pipeline
            var sexy = new SexyContent(0, appId);
            var templatesUsingPipeline = sexy.Templates.GetAllTemplates().Where(t => t.Pipeline != null && t.Pipeline.EntityId == id).Select(t => t.TemplateId).ToArray();
            if (templatesUsingPipeline.Any())
                throw new Exception(string.Format("Pipeline is used by Templates and cant be deleted. Pipeline EntityId: {0}. TemplateIds: {1}", id, string.Join(", ", templatesUsingPipeline)));

            return _controller.DeletePipeline(appId, id);
        }
Exemplo n.º 12
0
        public object DeletePipeline(int appId, int id)
        {
            // Stop if a Template uses this Pipeline
            var sexy = new SexyContent(0, appId);
            var templatesUsingPipeline = sexy.TemplateContext.GetAllTemplates().Where(t => t.PipelineEntityID == id).Select(t => t.TemplateID).ToArray();

            if (templatesUsingPipeline.Any())
            {
                throw new Exception(string.Format("Pipeline is used by Templates and cant be deleted. Pipeline EntityId: {0}. TemplateIds: {1}", id, string.Join(", ", templatesUsingPipeline)));
            }

            return(_controller.DeletePipeline(appId, id));
        }
Exemplo n.º 13
0
 public IEnumerable <object> GetSelectableApps()
 {
     try
     {
         var zoneId = SexyContent.GetZoneID(ActiveModule.PortalID);
         return(SexyContent.GetApps(zoneId.Value, false, new PortalSettings(ActiveModule.OwnerPortalID)).Select(a => new { a.Name, a.AppId }));
     }
     catch (Exception e)
     {
         DotNetNuke.Services.Exceptions.Exceptions.LogException(e);
         throw e;
     }
 }
Exemplo n.º 14
0
        // note: not sure yet where the best place for this method is, so it's here for now
        // will probably move again some day
        internal static ValueCollectionProvider GetConfigProviderForModule(int moduleId, SexyContent.App app, SxcInstance sxc)
        {
            var portalSettings = PortalSettings.Current;

            var provider = new SxcValueCollectionProvider(sxc);

            // only add these in running inside an http-context. Otherwise leave them away!
            if (HttpContext.Current != null)
            {
                var request = HttpContext.Current.Request;

                // new
                NameValueCollection paramList = new NameValueCollection();
                if(sxc?.Parameters != null)
                    foreach (var pair in sxc.Parameters)
                        paramList.Add(pair.Key, pair.Value);
                else
                    paramList = request.QueryString;
                provider.Sources.Add("querystring", new FilteredNameValueCollectionPropertyAccess("querystring", paramList));
                // old
                // provider.Sources.Add("querystring", new FilteredNameValueCollectionPropertyAccess("querystring", request.QueryString));
                provider.Sources.Add("server", new FilteredNameValueCollectionPropertyAccess("server", request.ServerVariables));
                provider.Sources.Add("form", new FilteredNameValueCollectionPropertyAccess("form", request.Form));
            }

            // Add the standard DNN property sources if PortalSettings object is available
            if (portalSettings != null)
            {
                var dnnUsr = portalSettings.UserInfo;
                var dnnCult = Thread.CurrentThread.CurrentCulture;
                var dnn = new TokenReplaceDnn(app, moduleId, portalSettings, dnnUsr);
                var stdSources = dnn.PropertySources;
                foreach (var propertyAccess in stdSources)
                    provider.Sources.Add(propertyAccess.Key,
                        new ValueProviderWrapperForPropertyAccess(propertyAccess.Key, propertyAccess.Value, dnnUsr, dnnCult));
            }

            provider.Sources.Add("app", new AppPropertyAccess("app", app));

            // add module if it was not already added previously
            if (!provider.Sources.ContainsKey("module"))
            {
                var modulePropertyAccess = new StaticValueProvider("module");
                modulePropertyAccess.Properties.Add("ModuleID", moduleId.ToString(CultureInfo.InvariantCulture));
                provider.Sources.Add(modulePropertyAccess.Name, modulePropertyAccess);
            }
            return provider;
            //return _valueCollectionProvider;
        }
Exemplo n.º 15
0
        /// <summary>
        /// Bind the grid and set NavigateUrls's (for DotNetNuke Modal Window)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindGrdTemplates();
            }

            hlkNewTemplate.NavigateUrl = EditUrl(PortalSettings.ActiveTab.TabID, SexyContent.ControlKeys.EditTemplate, true, "mid=" + this.ModuleId + "&" + SexyContent.AppIDString + "=" + AppId);
            hlkCancel.NavigateUrl      = DotNetNuke.Common.Globals.NavigateURL(this.TabId, "", null);

            if (!SexyContent.SexyContentDesignersGroupConfigured(PortalId))
            {
                pnlSexyContentDesignersInfo.Visible = true;
            }
        }
Exemplo n.º 16
0
        public T CreateSource <T>(Eav.DataSources.IDataSource inSource = null, IConfigurationProvider configurationProvider = null)
        {
            if (configurationProvider == null)
            {
                configurationProvider = ConfigurationProvider;
            }

            if (inSource != null)
            {
                return(DataSource.GetDataSource <T>(inSource.ZoneId, inSource.AppId, inSource, configurationProvider));
            }

            var initialSource = SexyContent.GetInitialDataSource(SexyContent.GetZoneID(Dnn.Portal.PortalId).Value, App.AppId, SexyContent.HasEditPermission(Dnn.Module));

            return(DataSource.GetDataSource <T>(initialSource.ZoneId, initialSource.AppId, initialSource, configurationProvider));
        }
Exemplo n.º 17
0
        /// <summary>
        /// Create a xml import. The data stream passed will be imported to memory, and checked
        /// for errors. If no error could be found, the data can be persisted to the repository.
        /// </summary>
        /// <param name="zoneId">ID of 2SexyContent zone</param>
        /// <param name="applicationId">ID of 2SexyContent application</param>
        /// <param name="contentTypeId">ID of 2SexyContent type</param>
        /// <param name="dataStream">Xml data stream to import</param>
        /// <param name="languages">Languages that can be imported (2SexyContent languages enabled)</param>
        /// <param name="documentLanguageFallback">Fallback document language</param>
        /// <param name="entityClear">How to handle entities already in the repository</param>
        /// <param name="resourceReference">How value references to files and pages are handled</param>
        public XmlImport(int zoneId, int applicationId, int contentTypeId, Stream dataStream, IEnumerable <string> languages, string documentLanguageFallback, EntityClearImport entityClear, ResourceReferenceImport resourceReference)
        {
            this.Entities      = new List <Entity>();
            this.ErrorProtocol = new ImportErrorProtocol();

            this.applicationId            = applicationId;
            this.zoneId                   = zoneId;
            this.contentManager           = new SexyContent(zoneId, applicationId);
            this.contentType              = contentManager.ContentContext.GetAttributeSet(contentTypeId);
            this.languages                = languages;
            this.documentLanguageFallback = documentLanguageFallback;
            this.entityClear              = entityClear;
            this.resourceReference        = resourceReference;

            ValidateAndImportToMemory(dataStream);
        }
Exemplo n.º 18
0
        protected void Page_Load(object sender, EventArgs e)
        {
            ServicesFramework.Instance.RequestAjaxAntiForgerySupport();

            var gettingStartedSrc = "http://gettingstarted.2sexycontent.org/router.aspx?";

            // Add desired destination
            gettingStartedSrc += "destination=" + (ModuleConfiguration.DesktopModule.ModuleName == "2sxc" ? "autoconfigurecontent" : "autoconfigureapp");

            // Add DNN Version
            gettingStartedSrc += "&DnnVersion=" + Assembly.GetAssembly(typeof(DotNetNuke.Common.Globals)).GetName().Version.ToString(4);
            // Add 2SexyContent Version
            gettingStartedSrc += "&2SexyContentVersion=" + SexyContent.ModuleVersion;
            // Add module type
            gettingStartedSrc += "&ModuleName=" + ModuleConfiguration.DesktopModule.ModuleName;
            // Add module id
            gettingStartedSrc += "&ModuleId=" + ModuleID;
            // Add Portal ID
            gettingStartedSrc += "&PortalID=" + PortalId.ToString();
            // Add VDB / Zone ID (if set)
            var ZoneID = SexyContent.GetZoneID(PortalId);

            gettingStartedSrc += ZoneID.HasValue ? "&ZoneID=" + ZoneID.Value.ToString() : "";
            // Add AppStaticName and Version
            if (AppId.HasValue && !IsContentApp)
            {
                var app = SexyContent.GetApp(ZoneId.Value, AppId.Value, Sexy.OwnerPS);

                gettingStartedSrc += "&AppGuid=" + app.AppGuid;
                if (app.Configuration != null)
                {
                    gettingStartedSrc += "&AppVersion=" + app.Configuration.Version;
                    gettingStartedSrc += "&AppOriginalId=" + app.Configuration.OriginalId;
                }
            }
            // Add DNN Guid
            var HostSettings = HostController.Instance.GetSettingsDictionary();

            gettingStartedSrc += HostSettings.ContainsKey("GUID") ? "&DnnGUID=" + HostSettings["GUID"].ToString() : "";
            // Add Portal Default Language
            gettingStartedSrc += "&DefaultLanguage=" + PortalSettings.DefaultLanguage;
            // Add current language
            gettingStartedSrc += "&CurrentLanguage=" + PortalSettings.CultureCode;

            // Set src to iframe
            frGettingStarted.Attributes["src"] = gettingStartedSrc;
        }
Exemplo n.º 19
0
        /// <summary>
        /// Handles the control load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            // Add DNN Version to body Class
            SexyContent.AddDNNVersionToBodyClass(this);

            // Bind Languages Repeater
            var Languages = Sexy.ContentContext.GetLanguages().Where(l => l.Active).OrderByDescending(l => l.DimensionID == DefaultLanguageID).ThenBy(l => l.ExternalKey);

            if (Languages.Count() == 0)
            {
                pnlDimensionNav.Visible = false;
            }
            rptDimensions.DataSource = Languages;
            rptDimensions.DataBind();

            btnDelete.OnClientClick = "return confirm('" + LocalizeString("btnDelete.Confirm") + "')";
            btnDelete.Text          = Items.Count(p => p.ItemType == ContentGroupItemType.Content) > 1 ? LocalizeString("btnDelete.ListText") : LocalizeString("btnDelete.Text");
            btnDelete.Visible       = !NewMode && ContentGroupID.HasValue;

            // If there is something to edit
            if (CurrentlyEditedItems.Any())
            {
                // Settings link (to change content)
                hlkChangeContent.NavigateUrl = Sexy.GetElementSettingsLink(CurrentlyEditedItems.First().ContentGroupItemID, ModuleId, TabId, Request.RawUrl);

                // Show Change Content or Reference Link only if this is the default language
                var IsDefaultLanguage = LanguageID == DefaultLanguageID;
                hlkChangeContent.Visible = !NewMode && IsDefaultLanguage && (CurrentlyEditedItems.First().ItemType == ContentGroupItemType.Content || CurrentlyEditedItems.First().ItemType == ContentGroupItemType.ListContent);
            }

            // Show message if language is not active
            if (!Sexy.ContentContext.HasLanguages() || (LanguageID.HasValue && Sexy.ContentContext.GetDimension(LanguageID.Value).Active))
            {
                ProcessView();
            }
            else
            {
                pnlActions.Visible           = false;
                pnlLanguageNotActive.Visible = true;
                litLanguageName.Text         = LocaleController.Instance.GetLocale(System.Threading.Thread.CurrentThread.CurrentCulture.Name).Text;
                if (UserInfo.IsInRole(PortalSettings.AdministratorRoleName))
                {
                    btnActivateLanguage.Visible = true;
                }
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Returns the available Zones (VDB's) for the current user.
        /// Host users can see all zones, while Administrators may only
        /// see the current zone, if specified.
        /// </summary>
        private List <Zone> GetAvailableZones()
        {
            if (PortalSettings.UserInfo.IsSuperUser && !CurrentZoneID.HasValue)
            {
                return(SexyContent.GetZones());
            }

            if (CurrentZoneID.HasValue)
            {
                return new List <Zone> {
                           SexyContent.GetZones().Single(z => z.ZoneID == CurrentZoneID.Value)
                }
            }
            ;

            return(new List <Zone>());
        }
Exemplo n.º 21
0
        public void Init(Template template, App app, ModuleInfo hostingModule, IDataSource dataSource, InstancePurposes instancePurposes, SexyContent sexy)
        {
            var templatePath = VirtualPathUtility.Combine(SexyContent.GetTemplatePathRoot(template.Location, app) + "/", template.Path);

            // Throw Exception if Template does not exist
            if (!File.Exists(HostingEnvironment.MapPath(templatePath)))
                throw new SexyContentException("The template file '" + templatePath + "' does not exist.");

            Template = template;
            TemplatePath = templatePath;
            App = app;
            ModuleInfo = hostingModule;
            DataSource = dataSource;
            InstancePurposes = instancePurposes;
            Sexy = sexy;

            Init();
        }
Exemplo n.º 22
0
        /// <summary>
        /// Creates an app and then imports the xml
        /// </summary>
        /// <param name="xml"></param>
        /// <returns>AppId of the new imported app</returns>
        public bool ImportApp(int zoneId, string xml, out int?appId)
        {
            // Increase script timeout to prevent timeouts
            HttpContext.Current.Server.ScriptTimeout = 300;

            appId = new int?();

            // Parse XDocument from string
            XDocument doc = XDocument.Parse(xml);

            if (!IsCompatible(doc))
            {
                ImportLog.Add(new ExportImportMessage("The import file is not compatible with the installed version of 2sxc.", ExportImportMessage.MessageTypes.Error));
                return(false);
            }

            // Get root node "SexyContent"
            XElement xmlSource = doc.Element("SexyContent");
            var      xApp      = xmlSource.Element("Header").Element("App");

            // Build Guid (take existing, or create a new)
            var appGuid = xApp.Attribute("Guid").Value;

            if (String.IsNullOrEmpty(appGuid) || appGuid == new Guid().ToString())
            {
                appGuid = Guid.NewGuid().ToString();
            }

            // Adding app to EAV
            var sexy = new SexyContent(zoneId, SexyContent.GetDefaultAppId(zoneId));
            var app  = sexy.ContentContext.AddApp(appGuid);

            sexy.ContentContext.SaveChanges();

            appId = app.AppID;

            if (!appId.HasValue || appId <= 0)
            {
                ImportLog.Add(new ExportImportMessage("App was not created. Please try again or make sure the package you are importing is correct.", ExportImportMessage.MessageTypes.Error));
                return(false);
            }

            return(ImportXml(zoneId, app.AppID, xml));
        }
Exemplo n.º 23
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Correct Local Resource File
            var ResourceFile = DotNetNuke.Common.Globals.ResolveUrl("~/DesktopModules/ToSIC_SexyContent/Administration/App_LocalResources/Registers.ascx.resx");

            var ParentModule = (SexyControlAdminBase)Parent;

            var Registers = new List <string>();

            Registers.Add(SexyContent.ControlKeys.GettingStarted);

            // Add Buttons if ZoneID is set
            if (SexyContent.GetZoneID(ParentModule.PortalId).HasValue)
            {
                Registers.Add(SexyContent.ControlKeys.EavManagement);
                Registers.Add(SexyContent.ControlKeys.ManageTemplates);

                if (!ParentModule.IsContentApp)
                {
                    Registers.Add(SexyContent.ControlKeys.WebApiHelp);
                }

                Registers.Add(SexyContent.ControlKeys.Import);
            }

            if (ParentModule.IsContentApp)
            {
                Registers.Add(SexyContent.ControlKeys.PortalConfiguration);
            }
            else
            {
                Registers.Add(SexyContent.ControlKeys.AppConfig);
            }

            rptRegisters.DataSource = from c in Registers
                                      select new {
                Name = DotNetNuke.Services.Localization.Localization.GetString(c + ".Text", ResourceFile),
                Key  = c,
                Url  = ParentModule.EditUrl(ParentModule.TabId, c, true, "mid=" + ParentModule.ModuleId +
                                            (String.IsNullOrEmpty(Request.QueryString[SexyContent.AppIDString]) ? "" : "&" + SexyContent.AppIDString + "=" + Request.QueryString[SexyContent.AppIDString])),
                Active = Request.QueryString["ctl"].ToLower() == c.ToLower()
            };
            rptRegisters.DataBind();
        }
Exemplo n.º 24
0
        /// <summary>
        /// GridView DeleteCommand, deletes the app that caused the command
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grdApps_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            if (hfAppNameToDelete.Value == "")
                return;

            var item = grdApps.Items[e.CommandArgument.ToString()];
            var appId = (int) item.GetDataKeyValue("AppId");

            //int appId = Convert.ToInt32(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["AppId"]);
            var sexy = new SexyContent(ZoneId.Value, appId, false);

            if (sexy.App.Name == hfAppNameToDelete.Value)
            {
                sexy.RemoveApp(appId, UserId);
                grdApps.Rebind();
            }

            hfAppNameToDelete.Value = "";
        }
Exemplo n.º 25
0
        public void Init(Template template, App app, ModuleInfo hostingModule, IDataSource dataSource, InstancePurposes instancePurposes, SexyContent sexy)
        {
            var templatePath = VirtualPathUtility.Combine(SexyContent.GetTemplatePathRoot(template.Location, app) + "/", template.Path);

            // Throw Exception if Template does not exist
            if (!System.IO.File.Exists(HostingEnvironment.MapPath(templatePath)))
            {
                throw new SexyContentException("The template file '" + templatePath + "' does not exist.");
            }

            Template         = template;
            TemplatePath     = templatePath;
            App              = app;
            ModuleInfo       = hostingModule;
            DataSource       = dataSource;
            InstancePurposes = instancePurposes;
            Sexy             = sexy;

            this.Init();
        }
Exemplo n.º 26
0
        /// <summary>
        /// needed to initialize data - must always happen a bit later because the show-draft info isn't available when creating the first App-object.
        /// todo: later this should be moved to initialization of this object
        /// </summary>
        /// <param name="showDrafts"></param>
        internal void InitData(bool showDrafts)
        {
            // ToDo: Remove this as soon as App.Data getter on App class is fixed #1 and #2
            if (_data == null)
            {
                // ModulePermissionController does not work when indexing, return false for search
                var initialSource = SexyContent.GetInitialDataSource(ZoneId, AppId, showDrafts);

                _data = ToSic.Eav.DataSource.GetDataSource <ToSic.SexyContent.DataSources.App>(initialSource.ZoneId,
                                                                                               initialSource.AppId, initialSource, initialSource.ConfigurationProvider);
                var defaultLanguage = "";
                var languagesActive = SexyContent.GetCulturesWithActiveState(OwnerPS.PortalId, ZoneId).Any(c => c.Active);
                if (languagesActive)
                {
                    defaultLanguage = OwnerPS.DefaultLanguage;
                }
                Data.DefaultLanguage = defaultLanguage;
                Data.CurrentUserName = OwnerPS.UserInfo.Username;
            }
        }
Exemplo n.º 27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                return;
            }

            ApplicationId = Request["AppID"] != null?int.Parse(Request["AppID"]) : 0;

            var sexyContent = new SexyContent(ZoneId.Value, ApplicationId);

            LanguageFallback = PortalSettings.DefaultLanguage;
            Languages        = sexyContent.ContentContext.GetLanguages()
                               .Where(language => language.Active)
                               .Select(language => language.ExternalKey)
                               .OrderBy(language => language != LanguageFallback)
                               .ThenBy(language => language)
                               .ToList();

            ddlLanguage.DataSource = Languages;
            ddlLanguage.DataBind();

            ddlContentType.DataSource = sexyContent.GetAvailableAttributeSets(SexyContent.AttributeSetScope);
            ddlContentType.DataBind();

            rblRecordExport.DataSource = EnumToDataSource <RecordExport>();
            rblRecordExport.DataBind();
            rblRecordExport.SelectedValue = RecordExport.All.ToString();

            rblLanguageMissing.DataSource = EnumToDataSource <LanguageMissingExport>();
            rblLanguageMissing.DataBind();
            rblLanguageMissing.SelectedValue = LanguageMissingExport.Create.ToString();

            rblLanguageReference.DataSource = EnumToDataSource <LanguageReferenceExport>();
            rblLanguageReference.DataBind();
            rblLanguageReference.SelectedValue = LanguageReferenceExport.Link.ToString();

            rblResourceReference.DataSource = EnumToDataSource <ResourceReferenceExport>();
            rblResourceReference.DataBind();
            rblResourceReference.SelectedValue = ResourceReferenceExport.Link.ToString();
        }
Exemplo n.º 28
0
        /// <summary>
        /// GridView DeleteCommand, deletes the app that caused the command
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grdApps_DeleteCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            if (hfAppNameToDelete.Value == "")
            {
                return;
            }

            var item  = grdApps.Items[e.CommandArgument.ToString()];
            var appId = (int)item.GetDataKeyValue("AppId");

            //int appId = Convert.ToInt32(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["AppId"]);
            var sexy = new SexyContent(ZoneId.Value, appId, false);

            if (sexy.App.Name == hfAppNameToDelete.Value)
            {
                sexy.RemoveApp(appId, UserId);
                grdApps.Rebind();
            }

            hfAppNameToDelete.Value = "";
        }
Exemplo n.º 29
0
        public AppAndDataHelpers(SexyContent sexy, ModuleInfo module, ViewDataSource data, App app)
        {
            _sexy = sexy;
            App   = app;
            Data  = data;
            Dnn   = new DnnHelper(module);
            List  = new List <Element>();

            if (data != null)
            {
                if (data.Out.ContainsKey("Default"))
                {
                    var entities = data.List.Select(e => e.Value);
                    var elements = entities.Select(GetElementFromEntity).ToList();
                    List = elements;

                    if (elements.Any())
                    {
                        Content      = elements.First().Content;
                        Presentation = elements.First().Presentation;
                    }
                }

                if (data.Out.ContainsKey("ListContent"))
                {
                    var listEntity  = data["ListContent"].List.Select(e => e.Value).FirstOrDefault();
                    var listElement = listEntity != null?GetElementFromEntity(listEntity) : null;

                    if (listElement != null)
                    {
                        ListContent      = listElement.Content;
                        ListPresentation = listElement.Presentation;
                    }
                }
            }

            // If PortalSettings is null - for example, while search index runs - HasEditPermission would fail
            // But in search mode, it shouldn't show drafts, so this is ok.
            App.InitData(PortalSettings.Current != null && SexyContent.HasEditPermission(module));
        }
Exemplo n.º 30
0
        public HttpResponseMessage InstallPackage(string packageUrl)
        {
            var  zoneId = SexyContent.GetZoneID(ActiveModule.PortalID);
            var  appId  = SexyContent.GetAppIdFromModule(ActiveModule);
            bool success;

            // Install package
            var messages = new List <ExportImportMessage>();

            try
            {
                success = new ZipImport(zoneId.Value, appId, PortalSettings.UserInfo.IsSuperUser).ImportZipFromUrl(
                    packageUrl, messages, ActiveModule.DesktopModule.ModuleName == "2sxc-app");
            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "An error occurred while installing the app: " + ex.Message, ex));
            }

            return(Request.CreateResponse(success ? HttpStatusCode.OK : HttpStatusCode.InternalServerError, new { success, messages }));
        }
Exemplo n.º 31
0
        public void SetAppId(int?appId)
        {
            // Reset template to nothing (prevents errors after changing app)
            SexyUncached.UpdateTemplateForGroup(Sexy.GetContentGroupIdFromModule(ActiveModule.ModuleID), null, UserInfo.UserID);

            SexyContent.SetAppIdForModule(ActiveModule, appId);

            // Change to 1. template if app has been set
            if (appId.HasValue)
            {
                var sexyForNewApp = new SexyContent(Sexy.App.ZoneId, appId.Value, false);
                var templates     = sexyForNewApp.GetAvailableTemplatesForSelector(ActiveModule).ToList();
                if (templates.Any())
                {
                    SexyUncached.UpdateTemplateForGroup(Sexy.GetContentGroupIdFromModule(ActiveModule.ModuleID), templates.First().TemplateID, UserInfo.UserID);
                }
                else
                {
                    SexyUncached.UpdateTemplateForGroup(Sexy.GetContentGroupIdFromModule(ActiveModule.ModuleID), null, UserInfo.UserID);
                }
            }
        }
Exemplo n.º 32
0
        public HttpControllerDescriptor SelectController(HttpRequestMessage request)
        {
            IHttpRouteData routeData = request.GetRouteData();
            var            module    = request.FindModuleInfo();

            if (routeData.Route.RouteTemplate.Contains("DesktopModules/2sxc/API/App/") && module.DesktopModule.ModuleName == "2sxc-app")
            {
                var portalSettings = DotNetNuke.Entities.Portals.PortalSettings.Current;
                var sexy           = request.GetSxcOfModuleContext();

                if ((string)routeData.Values["appFolder"] != "auto-detect-app" && (string)routeData.Values["appFolder"] != sexy.App.Folder)
                {
                    throw new HttpException("AppFolder was not correct - was " + routeData.Values["appFolder"] + " but should be " + sexy.App.Folder);
                }

                var controllerTypeName = routeData.Values["controller"] + "Controller";

                var controllerPath = Path.Combine(SexyContent.AppBasePath(portalSettings), sexy.App.Folder,
                                                  "Api/" + controllerTypeName + ".cs");

                if (File.Exists(System.Web.Hosting.HostingEnvironment.MapPath(controllerPath)))
                {
                    var assembly = BuildManager.GetCompiledAssembly(controllerPath);
                    var type     = assembly.GetType(controllerTypeName);
                    return(new HttpControllerDescriptor(_config, controllerTypeName, type));
                }
                else
                {
                    throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound, "Controller " + controllerTypeName + " not found in app."));
                }
            }
            else
            {
                return(PreviousSelector.SelectController(request));
            }
        }
Exemplo n.º 33
0
        /// <summary>
        /// Imports a ZIP file (from stream)
        /// </summary>
        /// <param name="zipStream"></param>
        /// <param name="server"></param>
        /// <param name="portalSettings"></param>
        /// <param name="messages"></param>
        /// <returns></returns>
        public bool ImportZip(Stream zipStream, HttpServerUtility server, PortalSettings portalSettings, List <ExportImportMessage> messages, bool isAppImport)
        {
            if (!isAppImport && !_appId.HasValue)
            {
                throw new Exception("Could not import zip: No valid app id");
            }

            if (messages == null)
            {
                messages = new List <ExportImportMessage>();
            }

            var temporaryDirectory = server.MapPath(Path.Combine(SexyContent.TemporaryDirectory, System.Guid.NewGuid().ToString()));
            var success            = true;

            try
            {
                if (!Directory.Exists(temporaryDirectory))
                {
                    Directory.CreateDirectory(temporaryDirectory);
                }

                // Extract ZIP archive to the temporary folder
                ExtractZipFile(zipStream, temporaryDirectory);

                string   currentWorkingDir = temporaryDirectory;
                string[] baseDirectories   = Directory.GetDirectories(currentWorkingDir);

                // Loop through each root-folder. For now only contains the "Apps" folder.
                foreach (var directoryPath in baseDirectories)
                {
                    switch (Path.GetFileName(directoryPath))
                    {
                    // Handle the App folder
                    case "Apps":
                        currentWorkingDir = Path.Combine(currentWorkingDir, "Apps");

                        // Loop through each app directory
                        foreach (var appDirectory in Directory.GetDirectories(currentWorkingDir))
                        {
                            var appId            = new int?();
                            var xmlSearchPattern = isAppImport ? "App.xml" : "*.xml";

                            // Stores the number of the current xml file to process
                            var xmlIndex = 0;

                            // Import XML file(s)
                            foreach (var xmlFileName in Directory.GetFiles(appDirectory, "*.xml"))
                            {
                                var fileContents = File.ReadAllText(Path.Combine(appDirectory, xmlFileName));
                                var import       = new XmlImport();

                                if (isAppImport)
                                {
                                    if (!import.IsCompatible(_zoneId, fileContents))
                                    {
                                        throw new Exception("The " + (isAppImport ? "app" : "package") + " is not compatible with this version of 2sxc.");
                                    }

                                    var folder =
                                        XDocument.Parse(fileContents).Element("SexyContent")
                                        .Element("Entities").Elements("Entity").Single(e => e.Attribute("AttributeSetStaticName").Value == "2SexyContent-App")
                                        .Elements("Value").First(v => v.Attribute("Key").Value == "Folder").Attribute("Value").Value;
                                    var appPath = System.IO.Path.Combine(SexyContent.AppBasePath(PortalSettings.Current), folder);

                                    // Do not import (throw error) if the app directory already exists
                                    if (Directory.Exists(HttpContext.Current.Server.MapPath(appPath)))
                                    {
                                        throw new Exception("The app could not be installed because the app-folder '" + appPath + "' already exists. Please remove or rename the folder and install the app again.");
                                    }

                                    if (xmlIndex == 0)
                                    {
                                        // Handle PortalFiles folder
                                        string portalTempRoot = Path.Combine(appDirectory, "PortalFiles");
                                        if (Directory.Exists(portalTempRoot))
                                        {
                                            CopyAllFilesDnnPortal(portalTempRoot, "", false, messages);
                                        }
                                    }

                                    import.ImportApp(_zoneId, fileContents, out appId);
                                }
                                else
                                {
                                    appId = _appId.Value;
                                    if (xmlIndex == 0 && import.IsCompatible(_zoneId, fileContents))
                                    {
                                        // Handle PortalFiles folder
                                        string portalTempRoot = Path.Combine(appDirectory, "PortalFiles");
                                        if (Directory.Exists(portalTempRoot))
                                        {
                                            CopyAllFilesDnnPortal(portalTempRoot, "", false, messages);
                                        }
                                    }

                                    import.ImportXml(_zoneId, appId.Value, fileContents);
                                }


                                messages.AddRange(import.ImportLog);

                                xmlIndex++;
                            }

                            var sexy = new SexyContent(_zoneId, appId.Value);

                            // Copy all files in 2sexy folder to (portal file system) 2sexy folder
                            string templateRoot    = server.MapPath(SexyContent.GetTemplatePathRoot(SexyContent.TemplateLocations.PortalFileSystem, sexy.App));
                            string appTemplateRoot = Path.Combine(appDirectory, "2sexy");
                            if (Directory.Exists(appTemplateRoot))
                            {
                                ImportExportHelpers.CopyAllFiles(appTemplateRoot, templateRoot, false, messages);
                            }
                        }

                        // Reset CurrentWorkingDir
                        currentWorkingDir = temporaryDirectory;
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                // Add error message and return false
                messages.Add(new ExportImportMessage("Could not import the " + (isAppImport ? "app" : "package") + ": " + e.Message, ExportImportMessage.MessageTypes.Error));
                Exceptions.LogException(e);
                success = false;
            }
            finally
            {
                try
                {
                    // Finally delete the temporary directory
                    Directory.Delete(temporaryDirectory, true);
                }
                catch (IOException e)
                {
                    // The folder itself or files inside may be used by other processes.
                    // Deleting the folder recursively will fail in such cases
                    // If deleting is not possible, just leave the temporary folder as it is
                }
            }

            return(success);
        }
Exemplo n.º 34
0
 public void SwitchLanguage(string cultureCode, bool enable)
 {
     // Activate or Deactivate the Culture
     var portalId = PortalSettings.PortalId;
     var zoneId = SexyContent.GetZoneID(portalId);
     var cache = DataSource.GetCache(zoneId.Value);
     var sexy = new SexyContent(zoneId.Value, cache.AppId);
     sexy.SetCultureState(cultureCode, enable, PortalSettings.PortalId);
 }
Exemplo n.º 35
0
 private string GetPath(int zoneId, int appId)
 {
     var sexy = new SexyContent(zoneId, appId);
     return sexy.App.Path;
 }
Exemplo n.º 36
0
        /// <summary>
        /// Do the import
        /// </summary>
        /// <param name="xml">The previously exported XML</param>
        /// <returns></returns>
        public bool ImportXml(int zoneId, int appId, string xml)
        {
            _sexy   = new SexyContent(zoneId, appId, false);
            _appId  = appId;
            _zoneId = zoneId;

            // Parse XDocument from string
            XDocument doc = XDocument.Parse(xml);

            if (!IsCompatible(doc))
            {
                ImportLog.Add(new ExportImportMessage("The import file is not compatible with the installed version of 2sxc.", ExportImportMessage.MessageTypes.Error));
                return(false);
            }

            // Get root node "SexyContent"
            XElement xmlSource = doc.Element("SexyContent");

            PrepareFileIdCorrectionList(xmlSource);

            #region Prepare dimensions
            _sourceDimensions = xmlSource.Element("Header").Element("Dimensions").Elements("Dimension").Select(p => new Dimension()
            {
                DimensionID = int.Parse(p.Attribute("DimensionID").Value),
                Name        = p.Attribute("Name").Value,
                SystemKey   = p.Attribute("SystemKey").Value,
                ExternalKey = p.Attribute("ExternalKey").Value,
                Active      = Boolean.Parse(p.Attribute("Active").Value)
            }).ToList();

            _sourceDefaultLanguage    = xmlSource.Element("Header").Element("Language").Attribute("Default").Value;
            _sourceDefaultDimensionId = _sourceDimensions.Any() ?
                                        _sourceDimensions.FirstOrDefault(p => p.ExternalKey == _sourceDefaultLanguage).DimensionID
                : new int?();

            _targetDimensions = _sexy.ContentContext.GetDimensionChildren("Culture");
            if (_targetDimensions.Count == 0)
            {
                _targetDimensions.Add(new Dimension()
                {
                    Active      = true,
                    ExternalKey = PortalSettings.Current.DefaultLanguage,
                    Name        = "(added by import System, default language " + PortalSettings.Current.DefaultLanguage + ")",
                    SystemKey   = "Culture"
                });
            }
            #endregion

            var importAttributeSets = GetImportAttributeSets(xmlSource.Element("AttributeSets").Elements("AttributeSet"));
            var importEntities      = GetImportEntities(xmlSource.Elements("Entities").Elements("Entity"), SexyContent.AssignmentObjectTypeIDDefault);

            var import = new ToSic.Eav.Import.Import(_zoneId, _appId, PortalSettings.Current.UserInfo.DisplayName);
            import.RunImport(importAttributeSets, importEntities, true, true);
            ImportLog.AddRange(GetExportImportMessagesFromImportLog(import.ImportLog));

            if (xmlSource.Elements("Templates").Any())
            {
                if (_sexy.TemplateContext.Connection.State != ConnectionState.Open)
                {
                    _sexy.TemplateContext.Connection.Open();
                }
                var           transaction = _sexy.TemplateContext.Connection.BeginTransaction();
                List <Entity> templateDescribingEntities;
                ImportXmlTemplates(xmlSource, out templateDescribingEntities);

                var import2 = new ToSic.Eav.Import.Import(_zoneId, _appId, PortalSettings.Current.UserInfo.DisplayName);
                import2.RunImport(new List <AttributeSet>(), templateDescribingEntities, true, true);
                ImportLog.AddRange(GetExportImportMessagesFromImportLog(import2.ImportLog));

                transaction.Commit();
            }

            return(true);
        }
Exemplo n.º 37
0
 /// <summary>
 /// Common constructor, directly preparing it with 2sxc
 /// </summary>
 /// <param name="sexy"></param>
 public Serializer(SexyContent sexy)
 {
     Sxc = sexy;
 }
Exemplo n.º 38
0
        /// <summary>
        /// Imports a ZIP file (from stream)
        /// </summary>
        /// <param name="zipStream"></param>
        /// <param name="server"></param>
        /// <param name="portalSettings"></param>
        /// <param name="messages"></param>
        /// <returns></returns>
        public bool ImportZip(Stream zipStream, HttpServerUtility server, PortalSettings portalSettings, List<ExportImportMessage> messages)
        {
            if (messages == null)
                messages = new List<ExportImportMessage>();

            var temporaryDirectory = server.MapPath(Path.Combine(SexyContent.TemporaryDirectory, Guid.NewGuid().ToString()));
            var success = true;

            try
            {
                if (!Directory.Exists(temporaryDirectory))
                    Directory.CreateDirectory(temporaryDirectory);

                // Extract ZIP archive to the temporary folder
                ExtractZipFile(zipStream, temporaryDirectory);

                var currentWorkingDir = temporaryDirectory;
                var baseDirectories = Directory.GetDirectories(currentWorkingDir);

                // Loop through each root-folder. For now only contains the "Apps" folder.
                foreach (var directoryPath in baseDirectories)
                {
                    switch (Path.GetFileName(directoryPath))
                    {
                        // Handle the App folder
                        case "Apps":
                            currentWorkingDir = Path.Combine(currentWorkingDir, "Apps");

                            // Loop through each app directory
                            foreach (var appDirectory in Directory.GetDirectories(currentWorkingDir))
                            {

                                var appId = new int?();

                                // Stores the number of the current xml file to process
                                var xmlIndex = 0;

                                // Import XML file(s)
                                foreach (var xmlFileName in Directory.GetFiles(appDirectory, "*.xml"))
                                {
                                    var fileContents = File.ReadAllText(Path.Combine(appDirectory, xmlFileName));
                                    var doc = XDocument.Parse(fileContents);
                                    var import = new XmlImport(PortalSettings.Current.DefaultLanguage, PortalSettings.Current.UserInfo.Username);

                                    if (!import.IsCompatible(doc))
                                        throw new Exception("The app / package is not compatible with this version of 2sxc.");

                                    var isAppImport = doc.Element("SexyContent").Element("Header").Elements("App").Any() && doc.Element("SexyContent").Element("Header").Element("App").Attribute("Guid").Value != "Default";

                                    if (!isAppImport && !_appId.HasValue)
                                        _appId = ((BaseCache) DataSource.GetCache(_zoneId)).ZoneApps[_zoneId].DefaultAppId;

                                    if (isAppImport)
                                    {
                                        var folder =
                                            XDocument.Parse(fileContents).Element("SexyContent")
                                                .Element("Entities").Elements("Entity").Single(e =>e.Attribute("AttributeSetStaticName").Value =="2SexyContent-App")
                                                .Elements("Value").First(v => v.Attribute("Key").Value == "Folder").Attribute("Value").Value;
                                        var appPath = Path.Combine(SexyContent.AppBasePath(PortalSettings.Current), folder);

                                        // Do not import (throw error) if the app directory already exists
                                        if(Directory.Exists(HttpContext.Current.Server.MapPath(appPath)))
                                        {
                                            throw new Exception("The app could not be installed because the app-folder '" + appPath + "' already exists. Please remove or rename the folder and install the app again.");
                                        }

                                        if (xmlIndex == 0)
                                        {
                                            // Handle PortalFiles folder
                                            var portalTempRoot = Path.Combine(appDirectory, "PortalFiles");
                                            if (Directory.Exists(portalTempRoot))
                                                CopyAllFilesDnnPortal(portalTempRoot, "", false, messages);
                                        }

                                        import.ImportApp(_zoneId, doc, out appId);
                                    }
                                    else
                                    {
                                        appId = _appId.Value;
                                        if (xmlIndex == 0 && import.IsCompatible(doc))
                                        {
                                            // Handle PortalFiles folder
                                            var portalTempRoot = Path.Combine(appDirectory, "PortalFiles");
                                            if (Directory.Exists(portalTempRoot))
                                                CopyAllFilesDnnPortal(portalTempRoot, "", false, messages);
                                        }

                                        import.ImportXml(_zoneId, appId.Value, doc);
                                    }

                                    messages.AddRange(import.ImportLog);

                                    xmlIndex++;
                                }

                                var sexy = new SexyContent(_zoneId, appId.Value);

                                // Copy all files in 2sexy folder to (portal file system) 2sexy folder
                                var templateRoot = server.MapPath(SexyContent.GetTemplatePathRoot(SexyContent.TemplateLocations.PortalFileSystem, sexy.App));
                                var appTemplateRoot = Path.Combine(appDirectory, "2sexy");
                                if (Directory.Exists(appTemplateRoot))
                                    (new FileManager(appTemplateRoot)).CopyAllFiles(templateRoot, false, messages);

                            }

                            // Reset CurrentWorkingDir
                            currentWorkingDir = temporaryDirectory;
                            break;
                    }
                }
            }
            catch (Exception e)
            {
                // Add error message and return false
                messages.Add(new ExportImportMessage("Could not import the app / package: " + e.Message, ExportImportMessage.MessageTypes.Error));
                Exceptions.LogException(e);
                success = false;
            }
            finally
            {
                try
                {
                    // Finally delete the temporary directory
                    Directory.Delete(temporaryDirectory, true);
                }
                catch(IOException e)
                {
                    // The folder itself or files inside may be used by other processes.
                    // Deleting the folder recursively will fail in such cases
                    // If deleting is not possible, just leave the temporary folder as it is
                }
            }

            return success;
        }
Exemplo n.º 39
0
        /// <summary>
        /// Do the import
        /// </summary>
        public bool ImportXml(int zoneId, int appId, XDocument doc, bool leaveExistingValuesUntouched = true)
        {
            _sexy = new SexyContent(zoneId, appId, false);
            _appId = appId;
            _zoneId = zoneId;

            if (!IsCompatible(doc))
            {
                ImportLog.Add(new ExportImportMessage("The import file is not compatible with the installed version of 2sxc.", ExportImportMessage.MessageTypes.Error));
                return false;
            }

            // Get root node "SexyContent"
            var xmlSource = doc.Element("SexyContent");
            PrepareFileIdCorrectionList(xmlSource);

            #region Prepare dimensions
            _sourceDimensions = xmlSource.Element("Header").Element("Dimensions").Elements("Dimension").Select(p => new Dimension
            {
                DimensionID = int.Parse(p.Attribute("DimensionID").Value),
                Name = p.Attribute("Name").Value,
                SystemKey = p.Attribute("SystemKey").Value,
                ExternalKey = p.Attribute("ExternalKey").Value,
                Active = Boolean.Parse(p.Attribute("Active").Value)
            }).ToList();

            _sourceDefaultLanguage = xmlSource.Element("Header").Element("Language").Attribute("Default").Value;
            _sourceDefaultDimensionId = _sourceDimensions.Any() ?
                _sourceDimensions.FirstOrDefault(p => p.ExternalKey == _sourceDefaultLanguage).DimensionID
                : new int?();

            _targetDimensions = _sexy.ContentContext.Dimensions.GetDimensionChildren("Culture");
            if (_targetDimensions.Count == 0)
                _targetDimensions.Add(new Dimension
                {
                    Active = true,
                    ExternalKey = DefaultLanguage,
                    Name = "(added by import System, default language " + DefaultLanguage + ")",
                    SystemKey = "Culture"
                });
            #endregion

            var importAttributeSets = GetImportAttributeSets(xmlSource.Element("AttributeSets").Elements("AttributeSet"));
            var importEntities = GetImportEntities(xmlSource.Elements("Entities").Elements("Entity"), SexyContent.AssignmentObjectTypeIDDefault);

            var import = new Eav.Import.Import(_zoneId, _appId, UserName, leaveExistingValuesUntouched);
            import.RunImport(importAttributeSets, importEntities);
            ImportLog.AddRange(GetExportImportMessagesFromImportLog(import.ImportLog));

            if (xmlSource.Elements("Templates").Any())
                ImportXmlTemplates(xmlSource);

            return true;
        }
Exemplo n.º 40
0
        //public bool IsCompatible(string xml)
        //{
        //    // Parse XDocument from string
        //    var doc = XDocument.Parse(xml);
        //    return IsCompatible(doc);
        //}
        /// <summary>
        /// Creates an app and then imports the xml
        /// </summary>
        /// <param name="xml"></param>
        /// <returns>AppId of the new imported app</returns>
        public bool ImportApp(int zoneId, XDocument doc, out int? appId)
        {
            // Increase script timeout to prevent timeouts
            HttpContext.Current.Server.ScriptTimeout = 300;

            appId = new int?();

            // Parse XDocument from string
            //var doc = XDocument.Parse(xml);

            if (!IsCompatible(doc))
            {
                ImportLog.Add(new ExportImportMessage("The import file is not compatible with the installed version of 2sxc.", ExportImportMessage.MessageTypes.Error));
                return false;
            }

            // Get root node "SexyContent"
            var xmlSource = doc.Element("SexyContent");
            var xApp = xmlSource.Element("Header").Element("App");

            var appGuid = xApp.Attribute("Guid").Value;

            if (appGuid != "Default")
            {
                // Build Guid (take existing, or create a new)
                if (String.IsNullOrEmpty(appGuid) || appGuid == new Guid().ToString())
                {
                    appGuid = Guid.NewGuid().ToString();
                }

                // Adding app to EAV
                var sexy = new SexyContent(zoneId, SexyContent.GetDefaultAppId(zoneId));
                var app = sexy.ContentContext.App.AddApp(appGuid);
                sexy.ContentContext.SqlDb.SaveChanges();

                appId = app.AppID;
            }
            else
            {
                appId = this._appId;
            }

            if (!appId.HasValue || appId <= 0)
            {
                ImportLog.Add(new ExportImportMessage("App was not created. Please try again or make sure the package you are importing is correct.", ExportImportMessage.MessageTypes.Error));
                return false;
            }

            return ImportXml(zoneId, appId.Value, doc);
        }
Exemplo n.º 41
0
        public IList<SearchDocument> GetModifiedSearchDocuments(ModuleInfo moduleInfo, DateTime beginDate)
        {
            var searchDocuments = new List<SearchDocument>();

            var isContentModule = moduleInfo.DesktopModule.ModuleName == "2sxc";

            // New Context because PortalSettings.Current is null
            var zoneId = SexyContent.GetZoneID(moduleInfo.OwnerPortalID);

            if (!zoneId.HasValue)
                return searchDocuments;

            int? appId = SexyContent.GetDefaultAppId(zoneId.Value);

            if (!isContentModule)
            {
                appId = SexyContent.GetAppIdFromModule(moduleInfo);
                if (!appId.HasValue)
                    return searchDocuments;
            }

            var sexy = new SexyContent(zoneId.Value, appId.Value, true, moduleInfo.OwnerPortalID);
            var language = moduleInfo.CultureCode;
            var contentGroup = sexy.ContentGroups.GetContentGroupForModule(moduleInfo.ModuleID);
            var template = contentGroup.Template;

            // This list will hold all EAV entities to be indexed
            var dataSource = sexy.GetViewDataSource(moduleInfo.ModuleID, false, template);

            if (template == null)
                return searchDocuments;

            var engine = EngineFactory.CreateEngine(template);
            engine.Init(template, sexy.App, moduleInfo, dataSource, InstancePurposes.IndexingForSearch, sexy);

            try
            {
                engine.CustomizeData();
            }
            catch (Exception e) // Catch errors here, because of references to Request etc.
            {
                Exceptions.LogException(new SearchIndexException(moduleInfo, e));
            }

            var searchInfoDictionary = new Dictionary<string, List<ISearchInfo>>();

            // Get DNN SearchDocuments from 2Sexy SearchInfos
            foreach (var stream in dataSource.Out.Where(p => p.Key != "Presentation" && p.Key != "ListPresentation" ))
            {

                var entities = stream.Value.List.Select(p => p.Value);
                var searchInfoList = searchInfoDictionary[stream.Key] = new List<ISearchInfo>();

                searchInfoList.AddRange(entities.Select(entity =>
                {
                    var searchInfo = new SearchInfo
                    {
                        Entity = entity,
                        Url = "",
                        Description = "",
                        Body = GetJoinedAttributes(entity, language),
                        Title = entity.Title != null ? entity.Title[language].ToString() : "(no title)",
                        ModifiedTimeUtc = (entity.Modified == DateTime.MinValue ? DateTime.Now.Date.AddHours(DateTime.Now.Hour) : entity.Modified).ToUniversalTime(),
                        UniqueKey = "2sxc-" + moduleInfo.ModuleID + "-" + (entity.EntityGuid != new Guid() ? entity.EntityGuid.ToString() : (stream.Key + "-" + entity.EntityId)),
                        IsActive = true,
                        TabId = moduleInfo.TabID,
                        PortalId = moduleInfo.PortalID
                    };

                    // Take the newest value (from ContentGroupItem and Entity)
                    if (entity is IHasEditingData)
                    {
                        var contentGroupItemModifiedUtc = ((IHasEditingData) entity).ContentGroupItemModified.ToUniversalTime();
                        searchInfo.ModifiedTimeUtc = searchInfo.ModifiedTimeUtc > contentGroupItemModifiedUtc
                            ? searchInfo.ModifiedTimeUtc
                            : contentGroupItemModifiedUtc;
                    }

                    return searchInfo;
                }));
            }

            try
            {
                engine.CustomizeSearch(searchInfoDictionary, moduleInfo, beginDate);
            }
            catch (Exception e)
            {
                Exceptions.LogException(new SearchIndexException(moduleInfo, e));
            }

            foreach (var searchInfoList in searchInfoDictionary)
            {
                // Filter by Date - take only SearchDocuments that changed since beginDate
                var searchDocumentsToAdd = searchInfoList.Value.Where(p => p.ModifiedTimeUtc >= beginDate.ToUniversalTime()).Select(p => (SearchDocument) p);

                searchDocuments.AddRange(searchDocumentsToAdd);
            }

            return searchDocuments;
        }
Exemplo n.º 42
0
 public ZipExport(int zoneId, int appId)
 {
     _appId  = appId;
     _zoneId = zoneId;
     _sexy   = new SexyContent(_zoneId, _appId);
 }
Exemplo n.º 43
0
        public MemoryStream ExportApp()
        {
            // Get Export XML
            var attributeSets = _sexy.GetAvailableAttributeSets(SexyContent.AttributeSetScope).ToList();

            attributeSets.AddRange(_sexy.GetAvailableAttributeSets(SexyContent.AttributeSetScopeApps));
            attributeSets = attributeSets.Where(a => !a.UsesConfigurationOfAttributeSet.HasValue).ToList();

            // Special case: Entities of the template attributesets and field properties should not be exported here
            //var templateAttributeSets = _sexy.GetAvailableAttributeSets().Where(a => a.StaticName == SexyContent.AttributeSetStaticNameTemplateContentTypes
            //                    || a.StaticName == SexyContent.AttributeSetStaticNameTemplateMetaData
            //                    || a.StaticName.StartsWith("@"));

            var attributeSetIds = attributeSets.Select(p => p.AttributeSetId.ToString()).ToArray();
            var entities        = SexyContent.GetInitialDataSource(_zoneId, _appId).Out["Default"].List;
            var entityIds       = entities.Where(e => e.Value.AssignmentObjectTypeId != SexyContent.AssignmentObjectTypeIDSexyContentTemplate &&
                                                 e.Value.AssignmentObjectTypeId != DataSource.AssignmentObjectTypeIdFieldProperties)
                                  .Select(e => e.Value.EntityId.ToString()).ToArray();

            var templateIds = _sexy.GetTemplates(PortalSettings.Current.PortalId).Select(p => p.TemplateID.ToString()).ToArray();
            var messages    = new List <ExportImportMessage>();
            var xmlExport   = new XmlExport(_zoneId, _appId, true);
            var xml         = xmlExport.ExportXml(attributeSetIds, entityIds, templateIds, out messages);

            #region Copy needed files to temporary directory

            var temporaryDirectoryPath = HttpContext.Current.Server.MapPath(Path.Combine(SexyContent.TemporaryDirectory, System.Guid.NewGuid().ToString()));

            if (!Directory.Exists(temporaryDirectoryPath))
            {
                Directory.CreateDirectory(temporaryDirectoryPath);
            }

            var tempDirectory        = new DirectoryInfo(temporaryDirectoryPath);
            var appDirectory         = tempDirectory.CreateSubdirectory("Apps/" + _sexy.App.Folder + "/");
            var sexyDirectory        = appDirectory.CreateSubdirectory("2sexy");
            var portalFilesDirectory = appDirectory.CreateSubdirectory("PortalFiles");

            // Copy app folder
            if (Directory.Exists(_sexy.App.PhysicalPath))
            {
                ImportExportHelpers.CopyAllFiles(_sexy.App.PhysicalPath, sexyDirectory.FullName, false, messages);
            }

            // Copy PortalFiles
            foreach (var file in xmlExport.ReferencedFiles)
            {
                var portalFilePath = Path.Combine(portalFilesDirectory.FullName, Path.GetDirectoryName(file.RelativePath.Replace('/', '\\')));

                if (!Directory.Exists(portalFilePath))
                {
                    Directory.CreateDirectory(portalFilePath);
                }

                File.Copy(file.PhysicalPath, Path.Combine(portalFilesDirectory.FullName, file.RelativePath.Replace('/', '\\')));
            }

            // Save export xml
            File.AppendAllText(System.IO.Path.Combine(appDirectory.FullName, "App.xml"), xml);

            #endregion

            // Zip directory and return as stream
            var stream    = new MemoryStream();
            var zipStream = new ZipOutputStream(stream);
            zipStream.SetLevel(6);
            ZipFolder(tempDirectory.FullName + "\\", tempDirectory.FullName + "\\", zipStream);
            zipStream.Finish();

            tempDirectory.Delete(true);

            return(stream);
        }
Exemplo n.º 44
0
        public IList <SearchDocument> GetModifiedSearchDocuments(ModuleInfo moduleInfo, DateTime beginDate)
        {
            var searchDocuments = new List <SearchDocument>();

            var isContentModule = moduleInfo.DesktopModule.ModuleName == "2sxc";

            // New Context because PortalSettings.Current is null
            var zoneId = SexyContent.GetZoneID(moduleInfo.OwnerPortalID);

            if (!zoneId.HasValue)
            {
                return(searchDocuments);
            }

            var appId = SexyContent.GetDefaultAppId(zoneId.Value);

            if (!isContentModule)
            {
                // Get AppId from ModuleSettings
                var appIdString = moduleInfo.ModuleSettings[SexyContent.AppIDString];
                if (appIdString == null || !int.TryParse(appIdString.ToString(), out appId))
                {
                    return(searchDocuments);
                }
            }

            var sexy     = new SexyContent(zoneId.Value, appId, true, moduleInfo.OwnerPortalID);
            var language = moduleInfo.CultureCode;
            var template = sexy.GetTemplateForModule(moduleInfo.ModuleID);

            // This list will hold all EAV entities to be indexed
            var dataSource = sexy.GetViewDataSource(moduleInfo.ModuleID, false, template);

            if (template == null)
            {
                return(searchDocuments);
            }

            var engine = EngineFactory.CreateEngine(template);

            engine.Init(template, sexy.App, moduleInfo, dataSource, InstancePurposes.IndexingForSearch, sexy);

            try
            {
                engine.CustomizeData();
            }
            catch (Exception e) // Catch errors here, because of references to Request etc.
            {
                Exceptions.LogException(new SearchIndexException(moduleInfo, e));
            }


            var searchInfoDictionary = new Dictionary <string, List <ISearchInfo> >();

            // Get DNN SearchDocuments from 2Sexy SearchInfos
            foreach (var stream in dataSource.Out.Where(p => p.Key != "Presentation" && p.Key != "ListPresentation"))
            {
                var entities       = stream.Value.List.Select(p => p.Value);
                var searchInfoList = searchInfoDictionary[stream.Key] = new List <ISearchInfo>();

                searchInfoList.AddRange(entities.Select(entity =>
                {
                    var searchInfo = new SearchInfo()
                    {
                        Entity          = entity,
                        Url             = "",
                        Description     = "",
                        Body            = GetJoinedAttributes(entity, language),
                        Title           = entity.Title[language].ToString(),
                        ModifiedTimeUtc = (entity.Modified == DateTime.MinValue ? DateTime.Now.Date.AddHours(DateTime.Now.Hour) : entity.Modified).ToUniversalTime(),
                        UniqueKey       = "2sxc-" + moduleInfo.ModuleID + "-" + (entity.EntityGuid != new Guid() ? entity.EntityGuid.ToString() : (stream.Key + "-" + entity.EntityId)),
                        IsActive        = true,
                        TabId           = moduleInfo.TabID,
                        PortalId        = moduleInfo.PortalID
                    };

                    // Take the newest value (from ContentGroupItem and Entity)
                    if (entity is IHasEditingData)
                    {
                        var contentGroupItemModifiedUtc = ((IHasEditingData)entity).ContentGroupItemModified.ToUniversalTime();
                        searchInfo.ModifiedTimeUtc      = searchInfo.ModifiedTimeUtc > contentGroupItemModifiedUtc
                            ? searchInfo.ModifiedTimeUtc
                            : contentGroupItemModifiedUtc;
                    }

                    return(searchInfo);
                }));
            }

            try
            {
                engine.CustomizeSearch(searchInfoDictionary, moduleInfo, beginDate);
            }
            catch (Exception e)
            {
                Exceptions.LogException(new SearchIndexException(moduleInfo, e));
            }

            foreach (var searchInfoList in searchInfoDictionary)
            {
                // Filter by Date - take only SearchDocuments that changed since beginDate
                var searchDocumentsToAdd = searchInfoList.Value.Where(p => p.ModifiedTimeUtc >= beginDate.ToUniversalTime()).Select(p => (SearchDocument)p);

                searchDocuments.AddRange(searchDocumentsToAdd);
            }

            return(searchDocuments);
        }