Beispiel #1
0
        public void SaveTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache)
        {
            var portalAliasId = (tabUrl.PortalAliasUsage == PortalAliasUsageType.Default)
                                  ? Null.NullInteger
                                  : tabUrl.PortalAliasId;

            var saveLog = EventLogController.EventLogType.TABURL_CREATED;

            if (tabUrl.HttpStatus == "200")
            {
                saveLog = EventLogController.EventLogType.TABURL_CREATED;
            }
            else
            {
                //need to see if sequence number exists to decide if insert or update
                List <TabUrlInfo> t = GetTabUrls(portalId, tabUrl.TabId);
                var existingSeq     = t.FirstOrDefault(r => r.SeqNum == tabUrl.SeqNum);
                if (existingSeq == null)
                {
                    saveLog = EventLogController.EventLogType.TABURL_CREATED;
                }
            }

            DataProvider.Instance().SaveTabUrl(tabUrl.TabId, tabUrl.SeqNum, portalAliasId, (int)tabUrl.PortalAliasUsage, tabUrl.Url, tabUrl.QueryString, tabUrl.CultureCode, tabUrl.HttpStatus, tabUrl.IsSystem, UserController.GetCurrentUserInfo().UserID);

            var objEventLog = new EventLogController();

            objEventLog.AddLog("tabUrl",
                               tabUrl.ToString(),
                               PortalController.GetCurrentPortalSettings(),
                               UserController.GetCurrentUserInfo().UserID,
                               saveLog);

            if (clearCache)
            {
                DataCache.RemoveCache(String.Format(DataCache.TabUrlCacheKey, portalId));
                _legacyController.ClearCache(portalId);
                var tab = GetTab(tabUrl.TabId, portalId);
                tab.ClearTabUrls();
            }
        }
Beispiel #2
0
 public static string[] GetCacheKeys(int PortalId)
 {
     string[] CacheKeys = new string[] { };
     try
     {
         var builder = new UrlBuilder();
         CacheKeys = builder.BuildCacheKeys(PortalId);
     }
     catch (Exception ex)
     {
         //log it
         var objEventLog     = new EventLogController();
         var objEventLogInfo = new LogInfo();
         objEventLogInfo.AddProperty("UrlRewriter.RewriterConfiguration", "GetCacheKeys Failed");
         objEventLogInfo.AddProperty("ExceptionMessage", ex.Message);
         objEventLogInfo.LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString();
         objEventLog.AddLog(objEventLogInfo);
         Logger.Error(ex);
     }
     return(CacheKeys);
 }
        private void RestoreModule(int moduleId, int tabId)
        {
            var eventLogController = new EventLogController();
            var moduleController   = new ModuleController();

            // restore module
            var module = moduleController.GetModule(moduleId, tabId, false);

            if ((module != null))
            {
                if (tabsListBox.Items.FindByValue(module.TabID.ToString(CultureInfo.InvariantCulture)) != null)
                {
                    var title = !string.IsNullOrEmpty(module.ModuleTitle) ? module.ModuleTitle : module.DesktopModule.FriendlyName;
                    Skin.AddModuleMessage(this, string.Format(Localization.GetString("TabDeleted.ErrorMessage", LocalResourceFile), title),
                                          ModuleMessage.ModuleMessageType.RedError);
                    return;
                }
                moduleController.RestoreModule(module);
                eventLogController.AddLog(module, PortalSettings, UserId, "", EventLogController.EventLogType.MODULE_RESTORED);
            }
        }
        public static void UpdateSchedule(int ScheduleID, string TypeFullName, int TimeLapse, string TimeLapseMeasurement, int RetryTimeLapse, string RetryTimeLapseMeasurement, int RetainHistoryNum,
                                          string AttachToEvent, bool CatchUpEnabled, bool Enabled, string ObjectDependencies, string Servers, string FriendlyName)
        {
            DataProvider.Instance().UpdateSchedule(ScheduleID,
                                                   TypeFullName,
                                                   TimeLapse,
                                                   TimeLapseMeasurement,
                                                   RetryTimeLapse,
                                                   RetryTimeLapseMeasurement,
                                                   RetainHistoryNum,
                                                   AttachToEvent,
                                                   CatchUpEnabled,
                                                   Enabled,
                                                   ObjectDependencies,
                                                   Servers,
                                                   UserController.GetCurrentUserInfo().UserID,
                                                   FriendlyName);
            var objEventLog = new EventLogController();

            objEventLog.AddLog("TypeFullName", TypeFullName, PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, EventLogController.EventLogType.SCHEDULE_UPDATED);
        }
Beispiel #5
0
        internal void StorePageIndexInCache(SharedDictionary <string, string> tabDictionary,
                                            SharedDictionary <int, PathSizes> portalDepthInfo,
                                            FriendlyUrlSettings settings,
                                            string reason)
        {
            onRemovePageIndex = settings.LogCacheMessages ? (CacheItemRemovedCallback)RemovedPageIndexCallBack : null;

            //get list of portal ids for the portals we are storing in the page index
            var portalIds = new List <int>();

            using (portalDepthInfo.GetReadLock())
            {
                portalIds.AddRange(portalDepthInfo.Keys);
            }

            //783 : use cache dependency to manage page index instead of triggerDictionaryRebuild regex.
            SetPageCache(PageIndexKey, tabDictionary, new DNNCacheDependency(GetTabsCacheDependency(portalIds)), settings, onRemovePageIndex);

            SetPageCache(PageIndexDepthKey, portalDepthInfo, settings);

            LogRemovedReason = settings.LogCacheMessages;

            if (settings.LogCacheMessages)
            {
                var elc      = new EventLogController();
                var logValue = new LogInfo {
                    LogTypeKey = "HOST_ALERT"
                };

                logValue.AddProperty("Url Rewriting Caching Message", "Page Index built and Stored in Cache");
                logValue.AddProperty("Reason", reason);
                logValue.AddProperty("Cache Item Key", PageIndexKey);
                using (tabDictionary.GetReadLock())
                {
                    logValue.AddProperty("Item Count", tabDictionary.Count.ToString());
                }
                logValue.AddProperty("Thread Id", Thread.CurrentThread.ManagedThreadId.ToString());
                elc.AddLog(logValue);
            }
        }
Beispiel #6
0
        public bool ProcessMessages(EventMessageCollection eventMessages)
        {
            EventMessage message;

            foreach (EventMessage tempLoopVar_message in eventMessages)
            {
                message = tempLoopVar_message;
                try
                {
                    object oMessageProcessor = Reflection.CreateObject(message.ProcessorType, message.ProcessorType);
                    if (!((EventMessageProcessorBase)oMessageProcessor).ProcessMessage(message))
                    {
                        throw new Exception();
                    }
                }
                catch
                {
                    //log if message could not be processed
                    EventLogController objEventLog     = new EventLogController();
                    LogInfo            objEventLogInfo = new LogInfo();
                    objEventLogInfo.AddProperty("EventQueue.ProcessMessage", "Message Processing Failed");
                    objEventLogInfo.AddProperty("ProcessorType", message.ProcessorType);
                    objEventLogInfo.AddProperty("Body", message.Body);
                    objEventLogInfo.AddProperty("Sender", message.Sender);
                    foreach (string key in message.Attributes.Keys)
                    {
                        objEventLogInfo.AddProperty(key, message.Attributes[key]);
                    }
                    // HACK : Modified to not error if object is null.
                    //if( message.ExceptionMessage.Length > 0 )
                    if (!String.IsNullOrEmpty(message.ExceptionMessage))
                    {
                        objEventLogInfo.AddProperty("ExceptionMessage", message.ExceptionMessage);
                    }
                    objEventLogInfo.LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString();
                    objEventLog.AddLog(objEventLogInfo);
                }
            }
            return(true);
        }
Beispiel #7
0
        private void BtnClearClick(Object sender, EventArgs e)
        {
            var objLoggingController = new LogController();

            objLoggingController.ClearLog();
            UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("LogCleared", LocalResourceFile), ModuleMessage.ModuleMessageType.GreenSuccess);
            var objEventLog = new EventLogController();

            //add entry to log recording it was cleared
            objEventLog.AddLog(Localization.GetString("LogCleared", LocalResourceFile),
                               //Fariborz Khosravi
                               //Localization.GetString("Username", LocalResourceFile) + ":" + UserInfo.Username,
                               Localization.GetString("UserName", LocalResourceFile) + ":" + UserInfo.Username,
                               PortalSettings,
                               -1,
                               EventLogController.EventLogType.ADMIN_ALERT);
            BindPortalDropDown();
            dlLog.Visible     = false;
            btnDelete.Visible = false;
            btnClear.Visible  = false;
            ctlPagingControlBottom.Visible = false;
        }
Beispiel #8
0
        /// <summary>
        /// Store the Url Dictionary (all tab urls / tabids) for the installation
        /// </summary>
        /// <param name="urlDict"></param>
        /// <param name="urlPortals"></param>
        /// <param name="customAliasTabs"></param>
        /// <param name="settings"></param>
        /// <param name="reason"></param>
        /// <remarks>
        /// </remarks>
        internal void StoreFriendlyUrlIndexInCache(SharedDictionary <int, SharedDictionary <string, string> > urlDict,
                                                   List <int> urlPortals,
                                                   SharedDictionary <string, string> customAliasTabs,
                                                   FriendlyUrlSettings settings,
                                                   string reason)
        {
            if (settings.LogCacheMessages)
            {
                onRemovePageIndex = RemovedPageIndexCallBack;
            }
            else
            {
                onRemovePageIndex = null;
            }

            LogRemovedReason = settings.LogCacheMessages;

            SetPageCache(UrlDictKey, urlDict, new DNNCacheDependency(GetTabsCacheDependency(urlPortals)), settings, onRemovePageIndex);

            SetPageCache(UrlPortalsKey, urlPortals, settings);
            SetPageCache(CustomAliasTabsKey, customAliasTabs, settings);

            if (settings.LogCacheMessages)
            {
                var elc = new EventLogController();

                var logValue = new LogInfo {
                    LogTypeKey = "HOST_ALERT"
                };
                logValue.AddProperty("Url Rewriting Caching Message", "Friendly Url Index built and Stored in Cache.");
                logValue.AddProperty("Build Reason", reason);
                logValue.AddProperty("Cache Key", UrlDictKey);
                logValue.AddProperty("Item Count", urlDict.Values.Count.ToString());
                logValue.AddProperty("Thread Id", Thread.CurrentThread.ManagedThreadId.ToString());
                logValue.AddProperty("Item added to cache", "Url Portals object added to cache.  Key:" + UrlPortalsKey + "  Items: " + urlPortals.Count.ToString());
                logValue.AddProperty("Item added to cache", "Custom Alias Tabs added to cache.  Key:" + CustomAliasTabsKey + " Items: " + customAliasTabs.Count.ToString());
                elc.AddLog(logValue);
            }
        }
        public void LogException(Exception ex, EventLogSeverity severity)
        {
            var logInfo = new LogInfo();
            var user    = DnnUserController.Instance.GetCurrentUserInfo();

            logInfo.LogUserID   = user != null ? user.UserID : -1;
            logInfo.LogPortalID = DnnGlobal.Instance.GetPortalId();
            logInfo.LogTypeKey  = LOGTYPE_EXCEPTION;
            logInfo.AddProperty("Severity", severity.ToString());

            var exception4 = new BasePortalException(ex.ToString(), ex);

            logInfo.LogProperties.Add(new LogDetailInfo("AssemblyVersion", exception4.AssemblyVersion));
            logInfo.LogProperties.Add(new LogDetailInfo("PortalID", exception4.PortalID.ToString()));
            logInfo.LogProperties.Add(new LogDetailInfo("PortalName", exception4.PortalName));
            logInfo.LogProperties.Add(new LogDetailInfo("UserID", exception4.UserID.ToString()));
            logInfo.LogProperties.Add(new LogDetailInfo("UserName", exception4.UserName));
            logInfo.LogProperties.Add(new LogDetailInfo("ActiveTabID", exception4.ActiveTabID.ToString()));
            logInfo.LogProperties.Add(new LogDetailInfo("ActiveTabName", exception4.ActiveTabName));
            logInfo.LogProperties.Add(new LogDetailInfo("RawURL", exception4.RawURL));
            logInfo.LogProperties.Add(new LogDetailInfo("AbsoluteURL", exception4.AbsoluteURL));
            logInfo.LogProperties.Add(new LogDetailInfo("AbsoluteURLReferrer", exception4.AbsoluteURLReferrer));
            logInfo.LogProperties.Add(new LogDetailInfo("UserAgent", exception4.UserAgent));
            logInfo.LogProperties.Add(new LogDetailInfo("DefaultDataProvider", exception4.DefaultDataProvider));
            logInfo.LogProperties.Add(new LogDetailInfo("ExceptionGUID", exception4.ExceptionGUID));
            logInfo.LogProperties.Add(new LogDetailInfo("InnerException", exception4.InnerException.Message));
            logInfo.LogProperties.Add(new LogDetailInfo("FileName", exception4.FileName));
            logInfo.LogProperties.Add(new LogDetailInfo("FileLineNumber", exception4.FileLineNumber.ToString()));
            logInfo.LogProperties.Add(new LogDetailInfo("FileColumnNumber", exception4.FileColumnNumber.ToString()));
            logInfo.LogProperties.Add(new LogDetailInfo("Method", exception4.Method));
            logInfo.LogProperties.Add(new LogDetailInfo("StackTrace", exception4.StackTrace));
            logInfo.LogProperties.Add(new LogDetailInfo("Message", exception4.Message));
            logInfo.LogProperties.Add(new LogDetailInfo("Source", exception4.Source));

            var log = new EventLogController();

            log.AddLog(logInfo);
        }
        /// <summary>
        /// Deletes child tabs for the given Tab
        /// </summary>
        /// <param name="intTabid">ID of the parent tab</param>
        /// <returns>True is all child tabs could be deleted</returns>
        /// <remarks>
        /// Will delete child tabs recursively
        /// </remarks>
        /// <history>
        ///     [VMasanas]	30/09/2004	Created
        ///     [VMasanas]  01/09/2005  A tab will be deleted only if all descendants can be deleted
        /// </history>
        private bool DeleteChildTabs(int intTabid)
        {
            TabController objtabs = new TabController();
            ArrayList     arrTabs = objtabs.GetTabsByParentId(intTabid, PortalId);

            bool bDeleted = true;

            foreach (TabInfo objtab in arrTabs)
            {
                if (objtab.TabID != PortalSettings.AdminTabId && objtab.TabID != PortalSettings.SplashTabId && objtab.TabID != PortalSettings.HomeTabId && objtab.TabID != PortalSettings.LoginTabId && objtab.TabID != PortalSettings.UserTabId)
                {
                    //delete child tabs
                    if (DeleteChildTabs(objtab.TabID))
                    {
                        objtab.IsDeleted = true;
                        objtabs.UpdateTab(objtab);

                        EventLogController objEventLog = new EventLogController();
                        objEventLog.AddLog(objtab, PortalSettings, UserId, "", EventLogController.EventLogType.TAB_SENT_TO_RECYCLE_BIN);
                    }
                    else
                    {
                        //cannot delete tab, stop deleting and exit
                        bDeleted = false;
                        break;
                    }
                }
                else
                {
                    //cannot delete tab, stop deleting and exit
                    bDeleted = false;
                    break;
                }
            }


            return(bDeleted);
        }
Beispiel #11
0
        private static void UpgradeModule(EventMessage message)
        {
            try
            {
                int desktopModuleId = Convert.ToInt32(message.Attributes["DesktopModuleId"]);
                var desktopModule   = DesktopModuleController.GetDesktopModule(desktopModuleId, Null.NullInteger);

                string  BusinessControllerClass = message.Attributes["BusinessControllerClass"];
                object  controller         = Reflection.CreateObject(BusinessControllerClass, "");
                var     eventLogController = new EventLogController();
                LogInfo eventLogInfo;
                if (controller is IUpgradeable)
                {
                    //get the list of applicable versions
                    string[] UpgradeVersions = message.Attributes["UpgradeVersionsList"].Split(',');
                    foreach (string Version in UpgradeVersions)
                    {
                        //call the IUpgradeable interface for the module/version
                        string Results = ((IUpgradeable)controller).UpgradeModule(Version);
                        //log the upgrade results
                        eventLogInfo = new LogInfo();
                        eventLogInfo.AddProperty("Module Upgraded", BusinessControllerClass);
                        eventLogInfo.AddProperty("Version", Version);
                        if (!string.IsNullOrEmpty(Results))
                        {
                            eventLogInfo.AddProperty("Results", Results);
                        }
                        eventLogInfo.LogTypeKey = EventLogController.EventLogType.MODULE_UPDATED.ToString();
                        eventLogController.AddLog(eventLogInfo);
                    }
                }
                UpdateSupportedFeatures(controller, Convert.ToInt32(message.Attributes["DesktopModuleId"]));
            }
            catch (Exception exc)
            {
                Exceptions.LogException(exc);
            }
        }
        public async Task <List <Location> > GetSiteLocationsFromAPI(string siteID)
        {
            var        locationsURL = baseURL + "/markets/sites/" + siteID + "/locations";
            HttpClient client       = new HttpClient();

            client.DefaultRequestHeaders.Add("apikey", ServerCashBidsAPI);

            try
            {
                HttpResponseMessage response = await client.GetAsync(locationsURL).ConfigureAwait(false);

                string responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                var LocationsJSONList = JsonConvert.DeserializeObject <List <Location> >(responseBody);

                return(LocationsJSONList);
            } catch (Exception ex)
            {
                var objEventLog = new EventLogController();
                objEventLog.AddLog("Could not connect to locations market API;", ex.ToString(), EventLogController.EventLogType.ADMIN_ALERT);
            }
            return(new List <Location>());
        }
Beispiel #13
0
        public static void UpdatePackage(PackageInfo package)
        {
            provider.UpdatePackage(package.PortalID,
                                   package.Name,
                                   package.FriendlyName,
                                   package.Description,
                                   package.PackageType,
                                   package.Version.ToString(3),
                                   package.License,
                                   package.Manifest,
                                   package.Owner,
                                   package.Organization,
                                   package.Url,
                                   package.Email,
                                   package.ReleaseNotes,
                                   package.IsSystemPackage,
                                   UserController.GetCurrentUserInfo().UserID,
                                   package.FolderName,
                                   package.IconFile);
            var objEventLog = new EventLogController();

            objEventLog.AddLog(package, PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.PACKAGE_UPDATED);
        }
Beispiel #14
0
        internal static void ItemRemovedCallback(string key, object value, CacheItemRemovedReason removedReason)
        {
            //if the item was removed from the cache, log the key and reason to the event log
            try
            {
                if (Globals.Status == Globals.UpgradeStatus.None)
                {
                    var objEventLogInfo = new LogInfo();
                    switch (removedReason)
                    {
                    case CacheItemRemovedReason.Removed:
                        objEventLogInfo.LogTypeKey = EventLogController.EventLogType.CACHE_REMOVED.ToString();
                        break;

                    case CacheItemRemovedReason.Expired:
                        objEventLogInfo.LogTypeKey = EventLogController.EventLogType.CACHE_EXPIRED.ToString();
                        break;

                    case CacheItemRemovedReason.Underused:
                        objEventLogInfo.LogTypeKey = EventLogController.EventLogType.CACHE_UNDERUSED.ToString();
                        break;

                    case CacheItemRemovedReason.DependencyChanged:
                        objEventLogInfo.LogTypeKey = EventLogController.EventLogType.CACHE_DEPENDENCYCHANGED.ToString();
                        break;
                    }
                    objEventLogInfo.LogProperties.Add(new LogDetailInfo(key, removedReason.ToString()));
                    var objEventLog = new EventLogController();
                    objEventLog.AddLog(objEventLogInfo);
                }
            }
            catch (Exception exc)
            {
                //Swallow exception
                DnnLog.Error(exc);
            }
        }
        /// <summary>
        /// Deletes a tab
        /// </summary>
        /// <param name="objTab">The tab to be deleted</param>
        /// <remarks>
        /// Adds a log entry for the action to the EventLog
        /// </remarks>
        /// <history>
        ///     [VMasanas]	18/08/2004	Created
        ///                 19/09/2004  Remove skin deassignment. BLL takes care of this.
        ///                 30/09/2004  Change logic so log is only added when tab is actually deleted
        ///                 28/02/2005  Remove modules when deleting pages
        /// </history>
        private void DeleteTab(TabInfo objTab, bool deleteDescendants)
        {
            var objEventLog = new EventLogController();
            var objTabs     = new TabController();
            var objModules  = new ModuleController();

            //get tab modules before deleting page
            var dicTabModules = objModules.GetTabModules(objTab.TabID);

            //hard delete the tab
            objTabs.DeleteTab(objTab.TabID, objTab.PortalID, deleteDescendants);

            //delete modules that do not have other instances
            foreach (var kvp in dicTabModules)
            {
                //check if all modules instances have been deleted
                var objDelModule = objModules.GetModule(kvp.Value.ModuleID, Null.NullInteger, false);
                if (objDelModule == null || objDelModule.TabID == Null.NullInteger)
                {
                    objModules.DeleteModule(kvp.Value.ModuleID);
                }
            }
            objEventLog.AddLog(objTab, PortalSettings, UserId, "", EventLogController.EventLogType.TAB_DELETED);
        }
Beispiel #16
0
        public override List <SitemapUrl> GetUrls(int portalId, PortalSettings ps, string version)
        {
            var _eventLogController = new EventLogController();

            _eventLogController.AddLog("Message", "OpenNews SiteMap Provider being intialised", ps, -1, EventLogController.EventLogType.ADMIN_ALERT);
            List <SitemapUrl> results = new List <SitemapUrl>();
            var onMods = ModuleController.Instance.GetModulesByDefinition(PortalSettings.Current.PortalId, "dnn_OpenNewsSPA").Cast <ModuleInfo>().ToList();

            onMods.ToList().ForEach(m => {
                var urlOptions = new ModuleUrlOptions();
                UrlDataController.GetEverythingForProvider(m.TabID).ForEach(u => {
                    string url  = Globals.NavigateURL(m.TabID, ps, "", u.qsValue);
                    var pageUrl = new SitemapUrl
                    {
                        Url             = url,
                        Priority        = (float)0.5,
                        LastModified    = u.urlDate,
                        ChangeFrequency = SitemapChangeFrequency.Daily
                    };
                    results.Add(pageUrl);
                });
            });
            return(results);
        }
        private void LogResult(string message)
        {
            var portalSecurity = new PortalSecurity();

            var objEventLog     = new EventLogController();
            var objEventLogInfo = new LogInfo();

            objEventLogInfo.LogPortalID   = PortalSettings.PortalId;
            objEventLogInfo.LogPortalName = PortalSettings.PortalName;
            objEventLogInfo.LogUserID     = UserId;
            objEventLogInfo.LogUserName   = portalSecurity.InputFilter(User.Username,
                                                                       PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoMarkup);
            if (string.IsNullOrEmpty(message))
            {
                objEventLogInfo.LogTypeKey = "PASSWORD_SENT_SUCCESS";
            }
            else
            {
                objEventLogInfo.LogTypeKey = "PASSWORD_SENT_FAILURE";
                objEventLogInfo.LogProperties.Add(new LogDetailInfo("Cause", message));
            }

            objEventLog.AddLog(objEventLogInfo);
        }
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Updates a Property Defintion in the Data Store
        /// </summary>
        /// <param name="definition">The ProfilePropertyDefinition object to update</param>
        /// -----------------------------------------------------------------------------
        public static void UpdatePropertyDefinition(ProfilePropertyDefinition definition)
        {
            if (definition.Required)
            {
                definition.Visible = true;
            }
            _dataProvider.UpdatePropertyDefinition(definition.PropertyDefinitionId,
                                                   definition.DataType,
                                                   definition.DefaultValue,
                                                   definition.PropertyCategory,
                                                   definition.PropertyName,
                                                   definition.ReadOnly,
                                                   definition.Required,
                                                   definition.ValidationExpression,
                                                   definition.ViewOrder,
                                                   definition.Visible,
                                                   definition.Length,
                                                   (int)definition.DefaultVisibility,
                                                   UserController.GetCurrentUserInfo().UserID);
            var objEventLog = new EventLogController();

            objEventLog.AddLog(definition, PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.PROFILEPROPERTY_UPDATED);
            ClearProfileDefinitionCache(definition.PortalId);
        }
Beispiel #19
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Logs the Install event to the Event Log
        /// </summary>
        /// <param name="package">The name of the package</param>
        /// <param name="eventType">Event Type.</param>
        /// -----------------------------------------------------------------------------
        private void LogInstallEvent(string package, string eventType)
        {
            try
            {
                var objEventLogInfo = new LogInfo();
                objEventLogInfo.LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString();

                if (InstallerInfo.ManifestFile != null)
                {
                    objEventLogInfo.LogProperties.Add(new LogDetailInfo(eventType + " " + package + ":", InstallerInfo.ManifestFile.Name.Replace(".dnn", "")));
                }

                foreach (LogEntry objLogEntry in InstallerInfo.Log.Logs)
                {
                    objEventLogInfo.LogProperties.Add(new LogDetailInfo("Info:", objLogEntry.Description));
                }
                var objEventLog = new EventLogController();
                objEventLog.AddLog(objEventLogInfo);
            }
            catch (Exception exc)
            {
                Logger.Error(exc);
            }
        }
        private void DeleteTab(TabInfo tab, bool deleteDescendants)
        {
            var eventLogController = new EventLogController();
            var tabController      = new TabController();
            var moduleController   = new ModuleController();

            //get tab modules before deleting page
            var tabModules = moduleController.GetTabModules(tab.TabID);

            //hard delete the tab
            tabController.DeleteTab(tab.TabID, tab.PortalID, deleteDescendants);

            //delete modules that do not have other instances
            foreach (var kvp in tabModules)
            {
                //check if all modules instances have been deleted
                var delModule = moduleController.GetModule(kvp.Value.ModuleID, Null.NullInteger, false);
                if (delModule == null || delModule.TabID == Null.NullInteger)
                {
                    moduleController.DeleteModule(kvp.Value.ModuleID);
                }
            }
            eventLogController.AddLog(tab, PortalSettings, UserId, "", EventLogController.EventLogType.TAB_DELETED);
        }
Beispiel #21
0
 private void OnPageLoad(object sender, EventArgs e)
 {
     try
     {
         AnalyticsEngineCollection analyticsEngines = AnalyticsEngineConfiguration.GetConfig().AnalyticsEngines;
         if (analyticsEngines == null || analyticsEngines.Count == 0)
         {
             return;
         }
         var page = (Page)sender;
         if ((page == null))
         {
             return;
         }
         foreach (AnalyticsEngine engine in analyticsEngines)
         {
             if ((!String.IsNullOrEmpty(engine.ElementId)))
             {
                 AnalyticsEngineBase objEngine = null;
                 if ((!String.IsNullOrEmpty(engine.EngineType)))
                 {
                     Type engineType = Type.GetType(engine.EngineType);
                     if (engineType == null)
                     {
                         objEngine = new GenericAnalyticsEngine();
                     }
                     else
                     {
                         objEngine = (AnalyticsEngineBase)Activator.CreateInstance(engineType);
                     }
                 }
                 else
                 {
                     objEngine = new GenericAnalyticsEngine();
                 }
                 if (objEngine != null)
                 {
                     string script = engine.ScriptTemplate;
                     if ((!String.IsNullOrEmpty(script)))
                     {
                         script = objEngine.RenderScript(script);
                         if ((!String.IsNullOrEmpty(script)))
                         {
                             var element = (HtmlContainerControl)page.FindControl(engine.ElementId);
                             if (element != null)
                             {
                                 var scriptControl = new LiteralControl();
                                 scriptControl.Text = script;
                                 if (engine.InjectTop)
                                 {
                                     element.Controls.AddAt(0, scriptControl);
                                 }
                                 else
                                 {
                                     element.Controls.Add(scriptControl);
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         var objEventLog     = new EventLogController();
         var objEventLogInfo = new LogInfo();
         objEventLogInfo.AddProperty("Analytics.AnalyticsModule", "OnPageLoad");
         objEventLogInfo.AddProperty("ExceptionMessage", ex.Message);
         objEventLogInfo.LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString();
         objEventLog.AddLog(objEventLogInfo);
         Logger.Error(ex);
     }
 }
Beispiel #22
0
        /// <summary>
        /// UserCreateCompleted runs when a new user has been Created
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///     [cnurse]	3/06/2006	created
        /// </history>
        protected void UserCreateCompleted(object sender, User.UserCreatedEventArgs e)
        {
            string strMessage = "";

            try
            {
                if (e.CreateStatus == UserCreateStatus.Success)
                {
                    if (IsRegister)
                    {
                        // send notification to portal administrator of new user registration
                        Mail.SendMail(User, MessageType.UserRegistrationAdmin, PortalSettings);

                        // complete registration

                        switch (PortalSettings.UserRegistration)
                        {
                        case (int)Globals.PortalRegistrationType.PrivateRegistration:

                            Mail.SendMail(User, MessageType.UserRegistrationPrivate, PortalSettings);

                            //show a message that a portal administrator has to verify the user credentials
                            strMessage = string.Format(Localization.GetString("PrivateConfirmationMessage", this.LocalResourceFile), User.Email);
                            break;

                        case (int)Globals.PortalRegistrationType.PublicRegistration:

                            Mail.SendMail(User, MessageType.UserRegistrationPublic, PortalSettings);

                            UserLoginStatus loginStatus = 0;
                            UserController.UserLogin(PortalSettings.PortalId, User.Username, User.Membership.Password, "", PortalSettings.PortalName, "", ref loginStatus, false);
                            break;

                        case (int)Globals.PortalRegistrationType.VerifiedRegistration:

                            Mail.SendMail(User, MessageType.UserRegistrationVerified, PortalSettings);

                            //show a message that an email has been send with the registration details
                            strMessage = string.Format(Localization.GetString("VerifiedConfirmationMessage", this.LocalResourceFile), User.Email);
                            break;
                        }

                        // affiliate
                        if (!Null.IsNull(User.AffiliateID))
                        {
                            AffiliateController objAffiliates = new AffiliateController();
                            objAffiliates.UpdateAffiliateStats(User.AffiliateID, 0, 1);
                        }

                        //store preferredlocale in cookie
                        Localization.SetLanguage(User.Profile.PreferredLocale);

                        AddLocalizedModuleMessage(strMessage, ModuleMessageType.GreenSuccess, (strMessage.Length > 0));
                    }
                    else
                    {
                        if (e.Notify)
                        {
                            //Send Notification to User
                            if (PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration)
                            {
                                Mail.SendMail(User, MessageType.UserRegistrationVerified, PortalSettings);
                            }
                            else
                            {
                                Mail.SendMail(User, MessageType.UserRegistrationPublic, PortalSettings);
                            }
                        }
                    }

                    //Log Event to Event Log
                    EventLogController objEventLog = new EventLogController();
                    objEventLog.AddLog(User, PortalSettings, UserId, User.Username, EventLogController.EventLogType.USER_CREATED);

                    if (IsRegister)
                    {
                        //Response.Redirect( RedirectURL, true );
                        if (string.IsNullOrEmpty(strMessage))
                        {
                            Response.Redirect(RedirectURL, true);
                        }
                        else
                        {
                            DisableForm();
                            pnlRegister.Visible = false;
                        }
                    }
                    else
                    {
                        Response.Redirect(ReturnUrl, true);
                    }
                }
                else
                {
                    AddLocalizedModuleMessage(UserController.GetUserCreateStatus(e.CreateStatus), ModuleMessageType.RedError, true);
                }
            }
            catch (Exception exc)  //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Beispiel #23
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// LogEnd logs the Application Start Event
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///     [cnurse]    1/28/2005   Moved back to App_End from Logging Module
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void LogEnd()
        {
            try
            {
                ApplicationShutdownReason shutdownReason = HostingEnvironment.ShutdownReason;
                string shutdownDetail = "";
                switch (shutdownReason)
                {
                case ApplicationShutdownReason.BinDirChangeOrDirectoryRename:
                    shutdownDetail = "The AppDomain shut down because of a change to the Bin folder or files contained in it.";
                    break;

                case ApplicationShutdownReason.BrowsersDirChangeOrDirectoryRename:
                    shutdownDetail = "The AppDomain shut down because of a change to the App_Browsers folder or files contained in it.";
                    break;

                case ApplicationShutdownReason.ChangeInGlobalAsax:
                    shutdownDetail = "The AppDomain shut down because of a change to Global.asax.";
                    break;

                case ApplicationShutdownReason.ChangeInSecurityPolicyFile:
                    shutdownDetail = "The AppDomain shut down because of a change in the code access security policy file.";
                    break;

                case ApplicationShutdownReason.CodeDirChangeOrDirectoryRename:
                    shutdownDetail = "The AppDomain shut down because of a change to the App_Code folder or files contained in it.";
                    break;

                case ApplicationShutdownReason.ConfigurationChange:
                    shutdownDetail = "The AppDomain shut down because of a change to the application level configuration.";
                    break;

                case ApplicationShutdownReason.HostingEnvironment:
                    shutdownDetail = "The AppDomain shut down because of the hosting environment.";
                    break;

                case ApplicationShutdownReason.HttpRuntimeClose:
                    shutdownDetail = "The AppDomain shut down because of a call to Close.";
                    break;

                case ApplicationShutdownReason.IdleTimeout:
                    shutdownDetail = "The AppDomain shut down because of the maximum allowed idle time limit.";
                    break;

                case ApplicationShutdownReason.InitializationError:
                    shutdownDetail = "The AppDomain shut down because of an AppDomain initialization error.";
                    break;

                case ApplicationShutdownReason.MaxRecompilationsReached:
                    shutdownDetail = "The AppDomain shut down because of the maximum number of dynamic recompiles of resources limit.";
                    break;

                case ApplicationShutdownReason.PhysicalApplicationPathChanged:
                    shutdownDetail = "The AppDomain shut down because of a change to the physical path for the application.";
                    break;

                case ApplicationShutdownReason.ResourcesDirChangeOrDirectoryRename:
                    shutdownDetail = "The AppDomain shut down because of a change to the App_GlobalResources folder or files contained in it.";
                    break;

                case ApplicationShutdownReason.UnloadAppDomainCalled:
                    shutdownDetail = "The AppDomain shut down because of a call to UnloadAppDomain.";
                    break;

                default:
                    shutdownDetail = "No shutdown reason provided.";
                    break;
                }
                var objEv           = new EventLogController();
                var objEventLogInfo = new LogInfo();
                objEventLogInfo.BypassBuffering = true;
                objEventLogInfo.LogTypeKey      = EventLogController.EventLogType.APPLICATION_SHUTTING_DOWN.ToString();
                objEventLogInfo.AddProperty("Shutdown Details", shutdownDetail);
                objEv.AddLog(objEventLogInfo);

                Logger.InfoFormat("Application shutting down. Reason: {0}", shutdownDetail);
            }
            catch (Exception exc)
            {
                Exceptions.LogException(exc);
            }
            if (Globals.Status != Globals.UpgradeStatus.Install)
            {
                //purge log buffer
                LoggingProvider.Instance().PurgeLogBuffer();
            }
        }
Beispiel #24
0
        private int DoAddExistingModule(int moduleId, int tabId, string paneName, int position, string align, bool cloneModule)
        {
            var        moduleCtrl = new ModuleController();
            ModuleInfo moduleInfo = moduleCtrl.GetModule(moduleId, tabId, false);

            int userID = -1;

            UserInfo user = UserController.GetCurrentUserInfo();

            if (user != null)
            {
                userID = user.UserID;
            }


            if ((moduleInfo != null))
            {
                // Is this from a site other than our own? (i.e., is the user requesting "module sharing"?)
                var remote = moduleInfo.PortalID != PortalSettings.Current.PortalId;
                if (remote)
                {
                    switch (moduleInfo.DesktopModule.Shareable)
                    {
                    case ModuleSharing.Unsupported:
                        // Should never happen since the module should not be listed in the first place.
                        throw new ApplicationException(string.Format("Module '{0}' does not support Shareable and should not be listed in Add Existing Module from a different source site",
                                                                     moduleInfo.DesktopModule.FriendlyName));

                    case ModuleSharing.Supported:
                        break;

                    case ModuleSharing.Unknown:
                        break;
                    }
                }

                // clone the module object ( to avoid creating an object reference to the data cache )
                ModuleInfo newModule = moduleInfo.Clone();

                newModule.UniqueId = Guid.NewGuid(); // Cloned Module requires a different uniqueID

                newModule.TabID       = PortalSettings.Current.ActiveTab.TabID;
                newModule.ModuleOrder = position;
                newModule.PaneName    = paneName;
                newModule.Alignment   = align;

                if ((cloneModule))
                {
                    newModule.ModuleID = Null.NullInteger;
                    //reset the module id
                    newModule.ModuleID = moduleCtrl.AddModule(newModule);

                    if (!string.IsNullOrEmpty(newModule.DesktopModule.BusinessControllerClass))
                    {
                        object objObject = DotNetNuke.Framework.Reflection.CreateObject(newModule.DesktopModule.BusinessControllerClass, newModule.DesktopModule.BusinessControllerClass);
                        if (objObject is IPortable)
                        {
                            string content = Convert.ToString(((IPortable)objObject).ExportModule(moduleId));
                            if (!string.IsNullOrEmpty(content))
                            {
                                ((IPortable)objObject).ImportModule(newModule.ModuleID, content, newModule.DesktopModule.Version, userID);
                            }
                        }
                    }
                }
                else
                {
                    moduleCtrl.AddModule(newModule);
                }

                if (remote)
                {
                    //Ensure the Portal Admin has View rights
                    var       permissionController           = new PermissionController();
                    ArrayList arrSystemModuleViewPermissions = permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", "VIEW");
                    AddModulePermission(newModule,
                                        (PermissionInfo)arrSystemModuleViewPermissions[0],
                                        PortalSettings.Current.AdministratorRoleId,
                                        Null.NullInteger,
                                        true);

                    //Set PortalID correctly
                    newModule.OwnerPortalID = newModule.PortalID;
                    newModule.PortalID      = PortalSettings.Current.PortalId;
                    ModulePermissionController.SaveModulePermissions(newModule);
                }

                //Add Event Log
                var objEventLog = new EventLogController();
                objEventLog.AddLog(newModule, PortalSettings.Current, userID, "", EventLogController.EventLogType.MODULE_CREATED);

                return(newModule.ModuleID);
            }

            return(-1);
        }
        protected void OnImportClick(object sender, EventArgs e)
        {
            try
            {
                if (cboTemplate.SelectedItem == null || cboTemplate.SelectedValue == "None_Specified")
                {
                    UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("SpecifyFile", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                    return;
                }
                if (optMode.SelectedIndex == -1)
                {
                    UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("SpecifyMode", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                    return;
                }
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(PortalSettings.HomeDirectoryMapPath + cboFolders.SelectedValue + cboTemplate.SelectedValue);
                XmlNode nodeTab = xmlDoc.SelectSingleNode("//portal/tabs/tab");
                TabInfo objTab;
                if (optMode.SelectedValue == "ADD")
                {
                    if (string.IsNullOrEmpty(txtTabName.Text))
                    {
                        UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("SpecifyName", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                        return;
                    }

                    //New Tab
                    objTab = new TabInfo {
                        PortalID = PortalId, TabName = txtTabName.Text, IsVisible = true
                    };
                    if (cboParentTab.SelectedItem != null)
                    {
                        objTab.ParentId = Int32.Parse(cboParentTab.SelectedItem.Value);
                    }
                    objTab.TabPath = Globals.GenerateTabPath(objTab.ParentId, objTab.TabName);
                    int tabID   = TabController.GetTabByTabPath(objTab.PortalID, objTab.TabPath, Null.NullString);
                    var objTabs = new TabController();

                    //Check if tab exists
                    if (tabID != Null.NullInteger)
                    {
                        TabInfo existingTab = objTabs.GetTab(tabID, PortalId, false);
                        if (existingTab != null && existingTab.IsDeleted)
                        {
                            UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("TabRecycled", LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning);
                        }
                        else
                        {
                            UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("TabExists", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                        }
                        return;
                    }

                    int positionTabID = Int32.Parse(cboPositionTab.SelectedItem.Value);

                    var objEventLog = new EventLogController();
                    if (rbInsertPosition.SelectedValue == "After" && positionTabID > Null.NullInteger)
                    {
                        objTab.TabID = objTabs.AddTabAfter(objTab, positionTabID);
                    }
                    else if (rbInsertPosition.SelectedValue == "Before" && positionTabID > Null.NullInteger)
                    {
                        objTab.TabID = objTabs.AddTabBefore(objTab, positionTabID);
                    }
                    else
                    {
                        objTab.TabID = objTabs.AddTab(objTab);
                    }
                    objEventLog.AddLog(objTab, PortalSettings, UserId, "", EventLogController.EventLogType.TAB_CREATED);

                    //Update Tab properties from template
                    objTab = TabController.DeserializeTab(nodeTab, objTab, PortalId, PortalTemplateModuleAction.Replace);
                }
                else
                {
                    //Replace Existing Tab
                    objTab = TabController.DeserializeTab(nodeTab, Tab, PortalId, PortalTemplateModuleAction.Replace);
                }
                switch (optRedirect.SelectedValue)
                {
                case "VIEW":
                    Response.Redirect(Globals.NavigateURL(objTab.TabID), true);
                    break;

                default:
                    Response.Redirect(Globals.NavigateURL(objTab.TabID, "Tab", "action=edit"), true);
                    break;
                }
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Beispiel #26
0
        protected void OnImportClick(object sender, EventArgs e)
        {
            try
            {
                if (cboTemplate.SelectedItem == null || cboTemplate.SelectedValue == "None_Specified")
                {
                    UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("SpecifyFile", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                    return;
                }
                if (optMode.SelectedIndex == -1)
                {
                    UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("SpecifyMode", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                    return;
                }
                if (cboFolders.SelectedItem == null)
                {
                    return;
                }
                var selectedFolder = FolderManager.Instance.GetFolder(cboFolders.SelectedItemValueAsInt);
                if (selectedFolder == null)
                {
                    return;
                }

                var xmlDoc = new XmlDocument();
                xmlDoc.Load(PortalSettings.HomeDirectoryMapPath + selectedFolder.FolderPath + cboTemplate.SelectedValue);

                var tabNodes         = new List <XmlNode>();
                var selectSingleNode = xmlDoc.SelectSingleNode("//portal/tabs");
                if (selectSingleNode != null)
                {
                    tabNodes.AddRange(selectSingleNode.ChildNodes.Cast <XmlNode>());
                }
                if (tabNodes.Count == 0)
                {
                    UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("NoTabsInTemplate", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                    return;
                }

                TabInfo objTab;
                if (optMode.SelectedValue == "ADD")
                {
                    if (string.IsNullOrEmpty(txtTabName.Text))
                    {
                        UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("SpecifyName", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                        return;
                    }

                    //New Tab
                    objTab = new TabInfo {
                        PortalID = PortalId, TabName = txtTabName.Text, IsVisible = true
                    };
                    var parentId = cboParentTab.SelectedItemValueAsInt;
                    if (parentId != Null.NullInteger)
                    {
                        objTab.ParentId = parentId;
                    }
                    objTab.TabPath = Globals.GenerateTabPath(objTab.ParentId, objTab.TabName);
                    var tabId   = TabController.GetTabByTabPath(objTab.PortalID, objTab.TabPath, Null.NullString);
                    var objTabs = new TabController();

                    //Check if tab exists
                    if (tabId != Null.NullInteger)
                    {
                        TabInfo existingTab = objTabs.GetTab(tabId, PortalId, false);
                        if (existingTab != null && existingTab.IsDeleted)
                        {
                            UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("TabRecycled", LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning);
                        }
                        else
                        {
                            UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("TabExists", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                        }
                        return;
                    }

                    var positionTabId = Int32.Parse(cboPositionTab.SelectedItem.Value);

                    //var pc = new PermissionController();

                    //var permission = pc.GetPermissionByCodeAndKey("SYSTEM_TAB", "VIEW");
                    //if (permission.Count > 0)
                    //{
                    //    var pid = ((PermissionInfo)permission[0]).PermissionID;
                    //    objTab.TabPermissions.Add(new TabPermissionInfo { PermissionID = pid, AllowAccess = true, RoleID = 0 });
                    //}

                    //permission = pc.GetPermissionByCodeAndKey("SYSTEM_TAB", "EDIT");
                    //if (permission.Count > 0)
                    //{
                    //    var pid = ((PermissionInfo)permission[0]).PermissionID;
                    //    objTab.TabPermissions.Add(new TabPermissionInfo { PermissionID = pid, AllowAccess = true, RoleID = 0 });
                    //}

                    var objEventLog = new EventLogController();
                    if (rbInsertPosition.SelectedValue == "After" && positionTabId > Null.NullInteger)
                    {
                        objTab.TabID = objTabs.AddTabAfter(objTab, positionTabId);
                    }
                    else if (rbInsertPosition.SelectedValue == "Before" && positionTabId > Null.NullInteger)
                    {
                        objTab.TabID = objTabs.AddTabBefore(objTab, positionTabId);
                    }
                    else
                    {
                        objTab.TabID = objTabs.AddTab(objTab);
                    }
                    objEventLog.AddLog(objTab, PortalSettings, UserId, "", EventLogController.EventLogType.TAB_CREATED);

                    objTab = TabController.DeserializeTab(tabNodes[0], objTab, PortalId, PortalTemplateModuleAction.Replace);

                    var exceptions = string.Empty;
                    //Create second tabs onwards. For firs tab, we like to use tab details from text box, for rest it'll come from template
                    for (var tab = 1; tab < tabNodes.Count; tab++)
                    {
                        try
                        {
                            TabController.DeserializeTab(tabNodes[tab], null, PortalId, PortalTemplateModuleAction.Replace);
                        }
                        catch (Exception ex)
                        {
                            Exceptions.LogException(ex);
                            exceptions += string.Format("Template Tab # {0}. Error {1}<br/>", tab + 1, ex.Message);
                        }
                    }
                    if (!string.IsNullOrEmpty(exceptions))
                    {
                        UI.Skins.Skin.AddModuleMessage(this, exceptions, ModuleMessage.ModuleMessageType.RedError);
                        return;
                    }
                }
                else
                {
                    //Replace Existing Tab
                    objTab = TabController.DeserializeTab(tabNodes[0], Tab, PortalId, PortalTemplateModuleAction.Replace);
                }
                switch (optRedirect.SelectedValue)
                {
                case "VIEW":
                    Response.Redirect(Globals.NavigateURL(objTab.TabID), true);
                    break;

                default:
                    Response.Redirect(Globals.NavigateURL(objTab.TabID, "Tab", "action=edit"), true);
                    break;
                }
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
        private string CreateModuleControl()
        {
            EventLogController objEventLog = new EventLogController();

            var moduleTemplatePath = Server.MapPath(ModulePath) + "Templates\\" + optLanguage.SelectedValue + "\\" + cboTemplate.SelectedValue + "\\";

            objEventLog.AddLog("Processing Template Folder", moduleTemplatePath, PortalSettings, -1, EventLogController.EventLogType.HOST_ALERT);


            var controlName = Null.NullString;
            var fileName    = Null.NullString;
            var modulePath  = "";
            var sourceCode  = Null.NullString;

            //iterate through files in template folder
            string[] fileList = Directory.GetFiles(moduleTemplatePath);
            foreach (string filePath in fileList)
            {
                modulePath = Server.MapPath("DesktopModules/" + GetFolderName() + "/");

                //open file
                TextReader tr = new StreamReader(filePath);
                sourceCode = tr.ReadToEnd();
                tr.Close();

                //replace tokens
                sourceCode = sourceCode.Replace("_OWNER_", GetOwner());
                sourceCode = sourceCode.Replace("_MODULE_", GetModule());
                sourceCode = sourceCode.Replace("_CONTROL_", GetControl());
                sourceCode = sourceCode.Replace("_YEAR_", DateTime.Now.Year.ToString());

                //get filename
                fileName = Path.GetFileName(filePath);
                fileName = fileName.Replace("template", GetControl());
                fileName = fileName.Replace("_CONTROL_", GetControl());

                switch (Path.GetExtension(filePath).ToLower())
                {
                case ".ascx":
                    controlName = fileName;
                    break;

                case ".vbhtml":
                    controlName = fileName;
                    break;

                case ".cshtml":
                    controlName = fileName;
                    break;

                case ".resx":
                    modulePath = modulePath + "\\App_LocalResources\\";
                    break;

                case ".vb":
                    if (filePath.ToLower().IndexOf(".ascx") == -1)
                    {
                        modulePath = modulePath.Replace("DesktopModules", "App_Code");
                    }
                    break;

                case ".cs":
                    if (filePath.ToLower().IndexOf(".ascx") == -1)
                    {
                        modulePath = modulePath.Replace("DesktopModules", "App_Code");
                    }
                    break;

                case ".js":
                    modulePath = modulePath + "\\js\\";
                    break;
                }

                //check if folder exists
                if (!Directory.Exists(modulePath))
                {
                    Directory.CreateDirectory(modulePath);
                }

                //check if file already exists
                if (!File.Exists(modulePath + fileName))
                {
                    //create file
                    TextWriter tw = new StreamWriter(modulePath + fileName);
                    tw.WriteLine(sourceCode);
                    tw.Close();

                    objEventLog.AddLog("Created File", modulePath + fileName, PortalSettings, -1, EventLogController.EventLogType.HOST_ALERT);
                }
            }

            return(controlName);
        }
Beispiel #28
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            try
            {
                bool blnValid = true;
//                string strTransactionID;
                int intRoleID   = 0;
                int intPortalID = PortalSettings.PortalId;
                int intUserID   = 0;
//                string strDescription;
                double dblAmount = 0;
//                string strEmail;
                bool   blnCancel           = false;
                string strPayPalID         = Null.NullString;
                var    objRoles            = new RoleController();
                var    objPortalController = new PortalController();
                string strPost             = "cmd=_notify-validate";
                foreach (string strName in Request.Form)
                {
                    string strValue = Request.Form[strName];
                    switch (strName)
                    {
                    case "txn_type":     //get the transaction type
                        string strTransactionType = strValue;
                        switch (strTransactionType)
                        {
                        case "subscr_signup":
                        case "subscr_payment":
                        case "web_accept":
                            break;

                        case "subscr_cancel":
                            blnCancel = true;
                            break;

                        default:
                            blnValid = false;
                            break;
                        }
                        break;

                    case "payment_status":     //verify the status
                        if (strValue != "Completed")
                        {
                            blnValid = false;
                        }
                        break;

                    case "txn_id":     //verify the transaction id for duplicates
//                            strTransactionID = strValue;
                        break;

                    case "receiver_email":     //verify the PayPalId
                        strPayPalID = strValue;
                        break;

                    case "mc_gross":     // verify the price
                        dblAmount = double.Parse(strValue);
                        break;

                    case "item_number":     //get the RoleID
                        intRoleID = Int32.Parse(strValue);
                        //RoleInfo objRole = objRoles.GetRole(intRoleID, intPortalID);
                        break;

                    case "item_name":     //get the product description
//                            strDescription = strValue;
                        break;

                    case "custom":     //get the UserID
                        intUserID = Int32.Parse(strValue);
                        break;

                    case "email":     //get the email
//                            strEmail = strValue;
                        break;
                    }

                    //reconstruct post for postback validation
                    strPost += string.Format("&{0}={1}", Globals.HTTPPOSTEncode(strName), Globals.HTTPPOSTEncode(strValue));
                }

                //postback to verify the source
                if (blnValid)
                {
                    Dictionary <string, string> settings = PortalController.GetPortalSettingsDictionary(PortalSettings.PortalId);
                    string strPayPalURL;

                    // Sandbox mode
                    if (settings.ContainsKey("paypalsandbox") && !String.IsNullOrEmpty(settings["paypalsandbox"]) && settings["paypalsandbox"] == "true")
                    {
                        strPayPalURL = "https://www.sandbox.paypal.com/cgi-bin/webscr?";
                    }
                    else
                    {
                        strPayPalURL = "https://www.paypal.com/cgi-bin/webscr?";
                    }
                    var objRequest = (HttpWebRequest)WebRequest.Create(strPayPalURL);
                    objRequest.Method        = "POST";
                    objRequest.ContentLength = strPost.Length;
                    objRequest.ContentType   = "application/x-www-form-urlencoded";
                    using (var objStream = new StreamWriter(objRequest.GetRequestStream()))
                    {
                        objStream.Write(strPost);
                    }

                    string strResponse;
                    using (var objResponse = (HttpWebResponse)objRequest.GetResponse())
                    {
                        using (var sr = new StreamReader(objResponse.GetResponseStream()))
                        {
                            strResponse = sr.ReadToEnd();
                        }
                    }
                    switch (strResponse)
                    {
                    case "VERIFIED":
                        break;

                    default:
                        //possible fraud
                        blnValid = false;
                        break;
                    }
                }
                if (blnValid)
                {
                    int        intAdministratorRoleId = 0;
                    string     strProcessorID         = Null.NullString;
                    PortalInfo objPortalInfo          = objPortalController.GetPortal(intPortalID);
                    if (objPortalInfo != null)
                    {
                        intAdministratorRoleId = objPortalInfo.AdministratorRoleId;
                        strProcessorID         = objPortalInfo.ProcessorUserId.ToLower();
                    }

                    if (intRoleID == intAdministratorRoleId)
                    {
                        //admin portal renewal
                        strProcessorID = Host.ProcessorUserId.ToLower();
                        float portalPrice = objPortalInfo.HostFee;
                        if ((portalPrice.ToString() == dblAmount.ToString()) && (HttpUtility.UrlDecode(strPayPalID.ToLower()) == strProcessorID))
                        {
                            objPortalController.UpdatePortalExpiry(intPortalID);
                        }
                        else
                        {
                            var objEventLog     = new EventLogController();
                            var objEventLogInfo = new LogInfo();
                            objEventLogInfo.LogPortalID   = intPortalID;
                            objEventLogInfo.LogPortalName = PortalSettings.PortalName;
                            objEventLogInfo.LogUserID     = intUserID;
                            objEventLogInfo.LogTypeKey    = "POTENTIAL PAYPAL PAYMENT FRAUD";
                            objEventLog.AddLog(objEventLogInfo);
                        }
                    }
                    else
                    {
                        //user subscription
                        RoleInfo objRoleInfo = TestableRoleController.Instance.GetRole(intPortalID, r => r.RoleID == intRoleID);
                        float    rolePrice   = objRoleInfo.ServiceFee;
                        float    trialPrice  = objRoleInfo.TrialFee;
                        if ((rolePrice.ToString() == dblAmount.ToString() || trialPrice.ToString() == dblAmount.ToString()) && (HttpUtility.UrlDecode(strPayPalID.ToLower()) == strProcessorID))
                        {
                            objRoles.UpdateUserRole(intPortalID, intUserID, intRoleID, blnCancel);
                        }
                        else
                        {
                            var objEventLog     = new EventLogController();
                            var objEventLogInfo = new LogInfo();
                            objEventLogInfo.LogPortalID   = intPortalID;
                            objEventLogInfo.LogPortalName = PortalSettings.PortalName;
                            objEventLogInfo.LogUserID     = intUserID;
                            objEventLogInfo.LogTypeKey    = "POTENTIAL PAYPAL PAYMENT FRAUD";
                            objEventLog.AddLog(objEventLogInfo);
                        }
                    }
                }
            }
            catch (Exception exc) //Page failed to load
            {
                Exceptions.ProcessPageLoadException(exc);
            }
        }
        private void AddLog(string logContent)
        {
            var objEventLog = new EventLogController();

            objEventLog.AddLog("Site Redirection Rule", logContent, PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, EventLogController.EventLogType.ADMIN_ALERT);
        }
        public void HandleImageRequest(HttpContextBase context, Func <NameValueCollection, ImageInfo> imageGenCallback, string uniqueIdStringSeed)
        {
            context.Response.Clear();

            string ipAddress = UserRequestIPAddressController.Instance.GetUserRequestIPAddress(context.Request);

            // Check if allowed standalone
            if (!this.AllowStandalone && context.Request.UrlReferrer == null && !context.Request.IsLocal)
            {
                string message = "Not allowed to use standalone";
                if (this.LogSecurity)
                {
                    EventLogController logController = new EventLogController();
                    var logInfo = new LogInfo
                    {
                        LogUserID   = PortalSettings.Current.UserId,
                        LogPortalID = PortalSettings.Current.PortalId,
                        LogTypeKey  = EventLogController.EventLogType.ADMIN_ALERT.ToString(),
                    };
                    logInfo.AddProperty("DnnImageHandler", message);
                    logInfo.AddProperty("IP", ipAddress);
                    logController.AddLog(logInfo);
                }

                context.Response.StatusCode        = 403;
                context.Response.StatusDescription = message;
                context.Response.End();
                return;
            }

            // Check if domain is allowed to embed image
            if (!string.IsNullOrEmpty(this.AllowedDomains[0]) &&
                context.Request.UrlReferrer != null &&
                context.Request.UrlReferrer.Host.ToLowerInvariant() != context.Request.Url.Host.ToLowerInvariant())
            {
                bool   allowed        = false;
                string allowedDomains = string.Empty;
                foreach (string allowedDomain in this.AllowedDomains)
                {
                    if (!string.IsNullOrEmpty(allowedDomain))
                    {
                        allowedDomains += allowedDomain + ",";
                        if (context.Request.UrlReferrer.Host.ToLowerInvariant().Contains(allowedDomain.ToLowerInvariant()))
                        {
                            allowed = true;
                        }
                    }
                }

                if (!allowed)
                {
                    string message = $"Not allowed to use from referrer '{context.Request.UrlReferrer.Host}'";
                    if (this.LogSecurity)
                    {
                        EventLogController logController = new EventLogController();
                        var logInfo = new LogInfo
                        {
                            LogUserID   = PortalSettings.Current.UserId,
                            LogPortalID = PortalSettings.Current.PortalId,
                            LogTypeKey  = EventLogController.EventLogType.ADMIN_ALERT.ToString(),
                        };
                        logInfo.AddProperty("DnnImageHandler", message);
                        logInfo.AddProperty("IP", ipAddress);
                        logInfo.AddProperty("AllowedDomains", allowedDomains);
                        logController.AddLog(logInfo);
                    }

                    context.Response.StatusCode        = 403;
                    context.Response.StatusDescription = "Forbidden";
                    context.Response.End();
                    return;
                }
            }

            // Generate Image
            var imageMethodData = imageGenCallback(context.Request.QueryString);

            context.Response.ContentType = GetImageMimeType(this.ContentType);
            if (imageMethodData == null)
            {
                throw new InvalidOperationException("The DnnImageHandler cannot return null.");
            }

            if (imageMethodData.IsEmptyImage)
            {
                using (var imageOutputBuffer = new MemoryStream())
                {
                    this.RenderImage(imageMethodData.Image, imageOutputBuffer);
                    var buffer = imageOutputBuffer.GetBuffer();
                    context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                    context.Response.End();
                    return;
                }
            }

            string cacheId = this.GetUniqueIDString(context, uniqueIdStringSeed);

            var cacheCleared = false;
            var profilepic   = context.Request.QueryString["mode"];
            int userId       = -1;

            if ("profilepic".Equals(profilepic, StringComparison.InvariantCultureIgnoreCase))
            {
                if (int.TryParse(context.Request.QueryString["userId"], out userId))
                {
                    cacheCleared = this.ClearDiskImageCacheIfNecessary(userId, PortalSettings.Current.PortalId, cacheId);
                }
            }

            // Handle client cache
            var cachePolicy = context.Response.Cache;

            cachePolicy.SetValidUntilExpires(true);
            if (this.EnableClientCache)
            {
                if (!string.IsNullOrEmpty(context.Request.Headers["If-Modified-Since"]) && !string.IsNullOrEmpty(context.Request.Headers["If-None-Match"]) && !cacheCleared)
                {
                    var provider = CultureInfo.InvariantCulture;
                    var lastMod  = DateTime.ParseExact(context.Request.Headers["If-Modified-Since"], "r", provider).ToLocalTime();
                    var etag     = context.Request.Headers["If-None-Match"];
                    if (lastMod + this.ClientCacheExpiration > this.DateTime_Now && etag == cacheId)
                    {
                        context.Response.StatusCode        = 304;
                        context.Response.StatusDescription = "Not Modified";
                        context.Response.End();
                        return;
                    }
                }

                cachePolicy.SetCacheability(HttpCacheability.Public);
                cachePolicy.SetLastModified(this.DateTime_Now);
                cachePolicy.SetExpires(this.DateTime_Now + this.ClientCacheExpiration);
                cachePolicy.SetETag(cacheId);
            }

            // Handle Server cache
            if (this.EnableServerCache)
            {
                if (!this.IsPicVisibleToCurrentUser(userId))
                {
                    string message = "Not allowed to see profile picture";

                    if (this.LogSecurity)
                    {
                        EventLogController logController = new EventLogController();
                        var logInfo = new LogInfo
                        {
                            LogUserID   = PortalSettings.Current.UserId,
                            LogPortalID = PortalSettings.Current.PortalId,
                            LogTypeKey  = EventLogController.EventLogType.ADMIN_ALERT.ToString(),
                        };
                        logInfo.AddProperty("DnnImageHandler", message);
                        logInfo.AddProperty("IP", ipAddress);
                        logController.AddLog(logInfo);
                    }

                    context.Response.StatusCode        = 403;
                    context.Response.StatusDescription = "Forbidden";
                    context.Response.End();
                    return;
                }

                if (this.ImageStore.TryTransmitIfContains(cacheId, context.Response))
                {
                    context.Response.Flush();
                    return;
                }
            }

            // Check IP Cout boundaries
            if (this.EnableIPCount)
            {
                if (!IPCount.CheckIp(ipAddress))
                {
                    string message = "Too many requests";

                    if (this.LogSecurity)
                    {
                        EventLogController logController = new EventLogController();
                        var logInfo = new LogInfo
                        {
                            LogUserID   = PortalSettings.Current.UserId,
                            LogPortalID = PortalSettings.Current.PortalId,
                            LogTypeKey  = EventLogController.EventLogType.ADMIN_ALERT.ToString(),
                        };
                        logInfo.AddProperty("DnnImageHandler", message);
                        logInfo.AddProperty("IP", ipAddress);
                        logController.AddLog(logInfo);
                    }

                    context.Response.StatusCode        = 429;
                    context.Response.StatusDescription = message;
                    context.Response.End();
                    return;
                }
            }

            if (imageMethodData.HttpStatusCode != null)
            {
                context.Response.StatusCode = (int)imageMethodData.HttpStatusCode;
                context.Response.End();
                return;
            }

            using (var imageOutputBuffer = new MemoryStream())
            {
                Debug.Assert(!(imageMethodData.Image == null && imageMethodData.ImageByteBuffer == null));
                if (imageMethodData.Image != null)
                {
                    this.RenderImage(this.GetImageThroughTransforms(imageMethodData.Image), imageOutputBuffer);
                }
                else if (imageMethodData.ImageByteBuffer != null)
                {
                    this.RenderImage(this.GetImageThroughTransforms(imageMethodData.ImageByteBuffer), imageOutputBuffer);
                }

                byte[] buffer = imageOutputBuffer.GetBuffer();

                context.Response.OutputStream.Write(buffer, 0, buffer.Length);

                if (this.EnableServerCache)
                {
                    this.ImageStore.Add(cacheId, buffer);
                }

                context.Response.End();
            }
        }