Inheritance: MonoBehaviour
 private void OnEnable()
 {
     if (mInstance == null)
     {
         mInstance = this;
     }
 }
 private void OnLocalize(Localization loc)
 {
     if (this.mLanguage != loc.currentLanguage)
     {
         this.Localize();
     }
 }
        public virtual void BuildEntityModel(ref EntityModel entityModel, IComponentPresentation cp, Localization localization)
        {
            using (new Tracer(entityModel, cp, localization))
            {
                MvcData mvcData = GetMvcData(cp);
                Type modelType = ModelTypeRegistry.GetViewModelType(mvcData);

                // NOTE: not using ModelBuilderPipeline here, but directly calling our own implementation.
                BuildEntityModel(ref entityModel, cp.Component, modelType, localization);

                entityModel.XpmMetadata.Add("ComponentTemplateID", cp.ComponentTemplate.Id);
                entityModel.XpmMetadata.Add("ComponentTemplateModified", cp.ComponentTemplate.RevisionDate.ToString("yyyy-MM-ddTHH:mm:ss"));
                entityModel.XpmMetadata.Add("IsRepositoryPublished", cp.IsDynamic ? "true" : "false");
                entityModel.MvcData = mvcData;

                // add html classes to model from metadata
                // TODO: move to CreateViewModel so it can be merged with the same code for a Page/PageTemplate
                IComponentTemplate template = cp.ComponentTemplate;
                if (template.MetadataFields != null && template.MetadataFields.ContainsKey("htmlClasses"))
                {
                    // strip illegal characters to ensure valid html in the view (allow spaces for multiple classes)
                    entityModel.HtmlClasses = template.MetadataFields["htmlClasses"].Value.StripIllegalCharacters(@"[^\w\-\ ]");
                }

                if (cp.IsDynamic)
                {
                    // update Entity Identifier to that of a DCP
                    entityModel.Id = GetDxaIdentifierFromTcmUri(cp.Component.Id, cp.ComponentTemplate.Id);
                }
            }
        }
 public DubizzleURIBuilder(HTTPProtocol protocol, Localization location, MainSection section)
 {
     Location = location ;
     Protocol = protocol;
     Section = section;
     this.Url = new Uri(string.Format("{0}{1}.{2}/{3}", _protocolString, _locationString, baseuri, _sectionString));
 }
        /// <summary>
        /// Add a localization file.
        /// </summary>
        /// <param name="localization">The localization file to add.</param>
        public void AddLocalization(Localization localization)
        {
            if (-1 == this.codepage)
            {
                this.codepage = localization.Codepage;
            }

            foreach (WixVariableRow wixVariableRow in localization.Variables)
            {
                WixVariableRow existingWixVariableRow = (WixVariableRow)this.variables[wixVariableRow.Id];

                if (null == existingWixVariableRow || (existingWixVariableRow.Overridable && !wixVariableRow.Overridable))
                {
                    this.variables[wixVariableRow.Id] = wixVariableRow;
                }
                else if (!wixVariableRow.Overridable)
                {
                    this.OnMessage(WixErrors.DuplicateLocalizationIdentifier(wixVariableRow.SourceLineNumbers, wixVariableRow.Id));
                }
            }

            foreach (KeyValuePair<string, LocalizedControl> localizedControl in localization.LocalizedControls)
            {
                if (!this.localizedControls.ContainsKey(localizedControl.Key))
                {
                    this.localizedControls.Add(localizedControl.Key, localizedControl.Value);
                }
            }
        }
 private void OnDestroy()
 {
     if (mInstance == this)
     {
         mInstance = null;
     }
 }
Exemple #7
0
    /// <summary>
    /// This function is called by the Localization manager via a broadcast SendMessage.
    /// </summary>
    void OnLocalize(Localization loc)
    {
        if (mLanguage != loc.currentLanguage)
        {
            UIWidget w = GetComponent<UIWidget>();
            UILabel lbl = w as UILabel;
            UISprite sp = w as UISprite;

            // If no localization key has been specified, use the label's text as the key
            if (string.IsNullOrEmpty(mLanguage) && string.IsNullOrEmpty(key) && lbl != null) key = lbl.text;

            // If we still don't have a key, use the widget's name
            string val = string.IsNullOrEmpty(key) ? loc.Get(w.name) : loc.Get(key);

            if (lbl != null)
            {
                lbl.text = val;
            }
            else if (sp != null)
            {
                sp.spriteName = val;
                sp.MakePixelPerfect();
            }
            mLanguage = loc.currentLanguage;
        }
    }
 public LocalizationViewModel Build(Localization localization)
 {
     return new LocalizationViewModel()
       {
     Culture = new CultureViewModelBuilder(this.handler).Build(localization.Culture),
     Value = localization.Value
       };
 }
		public App ()
		{
			InitializeComponent ();
			Localization = new Localization ();
			Preferences = DependencyService.Get<IPreferences> ();

			MainPage = new ContentPage ();
		}
Exemple #10
0
 public string Localize(Localization.rowIds in_textID)
 {
     var row = Localization.Instance.GetRow(in_textID);
     if (row != null)
     {
         return row.GetStringData(EditorLanguage);
     }
     return "Unable to find string ID: " + in_textID;
 }
        /// <summary>
        /// Gets the cached local file for a given URL path.
        /// </summary>
        /// <param name="urlPath">The URL path.</param>
        /// <param name="localization">The Localization.</param>
        /// <returns>The path to the local file.</returns>
        internal string GetCachedFile(string urlPath, Localization localization)
        {
            string localFilePath = GetFilePathFromUrl(urlPath, localization);
            using (new Tracer(urlPath, localization, localFilePath))
            {
                Dimensions dimensions;
                urlPath = StripDimensions(urlPath, out dimensions);
                int publicationId = Convert.ToInt32(localization.LocalizationId);

                DateTime lastPublishedDate = SiteConfiguration.CacheProvider.GetOrAdd(
                    urlPath,
                    CacheRegions.BinaryPublishDate,
                    () => GetBinaryLastPublishDate(urlPath, publicationId)
                    );

                if (lastPublishedDate != DateTime.MinValue)
                {
                    if (File.Exists(localFilePath))
                    {
                        if (localization.LastRefresh.CompareTo(lastPublishedDate) < 0)
                        {
                            //File has been modified since last application start but we don't care
                            Log.Debug("Binary with URL '{0}' is modified, but only since last application restart, so no action required", urlPath);
                            return localFilePath;
                        }
                        FileInfo fi = new FileInfo(localFilePath);
                        if (fi.Length > 0)
                        {
                            DateTime fileModifiedDate = File.GetLastWriteTime(localFilePath);
                            if (fileModifiedDate.CompareTo(lastPublishedDate) >= 0)
                            {
                                Log.Debug("Binary with URL '{0}' is still up to date, no action required", urlPath);
                                return localFilePath;
                            }
                        }
                    }
                }

                // Binary does not exist or cached binary is out-of-date
                BinaryMeta binaryMeta = GetBinaryMeta(urlPath, publicationId);
                if (binaryMeta == null)
                {
                    // Binary does not exist in Tridion, it should be removed from the local file system too
                    if (File.Exists(localFilePath))
                    {
                        CleanupLocalFile(localFilePath);
                    }
                    throw new DxaItemNotFoundException(urlPath, localization.LocalizationId);
                }
                BinaryFactory binaryFactory = new BinaryFactory();
                BinaryData binaryData = binaryFactory.GetBinary(publicationId, binaryMeta.Id, binaryMeta.VariantId);

                WriteBinaryToFile(binaryData.Bytes, localFilePath, dimensions);
                return localFilePath;
            }
        }
    // Use this for initialization
    void Start()
    {
        m_Localization = DcGame.getInstance ().transform.FindChild ("Localization(Clone)").GetComponent (typeof(Localization)) as Localization;
        if (m_Localization == null){
            Debug.LogError("CAN'T FIND LOCALIZATION FILE");
        }
        //m_Localization.currentLanguage = "cn";

        m_IsInit = true;
    }
        protected virtual NameValueCollection SetupParameters(SearchQuery searchQuery, Localization localization)
        {
            NameValueCollection result = new NameValueCollection(searchQuery.QueryStringParameters);
            result["fq"] = "publicationid:" + localization.LocalizationId;
            result["q"] = searchQuery.QueryText;
            result["start"] = searchQuery.Start.ToString(CultureInfo.InvariantCulture);
            result["rows"] = searchQuery.PageSize.ToString(CultureInfo.InvariantCulture);

            return result;
        }
Exemple #14
0
 protected virtual string GetSearchIndexUrl(Localization localization)
 {
     // First try the new search.queryURL setting provided by DXA 1.3 TBBs if the Search Query URL can be obtained from Topology Manager.
     string result = localization.GetConfigValue("search.queryURL");
     if (string.IsNullOrEmpty(result))
     {
         result = localization.GetConfigValue("search." + (localization.IsStaging ? "staging" : "live") + "IndexConfig");
     }
     return result;
 }
        /// <summary>
        /// Laedt das Formular zum Eintragen einer Trainingseinheit
        /// </summary>
        /// <param name="id">ID des Trainingsplans, fuer den die Trainingseinheit erstellt werden soll</param>
        /// <returns></returns>
        public ActionResult Create(int id)
        {
            RedirectIfNotLoggedIn();

            ml_WorkoutPlan model = _workoutService.Load(id);

            ILocalization loc = new Localization();
            ViewData["DateFormat"] = loc.GetjQueryDatepickerFormat();

            return View(model);
        }
Exemple #16
0
 /// <summary>
 /// Add a localization file to this library.
 /// </summary>
 /// <param name="localization">The localization file to add.</param>
 public void AddLocalization(Localization localization)
 {
     if (!this.localizations.Contains(localization.Culture))
     {
         this.localizations.Add(localization.Culture, localization);
     }
     else
     {
         Localization existingCulture = (Localization)this.localizations[localization.Culture];
         existingCulture.Merge(localization);
     }
 }
 /// <summary>
 /// Gets prefix for semantic vocabulary.
 /// </summary>
 /// <param name="vocab">Vocabulary name</param>
 /// <param name="loc">The localization</param>
 /// <returns>Prefix for this semantic vocabulary</returns>
 public static string GetPrefix(string vocab, Localization loc)
 {
     string key = loc.LocalizationId;
     if (!_semanticVocabularies.ContainsKey(key) || SiteConfiguration.CheckSettingsNeedRefresh(_vocabSettingsType, loc))
     {
         LoadVocabulariesForLocalization(loc);
     }
     if (_semanticVocabularies.ContainsKey(key))
     {
         List<SemanticVocabulary> vocabs = _semanticVocabularies[key];
         return GetPrefix(vocabs, vocab);
     }
     Log.Error("Localization {0} does not contain vocabulary {1}. Check that the Publish Settings page is published and the application cache is up to date.", loc.LocalizationId, vocab);
     return null;
 }
        public virtual void ExportStandardText(Localization localization)
        {
            string path = EditorUtility.SaveFilePanel("Export Standard Text", "Assets/", "standard.txt", "");
            if (path.Length == 0) 
            {
                return;
            }

            localization.ClearLocalizeableCache();

            string textData = localization.GetStandardText();           
            File.WriteAllText(path, textData);
            AssetDatabase.Refresh();

            ShowNotification(localization);
        }
 public IDictionary Resources(Localization localization)
 {
     string key = localization.LocalizationId;
     //Load resources if they are not already loaded, or if they are out of date and need refreshing
     if (!_resources.ContainsKey(key) || SiteConfiguration.CheckSettingsNeedRefresh(_settingsType, localization))
     {
         LoadResourcesForLocalization(localization);
         if (!_resources.ContainsKey(key))
         {
             Exception ex = new Exception(String.Format("No resources can be found for localization {0}. Check that the localization path is correct and the resources have been published.", localization.LocalizationId));
             Log.Error(ex);
             throw ex;
         }
     }
     return _resources[key];
 }
 private void Awake()
 {
     if (mInstance == null)
     {
         mInstance = this;
         UnityEngine.Object.DontDestroyOnLoad(base.gameObject);
         this.currentLanguage = PlayerPrefs.GetString("Language", this.startingLanguage);
         if ((string.IsNullOrEmpty(this.mLanguage) && (this.languages != null)) && (this.languages.Length > 0))
         {
             this.currentLanguage = this.languages[0].name;
         }
     }
     else
     {
         UnityEngine.Object.Destroy(base.gameObject);
     }
 }
        public virtual void BuildEntityModel(ref EntityModel entityModel, IComponent component, Type baseModelType, Localization localization)
        {
            using (new Tracer(entityModel, component, baseModelType, localization))
            {
                string[] schemaTcmUriParts = component.Schema.Id.Split('-');
                SemanticSchema semanticSchema = SemanticMapping.GetSchema(schemaTcmUriParts[1], localization);

                // The semantic mapping may resolve to a more specific model type than specified by the View Model itself (e.g. Image instead of just MediaItem for Teaser.Media)
                Type modelType = semanticSchema.GetModelTypeFromSemanticMapping(baseModelType);

                MappingData mappingData = new MappingData
                {
                    SemanticSchema = semanticSchema,
                    EntityNames = semanticSchema.GetEntityNames(),
                    TargetEntitiesByPrefix = GetEntityDataFromType(modelType),
                    Content = component.Fields,
                    Meta = component.MetadataFields,
                    TargetType = modelType,
                    SourceEntity = component,
                    Localization = localization
                };

                entityModel = (EntityModel)CreateViewModel(mappingData);
                entityModel.Id = GetDxaIdentifierFromTcmUri(component.Id);
                entityModel.XpmMetadata = GetXpmMetadata(component);

                if (entityModel is MediaItem && component.Multimedia != null && component.Multimedia.Url != null)
                {
                    MediaItem mediaItem = (MediaItem)entityModel;
                    mediaItem.Url = component.Multimedia.Url;
                    mediaItem.FileName = component.Multimedia.FileName;
                    mediaItem.FileSize = component.Multimedia.Size;
                    mediaItem.MimeType = component.Multimedia.MimeType;
                }

                if (entityModel is Link)
                {
                    Link link = (Link)entityModel;
                    if (String.IsNullOrEmpty(link.Url))
                    {
                        link.Url = SiteConfiguration.LinkResolver.ResolveLink(component.Id);
                    }
                }
            }
        }
    // Use this for initialization
    void Awake()
    {
        if (Instance != null && Instance != this) {
            //destroy other instances
            Destroy(gameObject);
            return;
        }

        //Singleton instance
        Instance = this;

        //on't destroy between scenes
        DontDestroyOnLoad(gameObject);

        if (SourceFile == null) {
            this.enabled = false;
            return;
        }
        _localizationDictionary = new Dictionary<string, Dictionary<string, string>>();

        UpdateDictionary();

        //new List<MainMenu_Settings>(Resources.FindObjectsOfTypeAll<MainMenu_Settings>()).ForEach(i => i.gameObject.SetActive(true));

        var dropdownObject = new List<Dropdown>(Resources.FindObjectsOfTypeAll<Dropdown>()).Find(i => i.name == "LanguageSelect");
        if (dropdownObject == null) {
            Debug.LogError("Localization::UpdateLocalization >> Make sure the languageSelect dropdown is called \"LanguageSelect\"");
            CurrentLanguage = "English";
        } else {
            dropdownObject.options.Clear();
            foreach (var key in _localizationDictionary.Keys) {
                Dropdown.OptionData data = new Dropdown.OptionData(key);
                dropdownObject.options.Add(data);
            }

            CurrentLanguage = dropdownObject.options[PlayerPrefs.GetInt("Language")].text;
        }
        dropdownObject.value = PlayerPrefs.GetInt("Language");

        //        new List<MainMenu_Settings>(Resources.FindObjectsOfTypeAll<MainMenu_Settings>()).ForEach(i => i.gameObject.SetActive(false));

        UpdateLocalization();
    }
        private void CreateLocalizations(PropertyInfo propertyInfo, Dictionary dictionary)
        {
            IEnumerable<Culture> cultures = this.Storage.GetRepository<ICultureRepository>().All();

              foreach (Culture culture in cultures)
              {
            Localization localization = new Localization();

            localization.DictionaryId = dictionary.Id;
            localization.CultureId = culture.Id;

            string identity = propertyInfo.Name + culture.Code;
            string value = this.Request.Form[identity];

            localization.Value = value;
            this.Storage.GetRepository<ILocalizationRepository>().Create(localization);
              }

              this.Storage.Save();
        }
        public void ExecuteQuery(SearchQuery searchQuery, Type resultType, Localization localization)
        {
            using (new Tracer(searchQuery, resultType, localization))
            {
                string searchIndexUrl = GetSearchIndexUrl(localization);
                NameValueCollection parameters = SetupParameters(searchQuery, localization);
                SearchResults results = ExecuteQuery(searchIndexUrl, parameters);
                if (results.HasError)
                {
                    Log.Error("Error executing Search Query on URL '{0}': {1}", results.QueryUrl ?? searchIndexUrl, results.ErrorDetail);
                }
                Log.Debug("Search Query '{0}' returned {1} results.", results.QueryText ?? results.QueryUrl, results.Total);

                searchQuery.Total = results.Total;
                searchQuery.HasMore = searchQuery.Start + searchQuery.PageSize <= results.Total;
                searchQuery.CurrentPage = ((searchQuery.Start - 1) / searchQuery.PageSize) + 1;

                foreach (SearchResult result in results.Items)
                {
                    searchQuery.Results.Add(MapResult(result, resultType, searchQuery.SearchItemView));
                }
            }
        }
        public virtual void ExportLocalizationFile(Localization localization)
        {
            string path = EditorUtility.SaveFilePanelInProject("Export Localization File",
                                                               "localization.csv",
                                                               "csv",
                                                               "Please enter a filename to save the localization file to");
            if (path.Length == 0) 
            {
                return;
            }

            string csvData = localization.GetCSVData();         
            File.WriteAllText(path, csvData);
            AssetDatabase.ImportAsset(path);

            TextAsset textAsset = AssetDatabase.LoadAssetAtPath(path, typeof(TextAsset)) as TextAsset;
            if (textAsset != null)
            {
                localization.LocalizationFile = textAsset;
            }

            ShowNotification(localization);
        }
 private static void LoadResourcesForLocalization(Localization loc)
 {
     Log.Debug("Loading resources for localization : {0}", loc.LocalizationId);
     string key = loc.LocalizationId;
     Dictionary<string, object> resources = new Dictionary<string, object>();
     string url = Path.Combine(loc.Path.ToCombinePath(true), SiteConfiguration.SystemFolder, @"resources\_all.json").Replace("\\","/");
     string jsonData = SiteConfiguration.ContentProvider.GetStaticContentItem(url, loc).GetText();
     if (jsonData!=null)
     {
         //The _all.json file contains a list of all other resources files to load
         dynamic bootstrapJson = Json.Decode(jsonData);
         foreach (string resourceUrl in bootstrapJson.files)
         {
             string type = resourceUrl.Substring(resourceUrl.LastIndexOf("/", StringComparison.Ordinal) + 1);
             type = type.Substring(0, type.LastIndexOf(".", StringComparison.Ordinal)).ToLower();
             jsonData = SiteConfiguration.ContentProvider.GetStaticContentItem(resourceUrl, loc).GetText();
             if (jsonData!=null)
             {
                 Log.Debug("Loading resources from file: {0}", resourceUrl);
                 foreach (KeyValuePair<string, object> item in GetResourcesFromFile(jsonData))
                 {
                     //we ensure resource key uniqueness by adding the type (which comes from the filename)
                     resources.Add(String.Format("{0}.{1}", type, item.Key), item.Value);
                 }
             }
             else
             {
                 Log.Error("Resource file: {0} does not exist for localization {1} - skipping", resourceUrl, key);
             }
         }
         SiteConfiguration.ThreadSafeSettingsUpdate<Dictionary<string, object>>(_settingsType, _resources, key, resources);
     }
     else
     {
         Log.Error("Localization resource bootstrap file: {0} does not exist for localization {1}. Check that the Publish Settings page has been published in this publication.", url, loc.LocalizationId);
     }
 }
Exemple #27
0
 private void OnLocalize(Localization loc)
 {
     if (this.mLanguage != loc.currentLanguage)
     {
         UIWidget component = base.GetComponent<UIWidget>();
         UILabel uILabel = component as UILabel;
         UISprite uISprite = component as UISprite;
         if (string.IsNullOrEmpty(this.mLanguage) && string.IsNullOrEmpty(this.key) && uILabel != null)
         {
             this.key = uILabel.text;
         }
         string str = (!string.IsNullOrEmpty(this.key) ? loc.Get(this.key) : loc.Get(component.name));
         if (uILabel != null)
         {
             uILabel.text = str;
         }
         else if (uISprite != null)
         {
             uISprite.spriteName = str;
             uISprite.MakePixelPerfect();
         }
         this.mLanguage = loc.currentLanguage;
     }
 }
Exemple #28
0
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            cmdAssociate.Click  += cmdAssociate_Click;
            cmdCreateUser.Click += cmdCreateUser_Click;
            cmdProceed.Click    += cmdProceed_Click;

            //Verify if portal has a customized login page
            if (!Null.IsNull(PortalSettings.LoginTabId) && Globals.IsAdminControl())
            {
                if (Globals.ValidateLoginTabID(PortalSettings.LoginTabId))
                {
                    //login page exists and trying to access this control directly with url param -> not allowed
                    var parameters = new string[3];
                    if (!string.IsNullOrEmpty(Request.QueryString["returnUrl"]))
                    {
                        parameters[0] = "returnUrl=" + Request.QueryString["returnUrl"];
                    }
                    if (!string.IsNullOrEmpty(Request.QueryString["username"]))
                    {
                        parameters[1] = "username="******"username"];
                    }
                    if (!string.IsNullOrEmpty(Request.QueryString["verificationcode"]))
                    {
                        parameters[2] = "verificationcode=" + Request.QueryString["verificationcode"];
                    }
                    Response.Redirect(Globals.NavigateURL(PortalSettings.LoginTabId, "", parameters));
                }
            }
            if (Page.IsPostBack == false)
            {
                try
                {
                    PageNo = 0;
                }
                catch (Exception ex)
                {
                    //control not there
                    Logger.Error(ex);
                }
            }
            if (!Request.IsAuthenticated || UserNeedsVerification())
            {
                ShowPanel();
            }
            else             //user is already authenticated
            {
                //if a Login Page has not been specified for the portal
                if (Globals.IsAdminControl())
                {
                    //redirect to current page
                    Response.Redirect(Globals.NavigateURL(), true);
                }
                else                 //make module container invisible if user is not a page admin
                {
                    if (TabPermissionController.CanAdminPage())
                    {
                        ShowPanel();
                    }
                    else
                    {
                        ContainerControl.Visible = false;
                    }
                }
            }
            divCaptcha.Visible = UseCaptcha;

            if (UseCaptcha)
            {
                ctlCaptcha.ErrorMessage = Localization.GetString("InvalidCaptcha", Localization.SharedResourceFile);
                ctlCaptcha.Text         = Localization.GetString("CaptchaText", Localization.SharedResourceFile);
            }
        }
Exemple #29
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        ///
        /// </summary>
        /// <remarks>
        /// - Obtain PortalSettings from Current Context
        /// - redirect to a specific tab based on name
        /// - if first time loading this page then reload to avoid caching
        /// - set page title and stylesheet
        /// - check to see if we should show the Assembly Version in Page Title
        /// - set the background image if there is one selected
        /// - set META tags, copyright, keywords and description
        /// </remarks>
        /// <history>
        ///     [sun1]	1/19/2004	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        private void InitializePage()
        {
            var tabController = new TabController();

            //redirect to a specific tab based on name
            if (!String.IsNullOrEmpty(Request.QueryString["tabname"]))
            {
                TabInfo tab = tabController.GetTabByName(Request.QueryString["TabName"], ((PortalSettings)HttpContext.Current.Items["PortalSettings"]).PortalId);
                if (tab != null)
                {
                    var parameters = new List <string>(); //maximum number of elements
                    for (int intParam = 0; intParam <= Request.QueryString.Count - 1; intParam++)
                    {
                        switch (Request.QueryString.Keys[intParam].ToLower())
                        {
                        case "tabid":
                        case "tabname":
                            break;

                        default:
                            parameters.Add(
                                Request.QueryString.Keys[intParam] + "=" + Request.QueryString[intParam]);
                            break;
                        }
                    }
                    Response.Redirect(Globals.NavigateURL(tab.TabID, Null.NullString, parameters.ToArray()), true);
                }
                else
                {
                    //404 Error - Redirect to ErrorPage
                    Exceptions.ProcessHttpException(Request);
                }
            }
            if (Request.IsAuthenticated)
            {
                switch (Host.AuthenticatedCacheability)
                {
                case "0":
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    break;

                case "1":
                    Response.Cache.SetCacheability(HttpCacheability.Private);
                    break;

                case "2":
                    Response.Cache.SetCacheability(HttpCacheability.Public);
                    break;

                case "3":
                    Response.Cache.SetCacheability(HttpCacheability.Server);
                    break;

                case "4":
                    Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache);
                    break;

                case "5":
                    Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
                    break;
                }
            }

            //page comment
            if (Host.DisplayCopyright)
            {
                Comment += string.Concat(Environment.NewLine,
                                         "<!--**********************************************************************************-->",
                                         Environment.NewLine,
                                         "<!-- DotNetNuke - http://www.dotnetnuke.com                                          -->",
                                         Environment.NewLine,
                                         "<!-- Copyright (c) 2002-2012                                                          -->",
                                         Environment.NewLine,
                                         "<!-- by DotNetNuke Corporation                                                        -->",
                                         Environment.NewLine,
                                         "<!--**********************************************************************************-->",
                                         Environment.NewLine);
            }
            Page.Header.Controls.AddAt(0, new LiteralControl(Comment));

            if (PortalSettings.ActiveTab.PageHeadText != Null.NullString && !Globals.IsAdminControl())
            {
                Page.Header.Controls.Add(new LiteralControl(PortalSettings.ActiveTab.PageHeadText));
            }

            //set page title
            string strTitle = PortalSettings.PortalName;

            if (IsPopUp)
            {
                var slaveModule = UIUtilities.GetSlaveModule(PortalSettings.ActiveTab.TabID);

                //Skip is popup is just a tab (no slave module)
                if (slaveModule.DesktopModuleID != Null.NullInteger)
                {
                    var control = ModuleControlFactory.CreateModuleControl(slaveModule) as IModuleControl;
                    control.LocalResourceFile = slaveModule.ModuleControl.ControlSrc.Replace(Path.GetFileName(slaveModule.ModuleControl.ControlSrc), "") + Localization.LocalResourceDirectory + "/" +
                                                Path.GetFileName(slaveModule.ModuleControl.ControlSrc);
                    var title = Localization.LocalizeControlTitle(control);

                    strTitle += string.Concat(" > ", PortalSettings.ActiveTab.TabName);
                    strTitle += string.Concat(" > ", title);
                }
                else
                {
                    strTitle += string.Concat(" > ", PortalSettings.ActiveTab.TabName);
                }
            }
            else
            {
                foreach (TabInfo tab in PortalSettings.ActiveTab.BreadCrumbs)
                {
                    strTitle += string.Concat(" > ", tab.TabName);
                }

                //tab title override
                if (!string.IsNullOrEmpty(PortalSettings.ActiveTab.Title))
                {
                    strTitle = PortalSettings.ActiveTab.Title;
                }
            }
            Title = strTitle;

            //set the background image if there is one selected
            if (!IsPopUp && FindControl("Body") != null)
            {
                if (!string.IsNullOrEmpty(PortalSettings.BackgroundFile))
                {
                    var fileInfo = GetBackgroundFileInfo();
                    var url      = FileManager.Instance.GetUrl(fileInfo);

                    ((HtmlGenericControl)FindControl("Body")).Attributes["style"] = string.Concat("background-image: url('", url, "')");
                }
            }

            //META Refresh
            if (PortalSettings.ActiveTab.RefreshInterval > 0 && Request.QueryString["ctl"] == null)
            {
                MetaRefresh.Content = PortalSettings.ActiveTab.RefreshInterval.ToString();
            }
            else
            {
                MetaRefresh.Visible = false;
            }

            //META description
            if (!string.IsNullOrEmpty(PortalSettings.ActiveTab.Description))
            {
                Description = PortalSettings.ActiveTab.Description;
            }
            else
            {
                Description = PortalSettings.Description;
            }

            //META keywords
            if (!string.IsNullOrEmpty(PortalSettings.ActiveTab.KeyWords))
            {
                KeyWords = PortalSettings.ActiveTab.KeyWords;
            }
            else
            {
                KeyWords = PortalSettings.KeyWords;
            }
            if (Host.DisplayCopyright)
            {
                KeyWords += ",DotNetNuke,DNN";
            }

            //META copyright
            if (!string.IsNullOrEmpty(PortalSettings.FooterText))
            {
                Copyright = PortalSettings.FooterText.Replace("[year]", DateTime.Now.Year.ToString());
            }
            else
            {
                Copyright = string.Concat("Copyright (c) ", DateTime.Now.Year, " by ", PortalSettings.PortalName);
            }

            //META generator
            if (Host.DisplayCopyright)
            {
                Generator = "DotNetNuke ";
            }
            else
            {
                Generator = "";
            }

            //META Robots
            if (Request.QueryString["ctl"] != null &&
                (Request.QueryString["ctl"] == "Login" || Request.QueryString["ctl"] == "Register"))
            {
                MetaRobots.Content = "NOINDEX, NOFOLLOW";
            }
            else
            {
                MetaRobots.Content = "INDEX, FOLLOW";
            }

            //NonProduction Label Injection
            if (NonProductionVersion() && Host.DisplayBetaNotice && !IsPopUp)
            {
                string versionString = string.Format(" ({0} Version: {1})", DotNetNukeContext.Current.Application.Status,
                                                     DotNetNukeContext.Current.Application.Version);
                Title += versionString;
            }

            //register DNN SkinWidgets Inititialization scripts
            if (PortalSettings.EnableSkinWidgets)
            {
                jQuery.RequestRegistration();
                // don't use the new API to register widgets until we better understand their asynchronous script loading requirements.
                ClientAPI.RegisterStartUpScript(Page, "initWidgets", string.Format("<script type=\"text/javascript\" src=\"{0}\" ></script>", ResolveUrl("~/Resources/Shared/scripts/initWidgets.js")));
            }
        }
Exemple #30
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Contains the functionality to populate the Root aspx page with controls
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks>
        /// - obtain PortalSettings from Current Context
        /// - set global page settings.
        /// - initialise reference paths to load the cascading style sheets
        /// - add skin control placeholder.  This holds all the modules and content of the page.
        /// </remarks>
        /// <history>
        ///     [sun1]	1/19/2004	Created
        ///		[jhenning] 8/24/2005 Added logic to look for post originating from a ClientCallback
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            //set global page settings
            InitializePage();

            //load skin control and register UI js
            UI.Skins.Skin ctlSkin;
            if (PortalSettings.EnablePopUps)
            {
                ctlSkin = IsPopUp ? UI.Skins.Skin.GetPopUpSkin(this) : UI.Skins.Skin.GetSkin(this);

                //register popup js
                jQuery.RegisterJQueryUI(Page);

                var popupFilePath = HttpContext.Current.IsDebuggingEnabled
                                   ? "~/js/Debug/dnn.modalpopup.js"
                                   : "~/js/dnn.modalpopup.js";

                ClientResourceManager.RegisterScript(this, popupFilePath);
            }
            else
            {
                ctlSkin = UI.Skins.Skin.GetSkin(this);
            }

            // DataBind common paths for the client resource loader
            ClientResourceLoader.DataBind();

            //check for and read skin package level doctype
            SetSkinDoctype();

            //Manage disabled pages
            if (PortalSettings.ActiveTab.DisableLink)
            {
                if (TabPermissionController.CanAdminPage())
                {
                    var heading = Localization.GetString("PageDisabled.Header");
                    var message = Localization.GetString("PageDisabled.Text");
                    UI.Skins.Skin.AddPageMessage(ctlSkin, heading, message,
                                                 ModuleMessage.ModuleMessageType.YellowWarning);
                }
                else
                {
                    if (PortalSettings.HomeTabId > 0)
                    {
                        Response.Redirect(Globals.NavigateURL(PortalSettings.HomeTabId), true);
                    }
                    else
                    {
                        Response.Redirect(Globals.GetPortalDomainName(PortalSettings.PortalAlias.HTTPAlias, Request, true), true);
                    }
                }
            }
            //Manage canonical urls
            if (PortalSettings.PortalAliasMappingMode == PortalSettings.PortalAliasMapping.CanonicalUrl && PortalSettings.PortalAlias.HTTPAlias != PortalSettings.DefaultPortalAlias)
            {
                var originalurl = Context.Items["UrlRewrite:OriginalUrl"].ToString();

                //Add Canonical <link>
                var canonicalLink = new HtmlLink();
                canonicalLink.Href = originalurl.Replace(PortalSettings.PortalAlias.HTTPAlias, PortalSettings.DefaultPortalAlias);
                canonicalLink.Attributes.Add("rel", "canonical");

                // Add the HtmlLink to the Head section of the page.
                Page.Header.Controls.Add(canonicalLink);
            }

            //check if running with known account defaults
            var messageText = "";

            if (Request.IsAuthenticated && string.IsNullOrEmpty(Request.QueryString["runningDefault"]) == false)
            {
                var userInfo = HttpContext.Current.Items["UserInfo"] as UserInfo;
                //only show message to default users
                if ((userInfo.Username.ToLower() == "admin") || (userInfo.Username.ToLower() == "host"))
                {
                    messageText = RenderDefaultsWarning();
                    var messageTitle = Localization.GetString("InsecureDefaults.Title", Localization.GlobalResourceFile);
                    UI.Skins.Skin.AddPageMessage(ctlSkin, messageTitle, messageText, ModuleMessage.ModuleMessageType.RedError);
                }
            }

            //add CSS links
            ClientResourceManager.RegisterStyleSheet(this, Globals.HostPath + "default.css", FileOrder.Css.DefaultCss);
            ClientResourceManager.RegisterStyleSheet(this, ctlSkin.SkinPath + "skin.css", FileOrder.Css.SkinCss);
            ClientResourceManager.RegisterStyleSheet(this, ctlSkin.SkinSrc.Replace(".ascx", ".css"), FileOrder.Css.SpecificSkinCss);

            //add skin to page
            SkinPlaceHolder.Controls.Add(ctlSkin);

            ClientResourceManager.RegisterStyleSheet(this, PortalSettings.HomeDirectory + "portal.css", 60);

            //add Favicon
            ManageFavicon();

            //ClientCallback Logic
            ClientAPI.HandleClientAPICallbackEvent(this);

            //add viewstateuserkey to protect against CSRF attacks
            if (User.Identity.IsAuthenticated)
            {
                ViewStateUserKey = User.Identity.Name;
            }
        }
Exemple #31
0
        public HttpResponseMessage UpdateIpFilter(UpdateIpFilterRequest request)
        {
            try
            {
                var ipf = new IPFilterInfo();
                ipf.IPAddress  = request.IPAddress;
                ipf.SubnetMask = request.SubnetMask;
                ipf.RuleType   = request.RuleType;

                if ((ipf.IPAddress == "127.0.0.1" || ipf.IPAddress == "localhost" || ipf.IPAddress == "::1" || ipf.IPAddress == "*") && ipf.RuleType == 2)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Format(Localization.GetString("CannotDeleteLocalhost.Text", Components.Constants.LocalResourcesFile))));
                }

                if (IPFilterController.Instance.IsAllowableDeny(HttpContext.Current.Request.UserHostAddress, ipf) == false)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Format(Localization.GetString("CannotDeleteIPInUse.Text", Components.Constants.LocalResourcesFile))));
                }

                if (request.IPFilterID > 0)
                {
                    ipf.IPFilterID = request.IPFilterID;
                    IPFilterController.Instance.UpdateIPFilter(ipf);
                }
                else
                {
                    IPFilterController.Instance.AddIPFilter(ipf);
                }
                return(Request.CreateResponse(HttpStatusCode.OK, new { Success = true }));
            }
            catch (ArgumentException exc)
            {
                Logger.Info(exc);
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, exc.Message));
            }
            catch (Exception exc)
            {
                Logger.Error(exc);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc));
            }
        }
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// The BuildTree helper method is used to build the tree
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// -----------------------------------------------------------------------------
        private void BuildTree(DNNNode objNode, bool blnPODRequest)
        {
            bool blnAddUpNode = false;
            DNNNodeCollection objNodes;

            objNodes = GetNavigationNodes(objNode);

            if (blnPODRequest == false)
            {
                if (!string.IsNullOrEmpty(Level))
                {
                    switch (Level.ToLower())
                    {
                    case "root":
                        break;

                    case "child":
                        blnAddUpNode = true;
                        break;

                    default:
                        if (Level.ToLower() != "root" && PortalSettings.ActiveTab.BreadCrumbs.Count > 1)
                        {
                            blnAddUpNode = true;
                        }
                        break;
                    }
                }
            }

            //add goto Parent node
            if (blnAddUpNode)
            {
                var objParentNode = new DNNNode();
                objParentNode.ID          = PortalSettings.ActiveTab.ParentId.ToString();
                objParentNode.Key         = objParentNode.ID;
                objParentNode.Text        = Localization.GetString("Parent", Localization.GetResourceFile(this, MyFileName));
                objParentNode.ToolTip     = Localization.GetString("GoUp", Localization.GetResourceFile(this, MyFileName));
                objParentNode.CSSClass    = NodeCssClass;
                objParentNode.Image       = ResolveUrl(TreeGoUpImage);
                objParentNode.ClickAction = eClickAction.PostBack;
                objNodes.InsertBefore(0, objParentNode);
            }
            foreach (DNNNode objPNode in objNodes) //clean up to do in processnodes???
            {
                ProcessNodes(objPNode);
            }
            Bind(objNodes);

            //technically this should always be a dnntree.  If using dynamic controls Nav.ascx should be used.  just being safe.
            if (Control.NavigationControl is DnnTree)
            {
                var objTree = (DnnTree)Control.NavigationControl;
                if (objTree.SelectedTreeNodes.Count > 0)
                {
                    var objTNode = (TreeNode)objTree.SelectedTreeNodes[1];
                    if (objTNode.DNNNodes.Count > 0) //only expand it if nodes are not pending
                    {
                        objTNode.Expand();
                    }
                }
            }
        }
        /// <summary>
        /// </summary>
        /// <remarks>
        /// </remarks>
        private bool CreateModuleDefinition()
        {
            try
            {
                if (PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == GetClassName()) == null)
                {
                    var controlName = Null.NullString;

                    //Create module folder
                    CreateModuleFolder();

                    //Create module control
                    controlName = CreateModuleControl();
                    if (controlName != "")
                    {
                        //Create package
                        var objPackage = new PackageInfo();
                        objPackage.Name         = GetClassName();
                        objPackage.FriendlyName = txtModule.Text;
                        objPackage.Description  = txtDescription.Text;
                        objPackage.Version      = new Version(1, 0, 0);
                        objPackage.PackageType  = "Module";
                        objPackage.License      = "";
                        objPackage.Owner        = txtOwner.Text;
                        objPackage.Organization = txtOwner.Text;
                        objPackage.FolderName   = "DesktopModules/" + GetFolderName();
                        objPackage.License      = "The license for this package is not currently included within the installation file, please check with the vendor for full license details.";
                        objPackage.ReleaseNotes = "This package has no Release Notes.";
                        PackageController.Instance.SaveExtensionPackage(objPackage);

                        //Create desktopmodule
                        var objDesktopModule = new DesktopModuleInfo();
                        objDesktopModule.DesktopModuleID         = Null.NullInteger;
                        objDesktopModule.ModuleName              = GetClassName();
                        objDesktopModule.FolderName              = GetFolderName();
                        objDesktopModule.FriendlyName            = txtModule.Text;
                        objDesktopModule.Description             = txtDescription.Text;
                        objDesktopModule.IsPremium               = false;
                        objDesktopModule.IsAdmin                 = false;
                        objDesktopModule.Version                 = "01.00.00";
                        objDesktopModule.BusinessControllerClass = "";
                        objDesktopModule.CompatibleVersions      = "";
                        objDesktopModule.AdminPage               = "";
                        objDesktopModule.HostPage                = "";
                        objDesktopModule.Dependencies            = "";
                        objDesktopModule.Permissions             = "";
                        objDesktopModule.PackageID               = objPackage.PackageID;
                        objDesktopModule.DesktopModuleID         = DesktopModuleController.SaveDesktopModule(objDesktopModule, false, true);
                        objDesktopModule = DesktopModuleController.GetDesktopModule(objDesktopModule.DesktopModuleID, Null.NullInteger);

                        //Add OwnerName to the DesktopModule taxonomy and associate it with this module
                        var vocabularyId      = -1;
                        var termId            = -1;
                        var objTermController = DotNetNuke.Entities.Content.Common.Util.GetTermController();
                        var objTerms          = objTermController.GetTermsByVocabulary("Module_Categories");
                        foreach (Term term in objTerms)
                        {
                            vocabularyId = term.VocabularyId;
                            if (term.Name == txtOwner.Text)
                            {
                                termId = term.TermId;
                            }
                        }
                        if (termId == -1)
                        {
                            termId = objTermController.AddTerm(new Term(vocabularyId)
                            {
                                Name = txtOwner.Text
                            });
                        }
                        var objTerm = objTermController.GetTerm(termId);
                        var objContentController = DotNetNuke.Entities.Content.Common.Util.GetContentController();
                        var objContent           = objContentController.GetContentItem(objDesktopModule.ContentItemId);
                        objTermController.AddTermToContent(objTerm, objContent);

                        //Add desktopmodule to all portals
                        DesktopModuleController.AddDesktopModuleToPortals(objDesktopModule.DesktopModuleID);

                        //Create module definition
                        var objModuleDefinition = new ModuleDefinitionInfo();
                        objModuleDefinition.ModuleDefID     = Null.NullInteger;
                        objModuleDefinition.DesktopModuleID = objDesktopModule.DesktopModuleID;
                        // need core enhancement to have a unique DefinitionName
                        objModuleDefinition.FriendlyName = GetClassName();
                        //objModuleDefinition.FriendlyName = txtModule.Text;
                        //objModuleDefinition.DefinitionName = GetClassName();
                        objModuleDefinition.DefaultCacheTime = 0;
                        objModuleDefinition.ModuleDefID      = ModuleDefinitionController.SaveModuleDefinition(objModuleDefinition, false, true);

                        //Create modulecontrol
                        var objModuleControl = new ModuleControlInfo();
                        objModuleControl.ModuleControlID          = Null.NullInteger;
                        objModuleControl.ModuleDefID              = objModuleDefinition.ModuleDefID;
                        objModuleControl.ControlKey               = "";
                        objModuleControl.ControlSrc               = "DesktopModules/" + GetFolderName() + "/" + controlName;
                        objModuleControl.ControlTitle             = "";
                        objModuleControl.ControlType              = SecurityAccessLevel.View;
                        objModuleControl.HelpURL                  = "";
                        objModuleControl.IconFile                 = "";
                        objModuleControl.ViewOrder                = 0;
                        objModuleControl.SupportsPartialRendering = false;
                        objModuleControl.SupportsPopUps           = false;
                        ModuleControlController.AddModuleControl(objModuleControl);

                        //Update current module to reference new moduledefinition
                        var objModule = ModuleController.Instance.GetModule(ModuleId, TabId, false);
                        objModule.ModuleDefID = objModuleDefinition.ModuleDefID;
                        objModule.ModuleTitle = txtModule.Text;

                        //HACK - need core enhancement to be able to update ModuleDefID
                        using (DotNetNuke.Data.DataProvider.Instance().ExecuteSQL(
                                   "UPDATE {databaseOwner}{objectQualifier}Modules SET ModuleDefID=" + objModule.ModuleDefID + " WHERE ModuleID=" + ModuleId))
                        {
                        }

                        ModuleController.Instance.UpdateModule(objModule);

                        return(true);
                    }
                    else
                    {
                        DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("TemplateProblem.ErrorMessage", LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning);
                        return(false);
                    }
                }
                else
                {
                    DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("AlreadyExists.ErrorMessage", LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning);
                    return(false);
                }
            }
            catch (Exception exc)
            {
                Exceptions.LogException(exc);
                DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, exc.ToString(), ModuleMessage.ModuleMessageType.RedError);
                return(false);
            }
        }
Exemple #34
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// ValidateUser runs when the user has been authorized by the data store.  It validates for
        /// things such as an expiring password, valid profile, or missing DNN User Association
        /// </summary>
        /// <param name="objUser">The logged in User</param>
        /// <param name="ignoreExpiring">Ignore the situation where the password is expiring (but not yet expired)</param>
        /// -----------------------------------------------------------------------------
        private void ValidateUser(UserInfo objUser, bool ignoreExpiring)
        {
            UserValidStatus validStatus   = UserValidStatus.VALID;
            string          strMessage    = Null.NullString;
            DateTime        expiryDate    = Null.NullDate;
            bool            okToShowPanel = true;

            validStatus = UserController.ValidateUser(objUser, PortalId, ignoreExpiring);

            if (PasswordConfig.PasswordExpiry > 0)
            {
                expiryDate = objUser.Membership.LastPasswordChangeDate.AddDays(PasswordConfig.PasswordExpiry);
            }
            UserId = objUser.UserID;

            //Check if the User has valid Password/Profile
            switch (validStatus)
            {
            case UserValidStatus.VALID:
                //check if the user is an admin/host and validate their IP
                if (Host.EnableIPChecking)
                {
                    bool isAdminUser = objUser.IsSuperUser || PortalSettings.UserInfo.IsInRole(PortalSettings.AdministratorRoleName);;
                    if (isAdminUser)
                    {
                        if (IPFilterController.Instance.IsIPBanned(Request.UserHostAddress))
                        {
                            new PortalSecurity().SignOut();
                            AddModuleMessage("IPAddressBanned", ModuleMessage.ModuleMessageType.RedError, true);
                            okToShowPanel = false;
                            break;
                        }
                    }
                }

                //Set the Page Culture(Language) based on the Users Preferred Locale
                if ((objUser.Profile != null) && (objUser.Profile.PreferredLocale != null))
                {
                    Localization.SetLanguage(objUser.Profile.PreferredLocale);
                }
                else
                {
                    Localization.SetLanguage(PortalSettings.DefaultLanguage);
                }

                //Set the Authentication Type used
                AuthenticationController.SetAuthenticationType(AuthenticationType);

                //Complete Login
                UserController.UserLogin(PortalId, objUser, PortalSettings.PortalName, AuthenticationLoginBase.GetIPAddress(), RememberMe);

                //redirect browser
                var redirectUrl = RedirectURL;

                //Clear the cookie
                HttpContext.Current.Response.Cookies.Set(new HttpCookie("returnurl", "")
                {
                    Expires = DateTime.Now.AddDays(-1)
                });

                Response.Redirect(redirectUrl, true);
                break;

            case UserValidStatus.PASSWORDEXPIRED:
                strMessage = string.Format(Localization.GetString("PasswordExpired", LocalResourceFile), expiryDate.ToLongDateString());
                AddLocalizedModuleMessage(strMessage, ModuleMessage.ModuleMessageType.YellowWarning, true);
                PageNo             = 2;
                pnlProceed.Visible = false;
                break;

            case UserValidStatus.PASSWORDEXPIRING:
                strMessage = string.Format(Localization.GetString("PasswordExpiring", LocalResourceFile), expiryDate.ToLongDateString());
                AddLocalizedModuleMessage(strMessage, ModuleMessage.ModuleMessageType.YellowWarning, true);
                PageNo             = 2;
                pnlProceed.Visible = true;
                break;

            case UserValidStatus.UPDATEPASSWORD:
                AddModuleMessage("PasswordUpdate", ModuleMessage.ModuleMessageType.YellowWarning, true);
                PageNo             = 2;
                pnlProceed.Visible = false;
                break;

            case UserValidStatus.UPDATEPROFILE:
                //Save UserID in ViewState so that can update profile later.
                UserId = objUser.UserID;

                //When the user need update its profile to complete login, we need clear the login status because if the logrin is from
                //3rd party login provider, it may call UserController.UserLogin because they doesn't check this situation.
                new PortalSecurity().SignOut();
                //Admin has forced profile update
                AddModuleMessage("ProfileUpdate", ModuleMessage.ModuleMessageType.YellowWarning, true);
                PageNo = 3;
                break;
            }
            if (okToShowPanel)
            {
                ShowPanel();
            }
        }
Exemple #35
0
        public HttpResponseMessage GetSecurityBulletins()
        {
            try
            {
                var    plartformVersion = System.Reflection.Assembly.LoadFrom(Globals.ApplicationMapPath + @"\bin\DotNetNuke.dll").GetName().Version;
                string sRequest         = string.Format("http://update.dotnetnuke.com/security.aspx?type={0}&name={1}&version={2}",
                                                        DotNetNukeContext.Current.Application.Type,
                                                        "DNNCORP.CE",
                                                        Globals.FormatVersion(plartformVersion, "00", 3, ""));

                //format for display with "." delimiter
                string sVersion = Globals.FormatVersion(plartformVersion, "00", 3, ".");

                // make remote request
                Stream oStream = null;
                try
                {
                    HttpWebRequest oRequest = Globals.GetExternalRequest(sRequest);
                    oRequest.Timeout = 10000; // 10 seconds
                    WebResponse oResponse = oRequest.GetResponse();
                    oStream = oResponse.GetResponseStream();
                }
                catch (Exception oExc)
                {
                    // connectivity issues
                    if (PortalSecurity.IsInRoles(PortalSettings.AdministratorRoleId.ToString()))
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Format(Localization.GetString("RequestFailed_Admin.Text", Components.Constants.LocalResourcesFile), sRequest)));
                    }
                    else
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, Localization.GetString("RequestFailed_User.Text", Components.Constants.LocalResourcesFile) + oExc.Message));
                    }
                }

                // load XML document
                StreamReader oReader = new StreamReader(oStream);
                XmlDocument  oDoc    = new XmlDocument {
                    XmlResolver = null
                };
                oDoc.LoadXml(oReader.ReadToEnd());

                List <object> items = new List <object>();
                foreach (XmlNode selectNode in oDoc.SelectNodes(BULLETIN_XMLNODE_PATH))
                {
                    items.Add(new
                    {
                        Title       = selectNode.SelectSingleNode("title") != null ? selectNode.SelectSingleNode("title").InnerText : "",
                        Link        = selectNode.SelectSingleNode("link") != null ? selectNode.SelectSingleNode("link").InnerText : "",
                        Description = selectNode.SelectSingleNode("description") != null ? selectNode.SelectSingleNode("description").InnerText : "",
                        Author      = selectNode.SelectSingleNode("author") != null ? selectNode.SelectSingleNode("author").InnerText : "",
                        PubDate     = selectNode.SelectSingleNode("pubDate") != null ? selectNode.SelectSingleNode("pubDate").InnerText.Split(' ')[0] : ""
                    });
                }

                var response = new
                {
                    Success = true,
                    Results = new
                    {
                        PlatformVersion   = sVersion,
                        SecurityBulletins = items
                    }
                };

                return(Request.CreateResponse(HttpStatusCode.OK, response));
            }
            catch (Exception exc)
            {
                Logger.Error(exc);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc));
            }
        }
Exemple #36
0
        /// <summary>
        /// The Page_Load event handler on this User Control is used to
        /// obtain a DataReader of banner information from the Banners
        /// table, and then databind the results to a templated DataList
        /// server control.  It uses the DotNetNuke.BannerDB()
        /// data component to encapsulate all data functionality.
        /// </summary>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            cmdUpdate.Click += cmdUpdate_Click;
            cmdCancel.Click += cmdCancel_Click;
            DNNTxtBannerGroup.PopulateOnDemand += DNNTxtBannerGroup_PopulateOnDemand;

            try
            {
                if (!Page.IsPostBack)
                {
                    //Obtain banner information from the Banners table and bind to the list control
                    var objBannerTypes = new BannerTypeController();

                    cboType.DataSource = objBannerTypes.GetBannerTypes();
                    cboType.DataBind();
                    cboType.Items.Insert(0, new ListItem(Localization.GetString("AllTypes", LocalResourceFile), "-1"));

                    if (ModuleId > 0)
                    {
                        if (optSource.Items.FindByValue(Convert.ToString(Settings["bannersource"])) != null)
                        {
                            optSource.Items.FindByValue(Convert.ToString(Settings["bannersource"])).Selected = true;
                        }
                        else
                        {
                            optSource.Items.FindByValue("L").Selected = true;
                        }
                        if (cboType.Items.FindByValue(Convert.ToString(Settings["bannertype"])) != null)
                        {
                            cboType.Items.FindByValue(Convert.ToString(Settings["bannertype"])).Selected = true;
                        }
                        if (!String.IsNullOrEmpty(Convert.ToString(Settings["bannergroup"])))
                        {
                            DNNTxtBannerGroup.Text = Convert.ToString(Settings["bannergroup"]);
                        }
                        if (optOrientation.Items.FindByValue(Convert.ToString(Settings["orientation"])) != null)
                        {
                            optOrientation.Items.FindByValue(Convert.ToString(Settings["orientation"])).Selected = true;
                        }
                        else
                        {
                            optOrientation.Items.FindByValue("V").Selected = true;
                        }
                        if (!String.IsNullOrEmpty(Convert.ToString(Settings["bannercount"])))
                        {
                            txtCount.Text = Convert.ToString(Settings["bannercount"]);
                        }
                        else
                        {
                            txtCount.Text = "1";
                        }
                        if (!String.IsNullOrEmpty(Convert.ToString(Settings["border"])))
                        {
                            txtBorder.Text = Convert.ToString(Settings["border"]);
                        }
                        else
                        {
                            txtBorder.Text = "0";
                        }
                        if (!String.IsNullOrEmpty(Convert.ToString(Settings["padding"])))
                        {
                            txtPadding.Text = Convert.ToString(Settings["padding"]);
                        }
                        else
                        {
                            txtPadding.Text = "4";
                        }
                        txtBorderColor.Text           = Convert.ToString(Settings["bordercolor"]);
                        txtRowHeight.Text             = Convert.ToString(Settings["rowheight"]);
                        txtColWidth.Text              = Convert.ToString(Settings["colwidth"]);
                        txtBannerClickThroughURL.Text = Convert.ToString(Settings["bannerclickthroughurl"]);
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Exemple #37
0
        /// <summary>
        /// UserAuthenticated runs when the user is authenticated by one of the child
        /// Authentication controls
        /// </summary>
        protected void UserAuthenticated(object sender, UserAuthenticatedEventArgs e)
        {
            LoginStatus = e.LoginStatus;

            //Check the Login Status
            switch (LoginStatus)
            {
            case UserLoginStatus.LOGIN_USERNOTAPPROVED:
                switch (e.Message)
                {
                case "UnverifiedUser":
                    if (e.User != null)
                    {
                        //First update the profile (if any properties have been passed)
                        AuthenticationType = e.AuthenticationType;
                        ProfileProperties  = e.Profile;
                        RememberMe         = e.RememberMe;
                        UpdateProfile(e.User, true);
                        ValidateUser(e.User, false);
                    }
                    break;

                case "EnterCode":
                    AddModuleMessage(e.Message, ModuleMessage.ModuleMessageType.YellowWarning, true);
                    break;

                case "InvalidCode":
                case "UserNotAuthorized":
                    AddModuleMessage(e.Message, ModuleMessage.ModuleMessageType.RedError, true);
                    break;

                default:
                    AddLocalizedModuleMessage(e.Message, ModuleMessage.ModuleMessageType.RedError, true);
                    break;
                }
                break;

            case UserLoginStatus.LOGIN_USERLOCKEDOUT:
                if (Host.AutoAccountUnlockDuration > 0)
                {
                    AddLocalizedModuleMessage(string.Format(Localization.GetString("UserLockedOut", LocalResourceFile), Host.AutoAccountUnlockDuration), ModuleMessage.ModuleMessageType.RedError, true);
                }
                else
                {
                    AddLocalizedModuleMessage(Localization.GetString("UserLockedOut_ContactAdmin", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError, true);
                }
                //notify administrator about account lockout ( possible hack attempt )
                var Custom = new ArrayList {
                    e.UserToken
                };

                var message = new Message
                {
                    FromUserID = PortalSettings.AdministratorId,
                    ToUserID   = PortalSettings.AdministratorId,
                    Subject    = Localization.GetSystemMessage(PortalSettings, "EMAIL_USER_LOCKOUT_SUBJECT", Localization.GlobalResourceFile, Custom),
                    Body       = Localization.GetSystemMessage(PortalSettings, "EMAIL_USER_LOCKOUT_BODY", Localization.GlobalResourceFile, Custom),
                    Status     = MessageStatusType.Unread
                };
                //_messagingController.SaveMessage(_message);

                Mail.SendEmail(PortalSettings.Email, PortalSettings.Email, message.Subject, message.Body);
                break;

            case UserLoginStatus.LOGIN_FAILURE:
                //A Login Failure can mean one of two things:
                //  1 - User was authenticated by the Authentication System but is not "affiliated" with a DNN Account
                //  2 - User was not authenticated
                if (e.Authenticated)
                {
                    AutoRegister       = e.AutoRegister;
                    AuthenticationType = e.AuthenticationType;
                    ProfileProperties  = e.Profile;
                    UserToken          = e.UserToken;
                    if (AutoRegister)
                    {
                        InitialiseUser();
                        User.Membership.Password = UserController.GeneratePassword();

                        ctlUser.User = User;

                        //Call the Create User method of the User control so that it can create
                        //the user and raise the appropriate event(s)
                        ctlUser.CreateUser();
                    }
                    else
                    {
                        PageNo = 1;
                        ShowPanel();
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(e.Message))
                    {
                        AddModuleMessage("LoginFailed", ModuleMessage.ModuleMessageType.RedError, true);
                    }
                    else
                    {
                        AddLocalizedModuleMessage(e.Message, ModuleMessage.ModuleMessageType.RedError, true);
                    }
                }
                break;

            default:
                if (e.User != null)
                {
                    //First update the profile (if any properties have been passed)
                    AuthenticationType = e.AuthenticationType;
                    ProfileProperties  = e.Profile;
                    RememberMe         = e.RememberMe;
                    UpdateProfile(e.User, true);
                    ValidateUser(e.User, (e.AuthenticationType != "DNN"));
                }
                break;
            }
        }
Exemple #38
0
 public DatabindingForLocalizationViewModel(Localization localization)
 {
     this.localization = localization;
 }
 public string GetMessageLabel()
 {
     return(Localization.GetString("SeeAllMessage", Localization.GetResourceFile(this, MyFileName)));
 }
 public string GetNotificationLabel()
 {
     return(Localization.GetString("SeeAllNotification", Localization.GetResourceFile(this, MyFileName)));
 }
Exemple #41
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StringLengthLocalizeAttribute"/> class.
 /// </summary>
 /// <param name="id">The text id.</param>
 /// <param name="minimumLength">The allowed string minimum length.</param>
 /// <param name="maximumLength">The allowed string maximum length.</param>
 public StringLengthLocalizeAttribute(string id, int maximumLength, int minimumLength) : base(new Func <string>(() => Localization.Localize(id)))
 {
     MaximumLength = maximumLength;
     MinimumLength = minimumLength;
 }
Exemple #42
0
 public override string GetInteractionName(Sim s, Sim target, InteractionObjectPair interaction)
 {
     return(Localization.LocalizeString(s.IsFemale, "NonaMena/BreastFeedBaby/BreastFeed:InteractionName", new object[0]));
 }
Exemple #43
0
        public void ItemMove(ChannelClient client, Packet packet)
        {
            var entityId        = packet.GetLong();
            var untrustedSource = (Pocket)packet.GetByte();             // Discard this, NA does too
            var target          = (Pocket)packet.GetByte();
            var unk             = packet.GetByte();
            var targetX         = packet.GetByte();
            var targetY         = packet.GetByte();

            // Get creature
            var creature = client.GetCreatureSafe(packet.Id);

            // Get item
            var item   = creature.Inventory.GetItemSafe(entityId);
            var source = item.Info.Pocket;

            // Check lock
            if ((source.IsEquip() || target.IsEquip()) && !creature.Can(Locks.ChangeEquipment))
            {
                Log.Debug("ChangeEquipment locked for '{0}'.", creature.Name);
                goto L_Fail;
            }

            // Check bag
            if (item.IsBag && target.IsBag() && !ChannelServer.Instance.Conf.World.Bagception)
            {
                Send.ServerMessage(creature, Localization.Get("Item bags can't be stored inside other bags."));
                goto L_Fail;
            }

            // Check TwinSword feature
            if (target == creature.Inventory.LeftHandPocket && !item.IsShieldLike && creature.RightHand != null && !AuraData.FeaturesDb.IsEnabled("TwinSword"))
            {
                // TODO: Is this message sufficient? Do we need a better one?
                //   Do we need one at all? Or would that confuse people even more?
                Send.Notice(creature, NoticeType.MiddleSystem, Localization.Get("The Dual Wielding feature hasn't been enabled yet."));
                goto L_Fail;
            }

            // Stop moving when changing weapons
            if ((target >= Pocket.RightHand1 && target <= Pocket.Magazine2) || (source >= Pocket.RightHand1 && source <= Pocket.Magazine2))
            {
                creature.StopMove();
            }

            // Try to move item
            if (!creature.Inventory.Move(item, target, targetX, targetY))
            {
                goto L_Fail;
            }

            // Give Ranged Attack when equipping a (cross)bow
            if (target.IsEquip() && (item.HasTag("/bow/|/crossbow/")) && !creature.Skills.Has(SkillId.RangedAttack))
            {
                creature.Skills.Give(SkillId.RangedAttack, SkillRank.Novice);
            }

            // Give Playing Instrument when equipping an instrument
            if (target.IsEquip() && (item.HasTag("/instrument/")) && !creature.Skills.Has(SkillId.PlayingInstrument))
            {
                creature.Skills.Give(SkillId.PlayingInstrument, SkillRank.Novice);
            }

            // Inform about temp moves (items in temp don't count for quest objectives?)
            if (source == Pocket.Temporary && target == Pocket.Cursor)
            {
                ChannelServer.Instance.Events.OnPlayerReceivesItem(creature, item.Info.Id, item.Info.Amount);
            }

            Send.ItemMoveR(creature, true);
            return;

L_Fail:
            Send.ItemMoveR(creature, false);
        }
        public HttpControllerDescriptor SelectController(HttpRequestMessage request)
        {
            Requires.NotNull("request", request);

            string controllerName           = GetControllerName(request);
            IEnumerable <string> namespaces = GetNameSpaces(request);

            if (namespaces == null || !namespaces.Any() || String.IsNullOrEmpty(controllerName))
            {
                throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound,
                                                                            "Unable to locate a controller for " +
                                                                            request.RequestUri));
            }

            var matches = new List <HttpControllerDescriptor>();

            foreach (string ns in namespaces)
            {
                string fullName = GetFullName(controllerName, ns);

                HttpControllerDescriptor descriptor;
                if (DescriptorCache.TryGetValue(fullName, out descriptor))
                {
                    matches.Add(descriptor);
                }
            }

            if (matches.Count == 1)
            {
                return(matches.First());
            }

            //only errors thrown beyond this point
            if (matches.Count == 0)
            {
                throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound, string.Format(Localization.GetString("ControllerNotFound", Localization.ExceptionsResourceFile), request.RequestUri, string.Join(", ", namespaces))));
            }

            throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.Conflict, string.Format(Localization.GetString("AmbiguousController", Localization.ExceptionsResourceFile), controllerName, string.Join(", ", namespaces))));
        }
Exemple #45
0
    /// <summary>
    /// load game from json string
    /// !!! move it to Game !!!
    /// </summary>
    void Load(string json)
    {
        Game       gm = Game.Load(json);
        MainScript ms = Camera.main.GetComponent <MainScript>();

        ms.ClearEverything();
        ms.Loading();

        CopyItems(gm.m_allArmy);
        CopyItems(gm.m_allBuildings);
        CopyItems(gm.m_allItems);
        CopyItems(gm.m_allMaterails);
        CopyItems(gm.m_allScience);
        CopyItems(gm.m_allResources);
        CopyItems(gm.m_allProcesses);
        CopyItems(gm.m_allWildAnimals);
        CopyItems(gm.m_allDomestic);

        AbstractObject.m_sEverything[AbstractObject.m_sEverything.Count - 1].
        Copy(gm.m_population);

        ms.PlaceOpenedItems(AbstractObject.GetOpennedItems());

        CopyTools(gm.m_allArmy);
        CopyTools(gm.m_allBuildings);
        CopyTools(gm.m_allItems);
        CopyTools(gm.m_allMaterails);
        CopyTools(gm.m_allProcesses);

        foreach (GameObject go in MainScript.m_sAllItems)
        {
            try
            {
                IconScript    ics = go.GetComponent <IconScript>();
                Game.GameIcon gic = null;
                foreach (var itm in gm.m_allGameIcons)
                {
                    if (itm.m_itmName == ics.m_thisItem.m_name)
                    {
                        gic = itm;
                        break;
                    }
                }
                if (gic == null)
                {
                    continue;             //throw new System.Exception("Object not found");
                }
                gm.m_allGameIcons.Remove(gic);
                ics.transform.position = gic.m_pos;
            }
            catch (Exception ex)
            {
                Debug.Log(ex.Message);
            }
        }

#if !UNITY_WEBGL
        Localization.GetLocalization().ChangeLanguage(Settings.GetSettings().m_localization.m_currentLanguage);
#endif
        TimeScript tsc = Camera.main.GetComponent <TimeScript>();
        tsc.m_day   = gm.m_day;
        tsc.m_year  = gm.m_year;
        tsc.m_speed = gm.m_speed;

        LearningTip.m_sCanShow = gm.m_canShowTooltips;

        gameObject.SetActive(false);
    }
Exemple #46
0
        public HttpResponseMessage DeleteIpFilter(int filterId)
        {
            try
            {
                IList <IPFilterInfo> currentRules             = IPFilterController.Instance.GetIPFilters();
                List <IPFilterInfo>  currentWithDeleteRemoved = (from p in currentRules where p.IPFilterID != filterId select p).ToList();

                if (IPFilterController.Instance.CanIPStillAccess(HttpContext.Current.Request.UserHostAddress, currentWithDeleteRemoved) == false)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Format(Localization.GetString("CannotDelete.Text", Components.Constants.LocalResourcesFile))));
                }
                else
                {
                    var ipf = new IPFilterInfo();
                    ipf.IPFilterID = filterId;
                    IPFilterController.Instance.DeleteIPFilter(ipf);
                    return(Request.CreateResponse(HttpStatusCode.OK, new { Success = true }));
                }
            }
            catch (Exception exc)
            {
                Logger.Error(exc);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc));
            }
        }
Exemple #47
0
        public void ItemMagnet(ChannelClient client, Packet packet)
        {
            var creature = client.GetCreatureSafe(packet.Id);

            Send.MsgBox(creature, Localization.Get("Not supported yet."));
        }
 public override MvcData GetDefaultView(Localization localization)
 {
     return(new MvcData("Test:TSI1758TestEmbedded2"));
 }
Exemple #49
0
        public void UseItem(ChannelClient client, Packet packet)
        {
            var entityId = packet.GetLong();

            var creature = client.GetCreatureSafe(packet.Id);

            // Check states
            if (creature.IsDead)
            {
                Log.Warning("Player '{0}' tried to use item while being dead.", creature.Name);
                goto L_Fail;
            }

            // Check lock
            if (!creature.Can(Locks.UseItem))
            {
                Log.Debug("UseItem locked for '{0}'.", creature.Name);
                goto L_Fail;
            }

            // Get item
            var item = creature.Inventory.GetItem(entityId);

            if (item == null)
            {
                goto L_Fail;
            }

            // Meta Data Scripts
            var gotMetaScript = false;

            {
                // Sealed books
                if (item.MetaData1.Has("MGCWRD") && item.MetaData1.Has("MGCSEL"))
                {
                    var magicWords = item.MetaData1.GetString("MGCWRD");
                    try
                    {
                        var sms = new MagicWordsScript(magicWords);
                        sms.Run(creature, item);

                        gotMetaScript = true;
                    }
                    catch (Exception ex)
                    {
                        Log.Exception(ex, "Problem while running magic words script '{0}'", magicWords);
                        Send.ServerMessage(creature, Localization.Get("Unimplemented item."));
                        goto L_Fail;
                    }
                }
            }

            // Aura Scripts
            if (!gotMetaScript)
            {
                // Get script
                var script = ChannelServer.Instance.ScriptManager.ItemScripts.Get(item.Info.Id);
                if (script == null)
                {
                    Log.Unimplemented("Item script for '{0}' not found.", item.Info.Id);
                    Send.ServerMessage(creature, Localization.Get("This item isn't implemented yet."));
                    goto L_Fail;
                }

                // Run script
                try
                {
                    script.OnUse(creature, item);
                }
                catch (NotImplementedException)
                {
                    Log.Unimplemented("UseItem: Item OnUse method for '{0}'.", item.Info.Id);
                    Send.ServerMessage(creature, Localization.Get("This item isn't implemented completely yet."));
                    goto L_Fail;
                }
            }

            ChannelServer.Instance.Events.OnPlayerUsesItem(creature, item);

            // Decrease item count
            if (item.Data.Consumed)
            {
                creature.Inventory.Decrement(item);
                ChannelServer.Instance.Events.OnPlayerRemovesItem(creature, item.Info.Id, 1);
            }

            // Break seal after use
            if (item.MetaData1.Has("MGCSEL"))
            {
                item.MetaData1.Remove("MGCWRD");
                item.MetaData1.Remove("MGCSEL");
                Send.ItemUpdate(creature, item);
            }

            // Mandatory stat update
            Send.StatUpdate(creature, StatUpdateType.Private, Stat.Life, Stat.LifeInjured, Stat.Mana, Stat.Stamina, Stat.Hunger);
            Send.StatUpdate(creature, StatUpdateType.Public, Stat.Life, Stat.LifeInjured);

            Send.UseItemR(creature, true, item.Info.Id);
            return;

L_Fail:
            Send.UseItemR(creature, false, 0);
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            ServicesFramework.Instance.RequestAjaxAntiForgerySupport();
            JavaScript.RequestRegistration(CommonJs.DnnPlugins);
            ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/scripts/dnn.searchBox.js");
            ClientResourceManager.RegisterStyleSheet(Page, "~/Resources/Shared/stylesheets/dnn.searchBox.css", FileOrder.Css.ModuleCss);
            ClientResourceManager.RegisterScript(Page, "~/DesktopModules/admin/SearchResults/dnn.searchResult.js");

            CultureCode = Thread.CurrentThread.CurrentCulture.ToString();

            foreach (string o in SearchContentSources)
            {
                var item = new ListItem(o, o)
                {
                    Selected = CheckedScopeItem(o)
                };
                SearchScopeList.Items.Add(item);
            }

            SearchScopeList.Options.Localization["AllItemsChecked"] = Localization.GetString("AllFeaturesSelected",
                                                                                             Localization.GetResourceFile(this, MyFileName));

            var pageSizeItem = ResultsPerPageList.FindItemByValue(PageSize.ToString());

            if (pageSizeItem != null)
            {
                pageSizeItem.Selected = true;
            }

            SetLastModifiedFilter();
        }
Exemple #51
0
 public static string GetCanvasSizeLocalizedString(string size)
 {
     return(Localization.LocalizeString("Gameplay/Objects/HobbiesSkills/Easel/CanvasSize:" + size, new object[0]));
 }
Exemple #52
0
 protected string GetSharedResource(string key)
 {
     return(Localization.GetString(key, "~/DesktopModules/ActiveForums/App_LocalResources/SharedResources.resx"));
 }
        public override void HourlyCallback()
        {
            if (GameUtils.IsOnVacation() || GameUtils.IsUniversityWorld())
            {
                Common.DebugNotify(mMom.FullName + Common.NewLine + "HumanSurrogatePregnancy.HourlyCallback" + Common.NewLine + " - Pregnancy Paused");
                return;
            }

            mHourOfPregnancy++;

            string msg = mMom.FullName + Common.NewLine + "HumanSurrogatePregnancy.HourlyCallback" + Common.NewLine +
                         " - Hour: " + mHourOfPregnancy + Common.NewLine;

            if (mHourOfPregnancy == kHourToStartPregnantMotives)
            {
                mMom.BuffManager.AddElement(BuffNames.Nauseous, Origin.FromUnknown);
            }

            if (mHourOfPregnancy < kHourToShowPregnantBuff && mHourOfPregnancy > kHourToStartPregnantMotives)
            {
                mMom.BuffManager.AddElement(BuffNames.Nauseous, Origin.FromUnknown);
            }

            if (mMom.Household.IsTouristHousehold)
            {
                msg += " - Foreign Sim" + Common.NewLine;

                ForeignVisitorsSituation foreignVisitorsSituation = ForeignVisitorsSituation.TryGetForeignVisitorsSituation(mMom);

                if (mHourOfPregnancy == kForeignSimDisplaysTNS && foreignVisitorsSituation != null)
                {
                    StyledNotification.Show(new StyledNotification.Format(Localization.LocalizeString("Gameplay/ActorSystems/Pregnancy:ForeignBabyIsComingTNS",
                                                                                                      new object[] { mMom }), StyledNotification.NotificationStyle.kGameMessagePositive), "glb_tns_baby_coming_r2");
                }

                if (mHourOfPregnancy == kForeignSimLeavesWorld)
                {
                    if (foreignVisitorsSituation != null)
                    {
                        foreignVisitorsSituation.MakeGuestGoHome(mMom);
                    }
                    else if (mMom.SimDescription.AssignedRole != null)
                    {
                        mMom.SimDescription.AssignedRole.RemoveSimFromRole();
                    }
                }

                if (mHourOfPregnancy > kForeignSimLeavesWorld)
                {
                    Common.DebugNotify(msg);

                    mHourOfPregnancy--;
                    return;
                }
            }

            if (mHourOfPregnancy == kHourToShowPregnantBuff)
            {
                msg += " - Adding Pregnant Buff" + Common.NewLine;
                Common.DebugNotify(msg);

                InteractionInstance interactionInstance = ShowPregnancyEx.Singleton.CreateInstance(mMom, mMom,
                                                                                                   new InteractionPriority(InteractionPriorityLevel.ESRB), false, false);
                interactionInstance.Hidden = true;
                mMom.InteractionQueue.AddNext(interactionInstance);
                return;
            }

            if (mHourOfPregnancy >= kHourToStartWalkingPregnant)
            {
                ActiveTopic.AddToSim(mMom, "Pregnant", mMom.SimDescription);
                RequestPregnantWalkStyle();
            }

            if (mHourOfPregnancy == kHourToStartContractions)
            {
                msg += " - Starting Labor" + Common.NewLine;

                for (int i = 0; i < kNumberOfPuddlesForWaterBreak; i++)
                {
                    PuddleManager.AddPuddle(mMom.PositionOnFloor);
                }

                if (mMom.IsSelectable)
                {
                    StyledNotification.Show(new StyledNotification.Format(Localization.LocalizeString("Gameplay/ActorSystems/Pregnancy:BabyIsComingTNS",
                                                                                                      new object[] { mMom }), StyledNotification.NotificationStyle.kGameMessageNegative), "glb_tns_baby_coming_r2");
                }

                mMom.BuffManager.RemoveElement(BuffNames.Pregnant);
                mMom.BuffManager.AddElement(BuffNames.BabyIsComing, Origin.FromPregnancy);

                if (mContractionBroadcast != null)
                {
                    mContractionBroadcast.Dispose();
                }

                mContractionBroadcast = new ReactionBroadcaster(mMom, kContractionBroadcasterParams,
                                                                new ReactionBroadcaster.BroadcastCallback(StartReaction), new ReactionBroadcaster.BroadcastCallback(CancelReaction));
                mMom.AddInteraction(TakeToHospital.Singleton);
                InteractionInstance entry = HaveContraction.Singleton.CreateInstance(mMom, mMom, new InteractionPriority(InteractionPriorityLevel.High, 10f), false, false);
                mMom.InteractionQueue.Add(entry);
                mContractionsAlarm = mMom.AddAlarmRepeating(5f, TimeUnit.Minutes, new AlarmTimerCallback(TriggerContraction),
                                                            5f, TimeUnit.Minutes, "Trigger Contractions Alarm", AlarmType.AlwaysPersisted);
                EventTracker.SendEvent(EventTypeId.kPregnancyContractionsStarted, mMom);
            }

            if (mHourOfPregnancy == kHoursOfPregnancy)
            {
                msg += " - Having the Baby";
                HaveTheBaby();
            }

            SetPregoBlendShape();

            Common.DebugNotify(msg);
        }
Exemple #54
0
 public override void Show()
 {
     if (base.enabled && NGUITools.GetActive(base.gameObject) && UIPopupList.mChild == null && this.atlas != null && this.isValid && this.items.Count > 0)
     {
         this.mLabelList.Clear();
         base.StopCoroutine("CloseIfUnselected");
         UICamera.selectedObject = (UICamera.hoveredObject ?? base.gameObject);
         this.mSelection         = UICamera.selectedObject;
         this.source             = UICamera.selectedObject;
         if (this.source == null)
         {
             Debug.LogError("Popup list needs a source object...");
             return;
         }
         this.mOpenFrame = Time.frameCount;
         if (this.mPanel == null)
         {
             this.mPanel = UIPanel.Find(base.transform);
             if (this.mPanel == null)
             {
                 return;
             }
         }
         UIPopupList.mChild       = new GameObject("Drop-down List");
         UIPopupList.mChild.layer = base.gameObject.layer;
         UIPopupList.current      = this;
         Transform transform = UIPopupList.mChild.transform;
         transform.parent = this.mPanel.cachedTransform;
         Vector3 vector;
         Vector3 vector2;
         Vector3 vector3;
         if (this.openOn == UIPopupList.OpenOn.Manual && this.mSelection != base.gameObject)
         {
             vector  = UICamera.lastEventPosition;
             vector2 = this.mPanel.cachedTransform.InverseTransformPoint(this.mPanel.anchorCamera.ScreenToWorldPoint(vector));
             vector3 = vector2;
             transform.localPosition = vector2;
             vector = transform.position;
         }
         else
         {
             Bounds bounds = NGUIMath.CalculateRelativeWidgetBounds(this.mPanel.cachedTransform, base.transform, false, false);
             vector2 = bounds.min;
             vector3 = bounds.max;
             transform.localPosition = vector2;
             vector = transform.position;
         }
         base.StartCoroutine("CloseIfUnselected");
         transform.localRotation = Quaternion.identity;
         transform.localScale    = Vector3.one;
         this.mBackground        = NGUITools.AddSprite(UIPopupList.mChild, this.atlas, this.backgroundSprite);
         this.mBackground.pivot  = UIWidget.Pivot.TopLeft;
         this.mBackground.depth  = NGUITools.CalculateNextDepth(this.mPanel.gameObject);
         this.mBackground.color  = this.backgroundColor;
         Vector4 border = this.mBackground.border;
         this.mBgBorder = border.y;
         this.mBackground.cachedTransform.localPosition = new Vector3(0f, border.y, 0f);
         this.mHighlight       = NGUITools.AddSprite(UIPopupList.mChild, this.atlas, this.highlightSprite);
         this.mHighlight.pivot = UIWidget.Pivot.TopLeft;
         this.mHighlight.color = this.highlightColor;
         UISpriteData atlasSprite = this.mHighlight.GetAtlasSprite();
         if (atlasSprite == null)
         {
             return;
         }
         float            num             = (float)atlasSprite.borderTop;
         float            num2            = (float)this.activeFontSize;
         float            activeFontScale = this.activeFontScale;
         float            num3            = num2 * activeFontScale;
         float            num4            = 0f;
         float            num5            = -this.padding.y;
         List <UILabel>   list            = new List <UILabel>();
         List <UITexture> list2           = new List <UITexture>();
         if (!this.items.Contains(this.mSelectedItem))
         {
             this.mSelectedItem = null;
         }
         int i     = 0;
         int count = this.items.Count;
         while (i < count)
         {
             string  text    = this.items[i];
             Texture texture = this.itemsIcon[i];
             UILabel uilabel = NGUITools.AddWidget <UILabel>(UIPopupList.mChild);
             uilabel.name         = i.ToString();
             uilabel.pivot        = UIWidget.Pivot.TopLeft;
             uilabel.bitmapFont   = this.bitmapFont;
             uilabel.trueTypeFont = this.trueTypeFont;
             uilabel.fontSize     = this.fontSize;
             uilabel.fontStyle    = this.fontStyle;
             string text2 = (!this.isLocalized) ? text : Localization.Get(text);
             if (this.toUpper)
             {
                 text2 = text2.ToUpper();
             }
             uilabel.text  = text2;
             uilabel.color = this.textColor;
             uilabel.cachedTransform.localPosition = new Vector3(border.x + this.padding.x - uilabel.pivotOffset.x + this.iconWidth, num5, -1f);
             uilabel.overflowMethod = UILabel.Overflow.ResizeFreely;
             uilabel.alignment      = this.alignment;
             list.Add(uilabel);
             if (texture)
             {
                 UITexture uitexture = NGUITools.AddWidget <UITexture>(uilabel.gameObject);
                 uitexture.name        = i.ToString();
                 uitexture.pivot       = UIWidget.Pivot.TopLeft;
                 uitexture.width       = 28;
                 uitexture.height      = 18;
                 uitexture.mainTexture = texture;
                 uitexture.cachedTransform.localPosition = new Vector3(-this.iconWidth, 0f, -1f);
                 list2.Add(uitexture);
             }
             else
             {
                 list2.Add(null);
             }
             num5 -= num3;
             num5 -= this.padding.y;
             num4  = Mathf.Max(num4, uilabel.printedSize.x);
             UIEventListener uieventListener = UIEventListener.Get(uilabel.gameObject);
             uieventListener.onHover   = new UIEventListener.BoolDelegate(base.OnItemHover);
             uieventListener.onPress   = new UIEventListener.BoolDelegate(base.OnItemPress);
             uieventListener.parameter = text;
             if (this.mSelectedItem == text || (i == 0 && string.IsNullOrEmpty(this.mSelectedItem)))
             {
                 base.Highlight(uilabel, true);
             }
             this.mLabelList.Add(uilabel);
             i++;
         }
         num4 = Mathf.Max(num4 + this.iconWidth, vector3.x - vector2.x - (border.x + this.padding.x) * 2f);
         float   num6    = num4;
         Vector3 vector4 = new Vector3(num6 * 0.5f, -num3 * 0.5f, 0f);
         Vector3 vector5 = new Vector3(num6, num3 + this.padding.y, 1f);
         int     j       = 0;
         int     count2  = list.Count;
         while (j < count2)
         {
             UILabel uilabel2 = list[j];
             NGUITools.AddWidgetCollider(uilabel2.gameObject);
             uilabel2.autoResizeBoxCollider = false;
             BoxCollider component = uilabel2.GetComponent <BoxCollider>();
             if (component != null)
             {
                 vector4.z        = component.center.z;
                 component.center = vector4;
                 component.size   = vector5;
             }
             else
             {
                 BoxCollider2D component2 = uilabel2.GetComponent <BoxCollider2D>();
                 component2.offset = vector4;
                 component2.size   = vector5;
             }
             j++;
         }
         int width = Mathf.RoundToInt(num4);
         num4 += (border.x + this.padding.x) * 2f;
         num5 -= border.y;
         this.mBackground.width  = Mathf.RoundToInt(num4);
         this.mBackground.height = Mathf.RoundToInt(-num5 + border.y);
         int k      = 0;
         int count3 = list.Count;
         while (k < count3)
         {
             UILabel uilabel3 = list[k];
             uilabel3.overflowMethod = UILabel.Overflow.ShrinkContent;
             uilabel3.width          = width;
             k++;
         }
         float num7 = 2f * this.atlas.pixelSize;
         float f    = num4 - (border.x + this.padding.x) * 2f + (float)atlasSprite.borderLeft * num7;
         float f2   = num3 + num * num7;
         this.mHighlight.width  = Mathf.RoundToInt(f);
         this.mHighlight.height = Mathf.RoundToInt(f2);
         bool     flag     = this.position == UIPopupList.Position.Above;
         UICamera uicamera = UICamera.FindCameraForLayer(this.mSelection.layer);
         if (this.position == UIPopupList.Position.Auto && uicamera != null)
         {
             flag = (uicamera.cachedCamera.WorldToViewportPoint(vector).y < 0.5f);
         }
         if (this.isAnimated)
         {
             base.AnimateColor(this.mBackground);
             if (Time.timeScale == 0f || Time.timeScale >= 0.1f)
             {
                 float bottom = num5 + num3;
                 base.Animate(this.mHighlight, flag, bottom);
                 int l      = 0;
                 int count4 = list.Count;
                 while (l < count4)
                 {
                     base.Animate(list[l], flag, bottom);
                     l++;
                 }
                 base.AnimateScale(this.mBackground, flag, bottom);
             }
         }
         if (flag)
         {
             vector2.y = vector3.y - border.y;
             vector3.y = vector2.y + (float)this.mBackground.height;
             vector3.x = vector2.x + (float)this.mBackground.width;
             transform.localPosition = new Vector3(vector2.x, vector3.y - border.y, vector2.z);
         }
         else
         {
             vector3.y = vector2.y + border.y;
             vector2.y = vector3.y - (float)this.mBackground.height;
             vector3.x = vector2.x + (float)this.mBackground.width;
         }
         Transform parent = this.mPanel.cachedTransform.parent;
         if (parent != null)
         {
             vector2 = this.mPanel.cachedTransform.TransformPoint(vector2);
             vector3 = this.mPanel.cachedTransform.TransformPoint(vector3);
             vector2 = parent.InverseTransformPoint(vector2);
             vector3 = parent.InverseTransformPoint(vector3);
         }
         if (uicamera != null)
         {
             transform.position = base.transform.TransformPoint(new Vector3((float)(-(float)this.mBackground.width) + this.iconWidth / 2f, (float)(((!flag) ? -1 : 1) * (this.mBackground.height + 10)), 0f));
         }
         else
         {
             Vector3 b = (!this.mPanel.hasClipping) ? this.mPanel.CalculateConstrainOffset(vector2, vector3) : Vector3.zero;
             vector   = transform.localPosition + b;
             vector.x = Mathf.Round(vector.x);
             vector.y = Mathf.Round(vector.y);
             transform.localPosition = vector;
         }
     }
     else
     {
         base.OnSelect(false);
     }
 }
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// The Page_Load server event handler on this user control is used
        /// to populate the tree with the Pages.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks>
        /// </remarks>
        /// -----------------------------------------------------------------------------
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            try
            {
                if (Page.IsPostBack == false)
                {
                    BuildTree(null, false);

                    //Main Table Properties
                    if (!String.IsNullOrEmpty(Width))
                    {
                        tblMain.Width = Width;
                    }

                    if (!String.IsNullOrEmpty(CssClass))
                    {
                        tblMain.Attributes.Add("class", CssClass);
                    }

                    //Header Properties
                    if (!String.IsNullOrEmpty(HeaderCssClass))
                    {
                        cellHeader.Attributes.Add("class", HeaderCssClass);
                    }

                    if (!String.IsNullOrEmpty(HeaderTextCssClass))
                    {
                        lblHeader.CssClass = HeaderTextCssClass;
                    }

                    //Header Text (if set)
                    if (!String.IsNullOrEmpty(HeaderText))
                    {
                        lblHeader.Text = HeaderText;
                    }

                    //ResourceKey overrides if found
                    if (!String.IsNullOrEmpty(ResourceKey))
                    {
                        string strHeader = Localization.GetString(ResourceKey, Localization.GetResourceFile(this, MyFileName));
                        if (!String.IsNullOrEmpty(strHeader))
                        {
                            lblHeader.Text = Localization.GetString(ResourceKey, Localization.GetResourceFile(this, MyFileName));
                        }
                    }

                    //If still not set get default key
                    if (String.IsNullOrEmpty(lblHeader.Text))
                    {
                        string strHeader = Localization.GetString("Title", Localization.GetResourceFile(this, MyFileName));
                        if (!String.IsNullOrEmpty(strHeader))
                        {
                            lblHeader.Text = Localization.GetString("Title", Localization.GetResourceFile(this, MyFileName));
                        }
                        else
                        {
                            lblHeader.Text = "Site Navigation";
                        }
                    }
                    tblHeader.Visible = IncludeHeader;

                    //Main Panel Properties
                    if (!String.IsNullOrEmpty(BodyCssClass))
                    {
                        cellBody.Attributes.Add("class", BodyCssClass);
                    }
                    cellBody.NoWrap = NoWrap;
                }
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Exemple #56
0
        /// <summary>
        /// Parse a localization file from an XML format.
        /// </summary>
        /// <param name="document">XmlDocument where the localization file is persisted.</param>
        /// <param name="tableDefinitions">Collection containing TableDefinitions to use when parsing the localization file.</param>
        /// <returns>The parsed localization.</returns>
        internal static Localization Parse(XmlReader reader, TableDefinitionCollection tableDefinitions)
        {
            XmlDocument document = new XmlDocument();
            reader.MoveToContent();
            XmlNode node = document.ReadNode(reader);
            document.AppendChild(node);

            Localization localization = new Localization();
            localization.tableDefinitions = tableDefinitions;
            localization.Parse(document);

            return localization;
        }
Exemple #57
0
        /// <summary>
        /// Merge the information from another localization object into this one.
        /// </summary>
        /// <param name="localization">The localization object to be merged into this one.</param>
        public void Merge(Localization localization)
        {
            foreach (WixVariableRow wixVariableRow in localization.Variables)
            {
                WixVariableRow existingWixVariableRow = (WixVariableRow)variables[wixVariableRow.Id];

                if (null == existingWixVariableRow || (existingWixVariableRow.Overridable && !wixVariableRow.Overridable))
                {
                    variables[wixVariableRow.Id] = wixVariableRow;
                }
                else if (!wixVariableRow.Overridable)
                {
                    throw new WixException(WixErrors.DuplicateLocalizationIdentifier(wixVariableRow.SourceLineNumbers, wixVariableRow.Id));
                }
            }
        }
Exemple #58
0
        /// <summary>
        ///   Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                if (Null.IsNull(ProfileUserId))
                {
                    Visible = false;
                    return;
                }

                var template = Convert.ToString(ModuleContext.Settings["ProfileTemplate"]);
                if (string.IsNullOrEmpty(template))
                {
                    template = Localization.GetString("DefaultTemplate", LocalResourceFile);
                }
                var editUrl    = Globals.NavigateURL(ModuleContext.PortalSettings.ActiveTab.TabID, "Profile", "userId=" + ProfileUserId, "pageno=1");
                var profileUrl = Globals.NavigateURL(ModuleContext.PortalSettings.ActiveTab.TabID, "Profile", "userId=" + ProfileUserId, "pageno=3");

                if (template.Contains("[BUTTON:EDITPROFILE]"))
                {
                    if (IncludeButton && IsUser)
                    {
                        string editHyperLink = String.Format("<a href=\"{0}\" class=\"dnnPrimaryAction\">{1}</a>", profileUrl, LocalizeString("Edit"));
                        template = template.Replace("[BUTTON:EDITPROFILE]", editHyperLink);
                    }
                    buttonPanel.Visible = false;
                }
                else
                {
                    buttonPanel.Visible  = IncludeButton;
                    editLink.NavigateUrl = editUrl;
                }
                if (template.Contains("[HYPERLINK:EDITPROFILE]"))
                {
                    if (IsUser)
                    {
                        string editHyperLink = String.Format("<a href=\"{0}\" class=\"dnnSecondaryAction\">{1}</a>", profileUrl, LocalizeString("Edit"));
                        template = template.Replace("[HYPERLINK:EDITPROFILE]", editHyperLink);
                    }
                }
                if (template.Contains("[HYPERLINK:MYACCOUNT]"))
                {
                    if (IsUser)
                    {
                        string editHyperLink = String.Format("<a href=\"{0}\" class=\"dnnSecondaryAction\">{1}</a>", editUrl, LocalizeString("MyAccount"));
                        template = template.Replace("[HYPERLINK:MYACCOUNT]", editHyperLink);
                    }
                    buttonPanel.Visible = false;
                }

                if (!IsUser && buttonPanel.Visible)
                {
                    buttonPanel.Visible = false;
                }

                if (ProfileUser.Profile.ProfileProperties.Cast <ProfilePropertyDefinition>().Count(profProperty => profProperty.Visible) == 0)
                {
                    noPropertiesLabel.Visible = true;
                    profileOutput.Visible     = false;
                }
                else
                {
                    var token = new TokenReplace {
                        User = ProfileUser, AccessingUser = ModuleContext.PortalSettings.UserInfo
                    };
                    profileOutput.InnerHtml   = token.ReplaceEnvironmentTokens(template);
                    noPropertiesLabel.Visible = false;
                    profileOutput.Visible     = true;
                }

                var           propertyAccess      = new ProfilePropertyAccess(ProfileUser);
                var           profileResourceFile = "~/DesktopModules/Admin/Security/App_LocalResources/Profile.ascx";
                StringBuilder sb = new StringBuilder();
                bool          propertyNotFound = false;
                foreach (ProfilePropertyDefinition property in ProfileUser.Profile.ProfileProperties)
                {
                    string value = propertyAccess.GetProperty(property.PropertyName,
                                                              String.Empty,
                                                              Thread.CurrentThread.CurrentUICulture,
                                                              ModuleContext.PortalSettings.UserInfo,
                                                              Scope.DefaultSettings,
                                                              ref propertyNotFound);
                    var propertyName = Localization.GetString("ProfileProperties_" + property.PropertyName, profileResourceFile);
                    propertyName = (String.IsNullOrEmpty(propertyName))
                                        ? property.PropertyName
                                        : propertyName.Trim(':');

                    var clientName = Localization.GetSafeJSString(property.PropertyName);
                    sb.Append("self['" + clientName + "'] = ko.observable(");
                    sb.Append("\"");
                    value = Localization.GetSafeJSString(value);
                    if (property.PropertyName == "Biography")
                    {
                        value = value.Replace("\r", string.Empty).Replace("\n", string.Empty);
                    }
                    sb.Append(value + "\"" + ");");
                    sb.Append('\n');
                    sb.Append("self['" + clientName + "Text'] = '");
                    sb.Append(clientName + "';");
                    sb.Append('\n');
                }

                string email = (ProfileUserId == ModuleContext.PortalSettings.UserId ||
                                ModuleContext.PortalSettings.UserInfo.IsInRole(ModuleContext.PortalSettings.AdministratorRoleName))
                                               ? ProfileUser.Email
                                               : String.Empty;

                sb.Append("self.Email = ko.observable('");
                sb.Append(email + "');");
                sb.Append('\n');
                sb.Append("self.EmailText = '");
                sb.Append(LocalizeString("Email") + "';");
                sb.Append('\n');


                ProfileProperties = sb.ToString();
            }
            catch (Exception exc)
            {
                //Module failed to load
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
 public override MvcData GetDefaultView(Localization localization)
 {
     return new MvcData("Test:TestFlickrImage");
 }
        public static string GetProductionType(bool isSelling, ushort buildingID, Building data)
        {
            RealCityIndustrialBuildingAI.InitDelegate();
            string material = "";

            if (!isSelling)
            {
                if (data.Info.m_buildingAI is IndustrialExtractorAI)
                {
                }
                else
                {
                    switch (data.Info.m_class.m_subService)
                    {
                    case ItemClass.SubService.CommercialHigh:
                    case ItemClass.SubService.CommercialLow:
                    case ItemClass.SubService.CommercialEco:
                    case ItemClass.SubService.CommercialLeisure:
                    case ItemClass.SubService.CommercialTourist:
                        CommercialBuildingAI commercialBuildingAI = data.Info.m_buildingAI as CommercialBuildingAI;
                        switch (commercialBuildingAI.m_incomingResource)
                        {
                        case TransferManager.TransferReason.Goods:
                            material = Localization.Get("PREGOODS") + Localization.Get("LUXURY_PRODUCTS"); break;

                        case TransferManager.TransferReason.Food:
                            material = Localization.Get("FOOD") + Localization.Get("LUXURY_PRODUCTS"); break;

                        case TransferManager.TransferReason.Petrol:
                            material = Localization.Get("PETROL"); break;

                        case TransferManager.TransferReason.Lumber:
                            material = Localization.Get("LUMBER"); break;

                        case TransferManager.TransferReason.Logs:
                            material = Localization.Get("LOG"); break;

                        case TransferManager.TransferReason.Oil:
                            material = Localization.Get("OIL"); break;

                        case TransferManager.TransferReason.Ore:
                            material = Localization.Get("ORE"); break;

                        case TransferManager.TransferReason.Grain:
                            material = Localization.Get("GRAIN_MEAT"); break;

                        default: break;
                        }
                        break;

                    case ItemClass.SubService.IndustrialForestry:
                    case ItemClass.SubService.IndustrialFarming:
                    case ItemClass.SubService.IndustrialOil:
                    case ItemClass.SubService.IndustrialOre:
                        switch (RealCityIndustrialBuildingAI.GetIncomingTransferReason((IndustrialBuildingAI)(data.Info.m_buildingAI), buildingID))
                        {
                        case TransferManager.TransferReason.Grain:
                            material = Localization.Get("GRAIN_MEAT"); break;

                        case TransferManager.TransferReason.Logs:
                            material = Localization.Get("LOG"); break;

                        case TransferManager.TransferReason.Ore:
                            material = Localization.Get("ORE"); break;

                        case TransferManager.TransferReason.Oil:
                            material = Localization.Get("OIL"); break;

                        default: break;
                        }
                        break;

                    case ItemClass.SubService.IndustrialGeneric:
                        switch (RealCityIndustrialBuildingAI.GetIncomingTransferReason((IndustrialBuildingAI)(data.Info.m_buildingAI), buildingID))
                        {
                        case TransferManager.TransferReason.Food:
                            material = Localization.Get("FOOD"); break;

                        case TransferManager.TransferReason.Lumber:
                            material = Localization.Get("LUMBER"); break;

                        case TransferManager.TransferReason.Petrol:
                            material = Localization.Get("PETROL"); break;

                        case TransferManager.TransferReason.Coal:
                            material = Localization.Get("COAL"); break;

                        default: break;
                        }
                        switch (RealCityIndustrialBuildingAI.GetSecondaryIncomingTransferReason((IndustrialBuildingAI)(data.Info.m_buildingAI), buildingID))
                        {
                        case TransferManager.TransferReason.AnimalProducts:
                            material += Localization.Get("ANIMALPRODUCTS"); break;

                        case TransferManager.TransferReason.Flours:
                            material += Localization.Get("FLOURS"); break;

                        case TransferManager.TransferReason.Paper:
                            material += Localization.Get("PAPER"); break;

                        case TransferManager.TransferReason.PlanedTimber:
                            material += Localization.Get("PLANEDTIMBER"); break;

                        case TransferManager.TransferReason.Petroleum:
                            material += Localization.Get("PETROLEUM"); break;

                        case TransferManager.TransferReason.Plastics:
                            material += Localization.Get("PLASTICS"); break;

                        case TransferManager.TransferReason.Glass:
                            material += Localization.Get("GLASS"); break;

                        case TransferManager.TransferReason.Metals:
                            material += Localization.Get("METALS"); break;

                        default: break;
                        }
                        break;

                    default:
                        material = ""; break;
                    }
                }
            }
            else
            {
                if (data.Info.m_buildingAI is IndustrialExtractorAI)
                {
                    switch (data.Info.m_class.m_subService)
                    {
                    case ItemClass.SubService.IndustrialForestry:
                        material = Localization.Get("LOG"); break;

                    case ItemClass.SubService.IndustrialFarming:
                        material = Localization.Get("GRAIN_MEAT"); break;

                    case ItemClass.SubService.IndustrialOil:
                        material = Localization.Get("OIL"); break;

                    case ItemClass.SubService.IndustrialOre:
                        material = Localization.Get("ORE"); break;

                    default:
                        material = ""; break;
                    }
                }
                else
                {
                    switch (data.Info.m_class.m_subService)
                    {
                    case ItemClass.SubService.IndustrialForestry:
                        material = Localization.Get("LUMBER"); break;

                    case ItemClass.SubService.IndustrialFarming:
                        material = Localization.Get("FOOD"); break;

                    case ItemClass.SubService.IndustrialOil:
                        material = Localization.Get("PETROL"); break;

                    case ItemClass.SubService.IndustrialOre:
                        material = Localization.Get("COAL"); break;

                    case ItemClass.SubService.IndustrialGeneric:
                        material = Localization.Get("PREGOODS"); break;

                    case ItemClass.SubService.CommercialHigh:
                    case ItemClass.SubService.CommercialLow:
                    case ItemClass.SubService.CommercialEco:
                    case ItemClass.SubService.CommercialLeisure:
                    case ItemClass.SubService.CommercialTourist:
                        material = Localization.Get("GOODS"); break;

                    default:
                        material = ""; break;
                    }
                }
            }
            return(material);
        }