Inheritance: System.Web.UI.Page
コード例 #1
0
 private SCountry(HttpContextBase context, Country country, Culture culture = Culture.En)
 {
     Id = country.Id;
     Name = country.GetName(culture);
     Image = DefineImagePath(context, country.Image);
     Rating = country.Rating;
 }
コード例 #2
0
 public static string TimeToString(TimeSpan timeSpan, Culture culture)
 {
     string s = "";
     switch (culture)
     {
         case Culture.Ru:
             s += ValueToString(timeSpan.Days, "дней", "день", "дня");
             s += " " + ValueToString(timeSpan.Hours, "часов", "час", "часа");
             s = s.Trim();
             s += " " + ValueToString(timeSpan.Minutes, "минут", "минута", "минуты");
             s = s.Trim();
             s += " " + ValueToString(timeSpan.Seconds, "секунд", "секунда", "секунды");
             s = s.Trim();
             break;
         default:
             s += ValueToString(timeSpan.Days, "day", "days");
             s += " " + ValueToString(timeSpan.Hours, "hour", "hours");
             s = s.Trim();
             s += " " + ValueToString(timeSpan.Minutes, "minute", "minutes");
             s = s.Trim();
             s += " " + ValueToString(timeSpan.Seconds, "second", "seconds");
             s = s.Trim();
             break;
     }
     return s;
 }
コード例 #3
0
ファイル: SRegion.cs プロジェクト: Reidan94/ITouristDashboard
 public SRegion(HttpContextBase context, Region region, Culture culture = Culture.En)
 {
     Id = region.Id;
     Name = region.GetName(culture);
     Rating = region.Rating;
     Image = DefineImagePath(context, region.Image);
 }
コード例 #4
0
ファイル: Manager.cs プロジェクト: Reidan94/ITouristDashboard
 public static ExtendedSearch ExtendedSearch(ExtendedSearch search, out int? max, Culture culture)
 {
     max = 0;
     if (search == null)
         return new ExtendedSearch(culture);
     if (!search.NeedToSearch)
         return search;
     int? type = search.CurrentPlaceType;
     if (type == -1)
         type = null;
     switch (search.CurrentSearchItem)
     {
         case (int)SearchItem.Region:
             Country country;
             search.Regions = DataManager.Regions.GetRegions(null, search.Page, ItemsPerPage, out max, out country, culture, search.Name, SearchOrder.GetOrder(search.CurrentSearchOrder));
             return search;
         case (int)SearchItem.Place:
             Region region;
             search.Places = DataManager.Places.GetPlaces(null, search.Page, ItemsPerPage, out max, out region, culture, search.Name, type, SearchOrder.GetOrder(search.CurrentSearchOrder));
             return search;
         case (int)SearchItem.Route:
             search.Routes = DataManager.Routes.GetPublicRoutes(search.Page, ItemsPerPage, out max, culture, search.Name, SearchOrder.GetOrder(search.CurrentSearchOrder));
             return search;
         default:
             search.Countries = DataManager.Countries.GetCountries(search.Page, ItemsPerPage, out max, culture, search.Name, SearchOrder.GetOrder(search.CurrentSearchOrder));
             return search;
     }
 }
コード例 #5
0
ファイル: Default.ascx.cs プロジェクト: liqueflies/pigeoncms
    protected void BtnSave_Click(object sender, EventArgs e)
    {
        LblErr.Text = "";
        LblOk.Text = "";

        try
        {
            Culture o1 = new Culture();
            if (base.CurrentKey == "")
            {
                form2obj(o1);
                o1 = new CulturesManager().Insert(o1);
            }
            else
            {
                o1 = new CulturesManager().GetByKey(base.CurrentKey);  //precarico i campi esistenti e nn gestiti dal form
                form2obj(o1);
                new CulturesManager().Update(o1);
            }
            Grid1.DataBind();
            LblOk.Text = Utility.GetLabel("RECORD_SAVED_MSG");
            MultiView1.ActiveViewIndex = 0;
        }
        catch (Exception e1)
        {
            LblErr.Text = Utility.GetLabel("RECORD_ERR_MSG") + "<br />" + e1.ToString();
        }
        finally
        {
        }
    }
コード例 #6
0
ファイル: SPlace.cs プロジェクト: Reidan94/ITouristDashboard
 public SPlaceExtended(HttpContextBase context, Place place, Culture culture = Culture.En)
     : base(context, place, culture)
 {
     Type = PlaceTypes.GetPlaceType(place.TypeId).GetName(culture);
     Description = place.GetDescription(culture);
     RegionId = place.RegionId;
     RegionName = place.Region.GetName(culture);
 }
コード例 #7
0
ファイル: SRoute.cs プロジェクト: Reidan94/ITouristDashboard
 public SRouteExtended(Route route, IEnumerable<SCheckPoint> checkPoints, Culture culture)
     : base(route, checkPoints, culture)
 {
     NumberOfCheckPoints = route.CheckPoints.Count;
     AverageTime = route.AverageTime;
     AverageTimeFormatted = route.FormatAverageTime(culture);
     AuthorName = route.User.FullName;
 }
コード例 #8
0
 public ActionResult ChangeCulture(Culture lang, string returnUrl)
 {
     if (returnUrl.Length >= 3)
     {
         returnUrl = returnUrl.Substring(3);
     }
     return Redirect("/" + lang.ToString() + returnUrl);
 }
コード例 #9
0
        public void GetCultureName_Returns_Valid_Result(Culture culture, string cultureName, int cultureLcid)
        {
            string name = null;

            Assert.That(() => name = culture.GetCultureName(), Throws.Nothing);
            Assert.That(name, Is.Not.Null);
            Assert.That(name, Is.EqualTo(cultureName));
        }
コード例 #10
0
 public static IEnumerable<Status> GetAll(Culture culture)
 {
     return new[]
     {
         Default,
         Name,
         Popularity
     };
 }
コード例 #11
0
        public void GetCultureInfo_Returns_Valid_Result(Culture culture, string cultureName, int cultureLcid)
        {
            CultureInfo cultureInfo = null;

            Assert.That(() => cultureInfo = culture.GetCultureInfo(), Throws.Nothing);
            Assert.That(cultureInfo, Is.Not.Null);
            Assert.That(cultureInfo.LCID, Is.EqualTo(cultureLcid));
            Assert.That(cultureInfo.Name, Is.EqualTo(cultureName));
        }
コード例 #12
0
ファイル: SPlace.cs プロジェクト: Reidan94/ITouristDashboard
 public SPlace(HttpContextBase context, Place place, Culture culture = Culture.En)
 {
     Id = place.Id;
     Name = place.GetName(culture);
     Rating = place.Rating;
     X = place.X;
     Y = place.Y;
     Image = DefineImagePath(context, place.Image);
 }
コード例 #13
0
 public static IEnumerable<Status> GetAll(Culture culture)
 {
     return new[]
     {
         Hidden,
         Private,
         Public
     };
 }
コード例 #14
0
ファイル: SRoute.cs プロジェクト: Reidan94/ITouristDashboard
 public SRoute(Route route, IEnumerable<SCheckPoint> checkPoints, Culture culture)
 {
     Id = route.Id;
     Name = route.GetName(culture);
     Rating = route.RelativeRating;
     AuthorId = route.Author;
     Status = RouteStatus.GetStatus(route.Status).GetName(culture);
     CheckPoints = checkPoints;
 }
コード例 #15
0
 public static string PlacesToString(int placesCount, Culture culture)
 {
     switch (culture)
     {
         case Culture.Ru:
             return ValueToString(placesCount, "мест", "место", "места");
         default:
             return ValueToString(placesCount, "place", "places");
     }
 }
コード例 #16
0
 public List<LocalizableStringVm> GetLocalizableStrings(Culture culture)
 {
     var package = culture == Culture.EN ? _enuResourcePackage : _ruResourcePackage;
     var strings = from stringItem in package.RootGroup.Items
         select new LocalizableStringVm {
             Name = stringItem.Name,
             Value = stringItem.StringValue
         };
     return strings.ToList();
 }
コード例 #17
0
 public static string CommentsToString(int commentsCount, Culture culture)
 {
     switch (culture)
     {
         case Culture.Ru:
             return ValueToString(commentsCount, "комментиариев", "комментарий", "комментария");
         default:
             return ValueToString(commentsCount, "comment", "comments");
     }
 }
コード例 #18
0
 public static string RegionsToString(int regionsCount, Culture culture)
 {
     switch (culture)
     {
         case Culture.Ru:
             return ValueToString(regionsCount, "регионов", "регион", "региона");
         default:
             return ValueToString(regionsCount, "region", "regions");
     }
 }
コード例 #19
0
 public static IEnumerable<Country> OrderAscending(IEnumerable<Country> countries, Culture culture)
 {
     switch (culture)
     {
         case Culture.Ru:
             return countries.OrderBy(x => x.Translation.Ru);
         default:
             return countries.OrderBy(x => x.Translation.En);
     }
 }
コード例 #20
0
        public void Initialize_Constructor(Culture culture, string expectedParameter, string expectedMessage)
        {
            SetCulture(culture);

            ArgumentWhiteSpaceException ex = null;

            Assert.That(() => ex = new ArgumentWhiteSpaceException(), Throws.Nothing);
            Assert.That(ex.ParamName, Is.EqualTo(expectedParameter));
            Assert.That(ex.Message, Is.EqualTo(expectedMessage));
            Assert.That(ex.InnerException, Is.EqualTo(null));
        }
コード例 #21
0
        // PUT api/awbuildversion/5
        public void Put(Culture value)
        {
            var GetActionType = Request.Headers.Where(x => x.Key.Equals("ActionType")).FirstOrDefault();

            if (GetActionType.Key != null)
            {
                if (GetActionType.Value.ToList()[0].Equals("DELETE"))
                    adventureWorks_BC.CultureDelete(value);
                if (GetActionType.Value.ToList()[0].Equals("UPDATE"))
                    adventureWorks_BC.CultureUpdate(value);
            }
        }
コード例 #22
0
ファイル: HomeController.cs プロジェクト: yaneli86/AzulBodas
 public ActionResult ChangeCulture(Culture lang, string returnUrl)
 {
     if (returnUrl.Length >= 3)
     {
         returnUrl = returnUrl.Substring(3);
     }
     else if (returnUrl == "/")
     {
         return RedirectToAction("Index", new { culture = lang.ToString() });
     }
     return Redirect("/" + lang.ToString() + returnUrl);
 }
コード例 #23
0
 protected static string GetTranslation(Culture culture, Translation translation)
 {
     switch (culture)
     {
         case Culture.En:
             return translation.En;
         case Culture.Ru:
             return translation.Ru;
         default:
             return null;
     }
 }
コード例 #24
0
ファイル: BlogService.cs プロジェクト: tah91/eworkyWebSite
 public static string GetBlogCacheKey(Culture culture)
 {
     switch (culture)
     {
         case Culture.fr:
             return FrBlogCacheKey;
         case Culture.es:
             return EsBlogCacheKey;
         case Culture.en:
         default:
             return EnBlogCacheKey;
     }
 }
コード例 #25
0
ファイル: BlogService.cs プロジェクト: tah91/eworkyWebSite
 public static string GetBlogUrl(Culture culture)
 {
     switch(culture)
     {
         case Culture.fr:
             return FrBlogUrl;
         case Culture.es:
             return EsBlogUrl;
         case Culture.en:
         default:
             return EnBlogUrl;
     }
 }
コード例 #26
0
 public static string DefineFullCultureName(Culture culture)
 {
     switch (culture)
     {
         case Culture.Ru:
             return "ru_RU";
         default:
             return "en_US" +
                    "" +
                    "" +
                    "";
     }
 }
コード例 #27
0
 public void SetLocalizableStrings(Culture culture, List<LocalizableStringVm> strings)
 {
     var package = culture == Culture.EN ? _enuResourcePackage : _ruResourcePackage;
     foreach (var stringVm in strings.Where(s=>s.IsEdited || s.IsNew)) {
         var existItem = package.RootGroup.Items.FirstOrDefault(i => i.Name == stringVm.Name);
         if (existItem != null) {
             existItem.StringValue = stringVm.Value;
         } else {
             package.RootGroup.Items.Add(new ResourceItem {
                 Name = stringVm.Name,
                 StringValue = stringVm.Value
             });
         }
     }
 }
コード例 #28
0
ファイル: Adventure.cs プロジェクト: Clement-E-Todd/UncleClem
    void GenerateSetting()
    {
        /*
         * SUMMARY
         * -Time period (past, modern, futuristic)
         * -Balance of technology and magic
         * -Geography
         * 		-Number of distinct regions
         * 		-For each region:
         * 			-Size of region (measured in grid spaces taken up on world map)
         * -Cultures
         * 		-Number of cultures
         * 		-For each culture:
         * 			-Size of culture
         * 			-Balance between religion, science, art and economy
         * 			-Government
         * 				-Republic
         * 				-Monarchy
         * 				-Democracy
         * 				-Extreme cultural governments (if previous balance leans heavily in one direction)
         * 					-Theocracy (religion)
         * 					-Technocrcy (science)
         * 					-Geniocracy (art)
         * 					-Bankocracy (economy)
         * 			-Trust of other cultures
         */

        char timePeriod = (char)random.Next(3);
        float techAndMagic = (float)random.NextDouble();
        Debug.Log("The story is set during a " +
                  ((timePeriod == 0) ? "past" : (timePeriod == 1 ? "modern" : "futuristic")) + " time period in a " +
                  ((techAndMagic < 0.2) ? "mechanically/technologically advanced" :
                  (techAndMagic < 0.4) ? "largely technological" :
                  (techAndMagic < 0.6) ? "mechanically and magically balanced" :
                  (techAndMagic < 0.8) ? "largely magical" :
         		  "magical") +
                  " world.");

        int peopleToAssign = 100;

        while (peopleToAssign > 0)
        {
            Culture culture = new Culture(peopleToAssign, random);
            cultures.Add(culture);
            peopleToAssign -= culture.population;
        }
    }
コード例 #29
0
ファイル: SUser.cs プロジェクト: Reidan94/ITouristDashboard
 private SUser(User user, HttpContextBase context, Culture culture = Culture.En)
 {
     Id = user.Id;
     Name = user.Name;
     LastName = user.LastName;
     FacebookLogin = user.FacebookLogin;
     GoogleLogin = user.GoogleLogin;
     VkLogin = user.VkLogin;
     Image = DefineImagePath(context, user.Image);
     Experience = user.Experience;
     Email = user.Email;
     Password = user.Password;
     Status = UserStatus.GetStatus(user.Status).GetName(culture);
     if (FacebookLogin != null || GoogleLogin != null || VkLogin != null)
         RegistrationDate = null;
     else
         RegistrationDate = user.RegistrationDate;
 }
コード例 #30
0
 public ExtendedSearch(Culture culture, int searchItem = 0, int searchOrder = 0, int placeType = -1,string name = null,int page = 1)
 {
     SearchItems = new[]
     {
         new ListItem((int)SearchItem.Country, new Translation("countries", "страны")),
         new ListItem((int)SearchItem.Region, new Translation("regions","регионы")),
         new ListItem((int)SearchItem.Place, new Translation("places","места")),
         new ListItem((int)SearchItem.Route, new Translation("routes","маршруты"))
     };
     SearchOrders = SearchOrder.GetAll(culture);
     var list = PlaceTypes.GetAllPlaceTypes().ToList();
     list.Add(new PlaceType(-1, new Translation("All", "Все")));
     SearchPlaceTypes = list.OrderBy(x => x.Id);
     CurrentSearchItem = searchItem;
     CurrentSearchOrder = searchOrder;
     CurrentPlaceType = placeType;
     Name = name;
     Page = page;
     NeedToSearch = false;
 }
コード例 #31
0
 public void setCulture(Culture culture)
 {
     this.culture = culture;
 }
コード例 #32
0
 public void BogusEmbeddedCulture()
 {
     Culture.ItemCultureInfo info = Culture.GetItemCultureInfo("MyResource.notalocale.resx", null);
     Assert.Null(info.culture);
     Assert.Equal("MyResource.notalocale.resx", info.cultureNeutralFilename);
 }
コード例 #33
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.SuppressOutput();

            if (String.IsNullOrEmpty(Name) && !String.IsNullOrEmpty(Source))
            {
                RequireSettings setting;

                if (String.IsNullOrEmpty(DependsOn))
                {
                    // Include custom script url
                    setting = _resourceManager.Include("script", Source, DebugSrc);
                }
                else
                {
                    // Anonymous declaration with dependencies, then display

                    // Using the source as the name to prevent duplicate references to the same file
                    var name = Source.ToLowerInvariant();

                    var definition = _resourceManager.InlineManifest.DefineScript(name);
                    definition.SetUrl(Source, DebugSrc);

                    if (!String.IsNullOrEmpty(Version))
                    {
                        definition.SetVersion(Version);
                    }

                    if (!String.IsNullOrEmpty(CdnSrc))
                    {
                        definition.SetCdn(CdnSrc, DebugCdnSrc);
                    }

                    if (!String.IsNullOrEmpty(Culture))
                    {
                        definition.SetCultures(Culture.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries));
                    }

                    if (!String.IsNullOrEmpty(DependsOn))
                    {
                        definition.SetDependencies(DependsOn.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries));
                    }

                    if (!String.IsNullOrEmpty(Version))
                    {
                        definition.SetVersion(Version);
                    }

                    setting = _resourceManager.RegisterResource("script", name);
                }

                if (At != ResourceLocation.Unspecified)
                {
                    setting.AtLocation(At);
                }

                if (!String.IsNullOrEmpty(Condition))
                {
                    setting.UseCondition(Condition);
                }

                setting.UseDebugMode(Debug);

                if (!String.IsNullOrEmpty(Culture))
                {
                    setting.UseCulture(Culture);
                }

                foreach (var attribute in output.Attributes)
                {
                    setting.SetAttribute(attribute.Name, attribute.Value.ToString());
                }
            }
            else if (!String.IsNullOrEmpty(Name) && String.IsNullOrEmpty(Source))
            {
                // Resource required

                var setting = _resourceManager.RegisterResource("script", Name);

                if (At != ResourceLocation.Unspecified)
                {
                    setting.AtLocation(At);
                }

                setting.UseCdn(UseCdn);

                if (!String.IsNullOrEmpty(Condition))
                {
                    setting.UseCondition(Condition);
                }

                setting.UseDebugMode(Debug);

                if (!String.IsNullOrEmpty(Culture))
                {
                    setting.UseCulture(Culture);
                }

                if (!String.IsNullOrEmpty(Version))
                {
                    setting.UseVersion(Version);
                }
            }
            else if (!String.IsNullOrEmpty(Name) && !String.IsNullOrEmpty(Source))
            {
                // Inline declaration

                var definition = _resourceManager.InlineManifest.DefineScript(Name);
                definition.SetUrl(Source, DebugSrc);

                if (!String.IsNullOrEmpty(Version))
                {
                    definition.SetVersion(Version);
                }

                if (!String.IsNullOrEmpty(CdnSrc))
                {
                    definition.SetCdn(CdnSrc, DebugCdnSrc);
                }

                if (!String.IsNullOrEmpty(Culture))
                {
                    definition.SetCultures(Culture.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries));
                }

                if (!String.IsNullOrEmpty(DependsOn))
                {
                    definition.SetDependencies(DependsOn.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries));
                }

                if (!String.IsNullOrEmpty(Version))
                {
                    definition.SetVersion(Version);
                }

                // If At is specified then we also render it
                if (At != ResourceLocation.Unspecified)
                {
                    var setting = _resourceManager.RegisterResource("script", Name);

                    setting.AtLocation(At);

                    if (!String.IsNullOrEmpty(Condition))
                    {
                        setting.UseCondition(Condition);
                    }

                    setting.UseDebugMode(Debug);

                    if (!String.IsNullOrEmpty(Culture))
                    {
                        setting.UseCulture(Culture);
                    }

                    foreach (var attribute in output.Attributes)
                    {
                        setting.SetAttribute(attribute.Name, attribute.Value.ToString());
                    }
                }
            }
            else if (String.IsNullOrEmpty(Name) && String.IsNullOrEmpty(Source))
            {
                // Custom script content

                var childContent = output.GetChildContentAsync().GetAwaiter().GetResult();

                var builder = new TagBuilder("script");
                builder.InnerHtml.AppendHtml(childContent);
                builder.TagRenderMode = TagRenderMode.Normal;

                foreach (var attribute in output.Attributes)
                {
                    builder.Attributes.Add(attribute.Name, attribute.Value.ToString());
                }

                // If no type was specified, define a default one
                if (!builder.Attributes.ContainsKey("type"))
                {
                    builder.Attributes.Add("type", "text/javascript");
                }

                if (At == ResourceLocation.Head)
                {
                    _resourceManager.RegisterHeadScript(builder);
                }
                else
                {
                    _resourceManager.RegisterFootScript(builder);
                }
            }
        }
コード例 #34
0
ファイル: ImageList.ascx.cs プロジェクト: holmes2136/ShopCart
 private void UpdateProductImageFromGrid(Product product, string productImageID, bool isZoom, bool isEnlarge, Culture culture, string altTag, string titleTag)
 {
     foreach (ProductImage productImage in product.ProductImages)
     {
         if (productImage.ProductImageID == productImageID)
         {
             productImage.IsZoom    = isZoom;
             productImage.IsEnlarge = isEnlarge;
             productImage.Locales[culture].AltTag   = altTag;
             productImage.Locales[culture].TitleTag = titleTag;
         }
     }
 }
コード例 #35
0
ファイル: TestBase.cs プロジェクト: weedkiller/Musoq
        static TestBase()
        {
            new Plugins.Environment().SetValue(Constants.NetStandardDllEnvironmentName, EnvironmentUtils.GetOrCreateEnvironmentVariable());

            Culture.ApplyWithDefaultCulture();
        }
コード例 #36
0
 public string GetPlaces(string token, int?regionId = null, int offset = 0, int count = 20, string search = null, Culture culture = Culture.En, Order order = Order.Default, bool details = false)
 {
     if (!CheckToken(token))
     {
         return(null);
     }
     return(ToJson(SFactory.Create(HttpContext, DataManager.Places.GetPlaces(regionId, offset, count, search, culture, order: order), culture, details)));
 }
コード例 #37
0
        protected internal void Execute()
        {
            Culture.SetCurrentCulture();
            // We can stop here if there are no assets to fetch
            if (m_repliesRequired == 0)
            {
                PerformAssetsRequestCallback(false);
                return;
            }

            m_timeOutTimer           = new System.Timers.Timer(60000);
            m_timeOutTimer.AutoReset = false;
            m_timeOutTimer.Elapsed  += OnTimeout;
            m_timeout = false;

            foreach (KeyValuePair <UUID, sbyte> kvp in m_uuids)
            {
                string thiskey = kvp.Key.ToString();
                try
                {
                    m_timeOutTimer.Enabled = true;
                    AssetBase asset = m_assetService.Get(thiskey);
                    if (m_timeout)
                    {
                        break;
                    }

                    m_timeOutTimer.Enabled = false;

                    if (asset == null)
                    {
                        m_notFoundAssetUuids.Add(new UUID(thiskey));
                        continue;
                    }

                    sbyte assetType = kvp.Value;
                    if (asset != null && assetType == (sbyte)AssetType.Unknown)
                    {
                        m_log.InfoFormat("[ARCHIVER]: Rewriting broken asset type for {0} to {1}", thiskey, SLUtil.AssetTypeFromCode(assetType));
                        asset.Type = assetType;
                    }

                    m_foundAssetUuids.Add(asset.FullID);
                    m_assetsArchiver.WriteAsset(PostProcess(asset));
                }

                catch (Exception e)
                {
                    m_log.ErrorFormat("[ARCHIVER]: Execute failed with {0}", e);
                }
            }

            m_timeOutTimer.Dispose();
            int totalerrors = m_notFoundAssetUuids.Count + m_previousErrorsCount;

            if (m_timeout)
            {
                m_log.DebugFormat("[ARCHIVER]: Aborted because AssetService request timeout. Successfully added {0} assets", m_foundAssetUuids.Count);
            }
            else if (totalerrors == 0)
            {
                m_log.DebugFormat("[ARCHIVER]: Successfully added all {0} assets", m_foundAssetUuids.Count);
            }
            else
            {
                m_log.DebugFormat("[ARCHIVER]: Successfully added {0} assets ({1} of total possible assets requested were not found, were damaged or were not assets)",
                                  m_foundAssetUuids.Count, totalerrors);
            }

            PerformAssetsRequestCallback(m_timeout);
        }
コード例 #38
0
            /// <summary>
            /// Compiles the given locale into a nested class inside the Processor class.
            /// </summary>
            /// <param name="code"></param>
            /// <param name="classNameTemplate"></param>
            /// <param name="baseClass"></param>
            /// <param name="accessor"></param>
            /// <param name="culture"></param>
            /// <returns></returns>
            private static LocaleProviderType Compile(Class code, ILocale locale, string classNameTemplate, LocaleProviderType baseClass, string accessor, Culture culture)
            {
                // init
                var className = "@" + string.Format(classNameTemplate, culture.GetMethodName());

                // class
                using (var @class = code.AppendNestedClass("{0} class {1} : {2}", accessor, className, (baseClass == null ? "LocaleProvider" : baseClass.ClassName)))
                {
                    // summary
                    @class.Summary = (culture.IsInvariant ? "Invariant." : culture.ToString());

                    // ctor()
                    using (var block = @class.AppendMethod("public {0}() : base({1})", className, Compiler.GetLiteral(culture.ToString())))
                    {
                    }

                    // ctor(string culture)
                    using (var block = @class.AppendMethod("protected {0}(Culture culture) : base(culture)", className))
                    {
                    }

                    // style options
                    CompileStyleOptions(@class, locale.StyleOptions);

                    // date parts
                    CompileDatePartParameters(@class, locale.Dates, DateFormat.Numeric);
                    CompileDatePartParameters(@class, locale.Dates, DateFormat.Text);

                    // ordinals
                    CompileOrdinals(@class, locale.Terms);
                    CompileLongOrdinals(@class, locale.Terms);

                    // terms
                    CompileTerms(@class, locale.Terms);
                    CompileTermGender(@class, locale.Terms);
                }

                // done
                return(new LocaleProviderType(culture, className));
            }
コード例 #39
0
 /// <summary> 
 /// Computes and retrieves a hash code for an object. 
 /// </summary> 
 /// <remarks> 
 /// This method implements the <see cref="Object">Object</see> method. 
 /// </remarks> 
 /// <returns>A hash code for an object.</returns>
 public override int GetHashCode()
 {
     return(Id.GetHashCode() + Culture.GetHashCode() + Name.GetHashCode() + CreatorUserName.GetHashCode() + LastModifierUserName.GetHashCode());
 }
コード例 #40
0
        //could move our main function into OpenSimMain and kill this class
        public static void BaseMain(string[] args, string defaultIniFile, ISimulationBase simBase)
        {
            // First line, hook the appdomain to the crash reporter
            AppDomain.CurrentDomain.UnhandledException +=
                new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            // Add the arguments supplied when running the application to the configuration
            ArgvConfigSource configSource = new ArgvConfigSource(args);

            // Configure Log4Net
            configSource.AddSwitch("Startup", "logconfig");
            string logConfigFile = configSource.Configs["Startup"].GetString("logconfig", String.Empty);

            if (logConfigFile != String.Empty)
            {
                XmlConfigurator.Configure(new System.IO.FileInfo(logConfigFile));
                //m_log.InfoFormat("[OPENSIM MAIN]: configured log4net using \"{0}\" as configuration file",
                //                 logConfigFile);
            }
            else
            {
                XmlConfigurator.Configure();
                //m_log.Info("[OPENSIM MAIN]: configured log4net using default OpenSim.exe.config");
            }

            // Increase the number of IOCP threads available. Mono defaults to a tragically low number
            int workerThreads, iocpThreads;

            System.Threading.ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
            //m_log.InfoFormat("[OPENSIM MAIN]: Runtime gave us {0} worker threads and {1} IOCP threads", workerThreads, iocpThreads);
            if (workerThreads < 500 || iocpThreads < 1000)
            {
                workerThreads = 500;
                iocpThreads   = 1000;
                //m_log.Info("[OPENSIM MAIN]: Bumping up to 500 worker threads and 1000 IOCP threads");
                System.Threading.ThreadPool.SetMaxThreads(workerThreads, iocpThreads);
            }

            // Check if the system is compatible with OpenSimulator.
            // Ensures that the minimum system requirements are met
            m_log.Info("[Setup]: Performing compatibility checks... \n");
            string supported = String.Empty;

            if (Util.IsEnvironmentSupported(ref supported))
            {
                m_log.Info("[Setup]: Environment is compatible.\n");
            }
            else
            {
                m_log.Warn("[Setup]: Environment is unsupported (" + supported + ")\n");
                #if BlockUnsupportedVersions
                Thread.Sleep(10000);     //Sleep 10 seconds
                return;
                #endif
            }

            // Configure nIni aliases and localles
            Culture.SetCurrentCulture();
            configSource.Alias.AddAlias("On", true);
            configSource.Alias.AddAlias("Off", false);
            configSource.Alias.AddAlias("True", true);
            configSource.Alias.AddAlias("False", false);

            ///Command line switches
            configSource.AddSwitch("Startup", "inifile");
            configSource.AddSwitch("Startup", "inimaster");
            configSource.AddSwitch("Startup", "inidirectory");
            configSource.AddSwitch("Console", "Console");
            configSource.AddSwitch("Startup", "inidbg");

            configSource.AddConfig("Network");

            IConfigSource m_configSource = Configuration(configSource, defaultIniFile);

            // Check if we're saving crashes
            m_saveCrashDumps = m_configSource.Configs["Startup"].GetBoolean("save_crashes", m_saveCrashDumps);

            // load Crash directory config
            m_crashDir = m_configSource.Configs["Startup"].GetString("crash_dir", m_crashDir);

            // check auto restart
            bool AutoRestart = m_configSource.Configs["Startup"].GetBoolean("AutoRestartOnCrash", true);

            //Set up the error reporting
            if (m_configSource.Configs["ErrorReporting"] != null)
            {
                m_sendErrorReport = m_configSource.Configs["ErrorReporting"].GetBoolean("SendErrorReports", true);
                m_urlToPostErrors = m_configSource.Configs["ErrorReporting"].GetString("ErrorReportingURL", m_urlToPostErrors);
            }

            bool Running = true;
            //If auto restart is set, then we always run.
            // otherwise, just run the first time that Running == true
            while (AutoRestart || Running)
            {
                //Always run once, then disable this
                Running = false;
                //Initialize the sim base now
                Startup(configSource, m_configSource, simBase.Copy(), args);
            }
        }
コード例 #41
0
ファイル: Generator.cs プロジェクト: nerdycraft/NPCgen
        private string GetName(Gender.NamingList naming, Culture culture)
        {
            string firstName = string.Empty, lastName;

            if (RowFirstName.NoGeneration)
            {
                firstName = RowFirstName.Value;
            }
            else
            {
                string format;
                switch (naming)
                {
                case Gender.NamingList.Male:
                    format = culture.Names.FormatMale;
                    if (string.IsNullOrEmpty(format))
                    {
                        firstName = culture.Names.Male.GetRandom();
                    }
                    break;

                case Gender.NamingList.Female:
                    format = culture.Names.FormatFemale;
                    if (string.IsNullOrEmpty(format))
                    {
                        firstName = culture.Names.Female.GetRandom();
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                if (!string.IsNullOrEmpty(format))
                {
                    firstName = ResolveNameFormat(format, culture.Names);
                }
            }

            if (RowLastName.NoGeneration)
            {
                lastName = RowLastName.Value;
            }
            else
            {
                string format;
                switch (naming)
                {
                case Gender.NamingList.Male:
                    format = culture.Names.FormatMaleLast;
                    break;

                case Gender.NamingList.Female:
                    format = culture.Names.FormatFemaleLast;
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                if (string.IsNullOrEmpty(format))
                {
                    lastName = culture.Names.Last.Any() ? culture.Names.Last.GetRandom() : string.Empty;
                }
                else
                {
                    lastName = ResolveNameFormat(format, culture.Names);
                }
            }

            return($"{firstName} {lastName}".Trim());
        }
コード例 #42
0
ファイル: Generator.cs プロジェクト: nerdycraft/NPCgen
 private Job GetJob(Culture culture)
 {
     return(RowJob.NoGeneration ? (Job)RowJob.Value : data.Jobs.Where(j => culture.DefaultJobs.Contains(j.ReferenceName)).GetRandom());
 }
コード例 #43
0
        protected static Application CreateDefaultApplication()
        {
            var defaultCountry = new Country {
                Code = "SE", Id = 1, Name = "SE"
            };
            var defaultCurrency = new Currency {
                Code = "SEK", Id = 1, Name = "SEK"
            };
            var defaultCulture = new Culture {
                Code = "sv-SE", Name = "sv-SE"
            };
            var defaultRole = new Role {
                Id = 1, Name = "DefaultRole", Description = "Default description"
            };
            var defaultSalesArea = new SalesArea {
                Id = 1, Name = "DefaultSalesArea"
            };

            return(new Application
            {
                Id = 1,
                ParentId = 1,
                Key = Guid.NewGuid(),
                Name = "Test application",
                Url = @"http://www.test.se",
                SenderEmailAddress = "*****@*****.**",
                Client = new Client {
                    Id = 1, Key = Guid.NewGuid(), Name = "TestClient"
                },
                Authorizations = new IdValues {
                    new IdValue {
                        Id = 1, Value = "DefaultAuthorization"
                    }
                },
                Countries = new Countries {
                    Default = defaultCountry, List = new CountryList {
                        defaultCountry
                    }
                },
                Currencies = new Currencies {
                    Default = defaultCurrency, List = new CurrencyList {
                        defaultCurrency
                    }
                },
                Cultures = new Cultures {
                    Default = defaultCulture, List = new CultureList {
                        defaultCulture
                    }
                },
                Pricelists = new Pricelists {
                    Default = 1, Ids = new[] { 1 }
                },
                Roles = new Roles {
                    Default = defaultRole, List = new RoleList {
                        defaultRole
                    }
                },
                SalesAreas = new SalesAreas {
                    Default = defaultSalesArea, List = new SalesAreaList {
                        defaultSalesArea
                    }
                }
            });
        }
コード例 #44
0
 /// <summary>
 /// Serves as a hash function for the current <see cref="TranslationBase"/>,
 /// suitable for hashing algorithms and data structures, such as a hash table.
 /// </summary>
 /// <returns>A hash code for the current <see cref="TranslationBase"/></returns>
 public override int GetHashCode()
 {
     return(Author.GetHashCode() ^ Culture.GetHashCode());
 }
コード例 #45
0
 public void NonCultureFile()
 {
     Culture.ItemCultureInfo info = Culture.GetItemCultureInfo("MyResource.resx", null);
     Assert.Null(info.culture);
     Assert.Equal("MyResource.resx", info.cultureNeutralFilename);
 }
コード例 #46
0
 public float getRate(Culture culture)
 {
     return(rates[culture]);
 }
コード例 #47
0
 public void Basic()
 {
     Culture.ItemCultureInfo info = Culture.GetItemCultureInfo("MyResource.fr.resx", null);
     Assert.Equal("fr", info.culture);
     Assert.Equal("MyResource.resx", info.cultureNeutralFilename);
 }
コード例 #48
0
 public string getSymbol(Culture culture)
 {
     return(symbol[culture]);
 }
コード例 #49
0
        // GET: JobsPage
        public ActionResult Index()
        {
            string id   = User.Identity.GetUserId();
            var    user = (from s in db.Users
                           where s.Id == id
                           select s).FirstOrDefault();

            if (user != null)
            {
                if (user.Role == Role.Seeker &&
                    user.SeekerAccount != null)
                {
                    SeekerAccount account = user.SeekerAccount;
                    if (account.CultureId != null &&
                        account.SkillRequirementId != null)
                    {
                        Culture culture = (from s in db.Cultures
                                           where s.Id == account.CultureId
                                           select s).FirstOrDefault();

                        SkillRequirement skill = (from sk in db.SkillRequirements
                                                  where sk.Id == account.SkillRequirementId
                                                  select sk).FirstOrDefault();

                        List <JobPosting> jobs = (from j in db.JobPostings
                                                  where j.Culture != null &&
                                                  j.SkillRequirement != null
                                                  select j).ToList();

                        int      cultureSize = culture.MapSize;
                        double[] cultureMap  = culture.Map;

                        int      skillSize = skill.MapSize;
                        double[] skillMap  = skill.Map;

                        KDTree <JobPosting> cultureTree = new KDTree <JobPosting>(cultureSize);
                        KDTree <JobPosting> skillTree   = new KDTree <JobPosting>(skillSize);

                        foreach (JobPosting job in jobs)
                        {
                            Culture jobCulture = (from c in db.Cultures
                                                  where c.Id == job.CultureId
                                                  select c).FirstOrDefault();
                            if (culture == null)
                            {
                                continue;
                            }

                            cultureTree.AddPoint(jobCulture.Map, job);
                        }

                        List <JobPosting> results = new List <JobPosting>();

                        var closest = cultureTree.NearestNeighbors(cultureMap, 5);
                        for (; closest.MoveNext();)
                        {
                            SkillRequirement jobSkill = (from js in db.SkillRequirements
                                                         where js.Id == closest.Current.SkillRequirementId
                                                         select js).FirstOrDefault();
                            if (jobSkill == null)
                            {
                                continue;
                            }
                            if (closest.CurrentDistance < 500)
                            {
                                skillTree.AddPoint(jobSkill.Map, closest.Current);
                            }
                        }

                        var sorted = skillTree.NearestNeighbors(skillMap, 5);
                        for (; sorted.MoveNext();)
                        {
                            results.Add(sorted.Current);
                        }

                        return(View(results));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Seeker"));
                    }
                }
                else if (user.Role == Role.Poster)
                {
                    var jobs = (from j in db.JobPostings
                                where j.UserId.Equals(user.Id)
                                select j).ToList();
                    return(View("JobListPartialView", jobs));
                }
            }
            else
            {
                return(RedirectToAction("Index", "Home"));
            }
            var jobPostings = db.JobPostings.Include(j => j.Culture).Include(j => j.SkillRequirement).Include(j => j.User);

            return(View(jobPostings.ToList()));
        }
コード例 #50
0
 private static void LoadAll(Culture culture)
 {
     cache = repo.GetByName("ContactMediaTypes", culture.Id);
 }
コード例 #51
0
ファイル: Resource.cs プロジェクト: ekolis/FrEee
 /// <summary>
 /// Function to compute the cultural modifier. A modifier of zero means 100%; 100 means doubled, -50 means halved, etc.
 /// </summary>
 public int GetCultureModifier(Culture c)
 => CultureModifierPropertyName is null ? 0 : (int)c.GetPropertyValue(CultureModifierPropertyName);
コード例 #52
0
ファイル: AssetsRequest.cs プロジェクト: 4U2NV/opensim
        /// <summary>
        /// Called back by the asset cache when it has the asset
        /// </summary>
        /// <param name="assetID"></param>
        /// <param name="asset"></param>
        public void AssetRequestCallback(string id, object sender, AssetBase asset)
        {
            Culture.SetCurrentCulture();

            try
            {
                lock (this)
                {
                    //m_log.DebugFormat("[ARCHIVER]: Received callback for asset {0}", id);

                    m_requestCallbackTimer.Stop();

                    if (m_requestState == RequestState.Aborted)
                    {
                        m_log.WarnFormat(
                            "[ARCHIVER]: Received information about asset {0} after archive save abortion.  Ignoring.",
                            id);

                        return;
                    }

                    if (asset != null)
                    {
                        if (m_options.ContainsKey("verbose"))
                        {
                            m_log.InfoFormat("[ARCHIVER]: Writing asset {0}", id);
                        }

                        m_foundAssetUuids.Add(asset.FullID);

                        m_assetsArchiver.WriteAsset(PostProcess(asset));
                    }
                    else
                    {
                        if (m_options.ContainsKey("verbose"))
                        {
                            m_log.InfoFormat("[ARCHIVER]: Recording asset {0} as not found", id);
                        }

                        m_notFoundAssetUuids.Add(new UUID(id));
                    }

                    if (m_foundAssetUuids.Count + m_notFoundAssetUuids.Count == m_repliesRequired)
                    {
                        m_requestState = RequestState.Completed;

                        m_log.DebugFormat(
                            "[ARCHIVER]: Successfully added {0} assets ({1} assets not found but these may be expected invalid references)",
                            m_foundAssetUuids.Count, m_notFoundAssetUuids.Count);

                        // We want to stop using the asset cache thread asap
                        // as we now need to do the work of producing the rest of the archive
                        Util.FireAndForget(PerformAssetsRequestCallback);
                    }
                    else
                    {
                        m_requestCallbackTimer.Start();
                    }
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[ARCHIVER]: AssetRequestCallback failed with {0}", e);
            }
        }
コード例 #53
0
        //could move our main function into OpenSimMain and kill this class
        public static void Main(string[] args)
        {
            // First line, hook the appdomain to the crash reporter
            AppDomain.CurrentDomain.UnhandledException +=
                new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            ServicePointManager.DefaultConnectionLimit = 12;

            // Add the arguments supplied when running the application to the configuration
            ArgvConfigSource configSource = new ArgvConfigSource(args);

            // Configure Log4Net
            configSource.AddSwitch("Startup", "logconfig");
            string logConfigFile = configSource.Configs["Startup"].GetString("logconfig", String.Empty);

            if (!String.IsNullOrEmpty(logConfigFile))
            {
                XmlConfigurator.Configure(new System.IO.FileInfo(logConfigFile));
                m_log.InfoFormat("[HALCYON MAIN]: configured log4net using \"{0}\" as configuration file",
                                 logConfigFile);
            }
            else
            {
                XmlConfigurator.Configure();
                m_log.Info("[HALCYON MAIN]: configured log4net using default Halcyon.exe.config");
            }

            m_log.Info("Performing compatibility checks... ");
            string supported = String.Empty;

            if (Util.IsEnvironmentSupported(ref supported))
            {
                m_log.Info("Environment is compatible.\n");
            }
            else
            {
                m_log.Warn("Environment is unsupported (" + supported + ")\n");
            }

            // Configure nIni aliases and localles
            Culture.SetCurrentCulture();

            configSource.Alias.AddAlias("On", true);
            configSource.Alias.AddAlias("Off", false);
            configSource.Alias.AddAlias("True", true);
            configSource.Alias.AddAlias("False", false);
            configSource.Alias.AddAlias("Yes", true);
            configSource.Alias.AddAlias("No", false);

            configSource.AddSwitch("Startup", "background");
            configSource.AddSwitch("Startup", "inifile");
            configSource.AddSwitch("Startup", "inimaster");
            configSource.AddSwitch("Startup", "inidirectory");
            configSource.AddSwitch("Startup", "gridmode");
            configSource.AddSwitch("Startup", "physics");
            configSource.AddSwitch("Startup", "gui");
            configSource.AddSwitch("Startup", "console");
            configSource.AddSwitch("Startup", "save_crashes");
            configSource.AddSwitch("Startup", "crash_dir");

            configSource.AddConfig("StandAlone");
            configSource.AddConfig("Network");

            // Check if we're running in the background or not
            bool background = configSource.Configs["Startup"].GetBoolean("background", false);

            // Check if we're saving crashes
            m_saveCrashDumps = configSource.Configs["Startup"].GetBoolean("save_crashes", false);

            // load Crash directory config
            m_crashDir = configSource.Configs["Startup"].GetString("crash_dir", m_crashDir);

            if (background)
            {
                m_sim = new OpenSimBackground(configSource);
                m_sim.Startup();
            }
            else
            {
                m_sim = new OpenSim(configSource);

                m_sim.Startup();

                while (true)
                {
                    try
                    {
                        // Block thread here for input
                        MainConsole.Instance.Prompt();
                    }
                    catch (Exception e)
                    {
                        m_log.ErrorFormat("Command error: {0}", e);
                    }
                }
            }
        }
コード例 #54
0
 public void HandleEvent(IRequestHandler requestHandler, Culture culture)
 {
     requestHandler.GetService <ICultureManager>().InvalidateCache();
 }
コード例 #55
0
        /// <summary>
        /// currentGroup will store the path for the current container
        /// Since we are expecting to receive from the SP a list ordered by
        /// path, each time the path changes, a new title row will be added in the
        /// grid
        /// </summary>
        protected void Page_Load(object sender, System.EventArgs e)
        {
            // *************************************************************************
            // Retrieve Product information
            // *************************************************************************
            if (Request["filter"] != null)
            {
                txtFilter.Text = Request["filter"].ToString();
            }
            col = (TemplatedColumn)dg.Columns.FromKey("Select");

            /* Alternate for CR 5096(Removal of rejection functionality)--start
             * stat_totalMandatory = stat_Mandatory_D = stat_Mandatory_F = stat_Mandatory_M = stat_Mandatory_R = 0;
             * stat_total = stat_nbFinal = stat_nbDraft = stat_nbMissing = stat_nbRejected = 0;
             * stat_nbDraft_inh = stat_nbFinal_inh = stat_nbRejected_inh = 0;
             */
            stat_totalMandatory = stat_Mandatory_D = stat_Mandatory_F = stat_Mandatory_M = 0;
            stat_total          = stat_nbFinal = stat_nbDraft = stat_nbMissing = 0;
            stat_nbDraft_inh    = stat_nbFinal_inh = 0;
            //Alternate for CR 5096(Removal of rejection functionality)--end

            itemId = QDEUtils.GetItemIdFromRequest().Id;
            QDEUtils.UpdateCultureCodeFromRequest();
            viewOnlyMandatory      = uwToolbar.Items.FromKeyButton("MandatoryOnly").Selected;
            viewOnlyRegionalizable = uwToolbar.Items.FromKeyButton("RegionalizableOnly").Selected;
            // Retrieve culture and master culture code
            if (SessionState.Culture == null)
            {
                UITools.FindUserFirstCulture(false);
            }
            masterCultureCode = HyperCatalog.Shared.SessionState.MasterCulture.Code;

            // Retrieve input form id
            if (Request["f"] != null)
            {
                inputFormId = Request["f"].ToString(); // for example: IF_177
                inputFormId = inputFormId.Substring(3, inputFormId.Length - 3);
            }

            // Update fallbacks
            if (SessionState.Culture.Type == CultureType.Regionale)
            {
                fallBackCulture = SessionState.Culture.Fallback;
            }
            if (SessionState.Culture.Type == CultureType.Locale)
            {
                fallBackCulture  = SessionState.Culture.Fallback;
                fallBackCulture2 = fallBackCulture.Fallback;
            }

            dg.Columns.FromKey("Select").ServerOnly = !SessionState.User.HasCapability(CapabilitiesEnum.EDIT_DELETE_DRAFT_CHUNKS) &&
                                                      !SessionState.User.HasCapability(CapabilitiesEnum.DELETE_ITEMS);

            if (!Page.IsPostBack)
            {
                ViewState["nbCellsWithIndex"] = 0;
                UpdateDataView();
            }
            else
            {
                if (Request["action"] != null)
                {
                    if (Request["action"].ToString() == "reload")
                    {
                        UpdateDataView();
                    }
                }
            }
            isUserItem = SessionState.CurrentItemIsUserItem;
            CheckIfSpellCheckOrMoveStatus();
            CheckIfContentCanBePasted();
            CheckIfContentCanBeDeleted();
            CheckIfAutoTranslate();
            CheckIfRegionalizable();

            //Modified by Prabhu for CR 5160 & ACQ 8.12 (PCF1: Auto TR Redesign)-- 01/Jul/09
            string strScript = "<script>inputFormName='" + ViewState["InputFormName"].ToString() + "'; inputFormId=" + inputFormId + "; isAutoTRButton = " + isAutoTRButton.ToString().ToLower() + "; containerLimit=" + Convert.ToString(ApplicationSettings.Parameters["AutoTR_UIContainerLimit"].Value) + "; cultureCode='" + SessionState.Culture.Code + "';iId=" + itemId.ToString() + ";nbCellsWithIndex=" + ViewState["nbCellsWithIndex"].ToString() + ";</script>";

            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "InitFormName", strScript);
        }
コード例 #56
0
ファイル: Application.cs プロジェクト: MXWest/opensimulator
        //could move our main function into OpenSimMain and kill this class
        public static void Main(string[] args)
        {
            // First line, hook the appdomain to the crash reporter
            AppDomain.CurrentDomain.UnhandledException +=
                new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            ServicePointManager.DefaultConnectionLimit = 12;
            ServicePointManager.UseNagleAlgorithm      = false;

            // Add the arguments supplied when running the application to the configuration
            ArgvConfigSource configSource = new ArgvConfigSource(args);

            // Configure Log4Net
            configSource.AddSwitch("Startup", "logconfig");
            string logConfigFile = configSource.Configs["Startup"].GetString("logconfig", String.Empty);

            if (logConfigFile != String.Empty)
            {
                XmlConfigurator.Configure(new System.IO.FileInfo(logConfigFile));
                m_log.InfoFormat("[OPENSIM MAIN]: configured log4net using \"{0}\" as configuration file",
                                 logConfigFile);
            }
            else
            {
                XmlConfigurator.Configure();
                m_log.Info("[OPENSIM MAIN]: configured log4net using default OpenSim.exe.config");
            }

            m_log.InfoFormat(
                "[OPENSIM MAIN]: System Locale is {0}", System.Threading.Thread.CurrentThread.CurrentCulture);

            string monoThreadsPerCpu = System.Environment.GetEnvironmentVariable("MONO_THREADS_PER_CPU");

            m_log.InfoFormat(
                "[OPENSIM MAIN]: Environment variable MONO_THREADS_PER_CPU is {0}", monoThreadsPerCpu ?? "unset");

            // Verify the Threadpool allocates or uses enough worker and IO completion threads
            // .NET 2.0, workerthreads default to 50 *  numcores
            // .NET 3.0, workerthreads defaults to 250 * numcores
            // .NET 4.0, workerthreads are dynamic based on bitness and OS resources
            // Max IO Completion threads are 1000 on all 3 CLRs
            //
            // Mono 2.10.9 to at least Mono 3.1, workerthreads default to 100 * numcores, iocp threads to 4 * numcores
            int workerThreadsMin = 500;
            int workerThreadsMax = 1000;           // may need further adjustment to match other CLR
            int iocpThreadsMin   = 1000;
            int iocpThreadsMax   = 2000;           // may need further adjustment to match other CLR

            {
                int currentMinWorkerThreads, currentMinIocpThreads;
                System.Threading.ThreadPool.GetMinThreads(out currentMinWorkerThreads, out currentMinIocpThreads);
                m_log.InfoFormat(
                    "[OPENSIM MAIN]: Runtime gave us {0} min worker threads and {1} min IOCP threads",
                    currentMinWorkerThreads, currentMinIocpThreads);
            }

            int workerThreads, iocpThreads;

            System.Threading.ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
            m_log.InfoFormat("[OPENSIM MAIN]: Runtime gave us {0} max worker threads and {1} max IOCP threads", workerThreads, iocpThreads);

            if (workerThreads < workerThreadsMin)
            {
                workerThreads = workerThreadsMin;
                m_log.InfoFormat("[OPENSIM MAIN]: Bumping up max worker threads to {0}", workerThreads);
            }
            if (workerThreads > workerThreadsMax)
            {
                workerThreads = workerThreadsMax;
                m_log.InfoFormat("[OPENSIM MAIN]: Limiting max worker threads to {0}", workerThreads);
            }

            // Increase the number of IOCP threads available.
            // Mono defaults to a tragically low number (24 on 6-core / 8GB Fedora 17)
            if (iocpThreads < iocpThreadsMin)
            {
                iocpThreads = iocpThreadsMin;
                m_log.InfoFormat("[OPENSIM MAIN]: Bumping up max IOCP threads to {0}", iocpThreads);
            }
            // Make sure we don't overallocate IOCP threads and thrash system resources
            if (iocpThreads > iocpThreadsMax)
            {
                iocpThreads = iocpThreadsMax;
                m_log.InfoFormat("[OPENSIM MAIN]: Limiting max IOCP completion threads to {0}", iocpThreads);
            }
            // set the resulting worker and IO completion thread counts back to ThreadPool
            if (System.Threading.ThreadPool.SetMaxThreads(workerThreads, iocpThreads))
            {
                m_log.InfoFormat(
                    "[OPENSIM MAIN]: Threadpool set to {0} max worker threads and {1} max IOCP threads",
                    workerThreads, iocpThreads);
            }
            else
            {
                m_log.Warn("[OPENSIM MAIN]: Threadpool reconfiguration failed, runtime defaults still in effect.");
            }

            // Check if the system is compatible with OpenSimulator.
            // Ensures that the minimum system requirements are met
            string supported = String.Empty;

            if (Util.IsEnvironmentSupported(ref supported))
            {
                m_log.Info("[OPENSIM MAIN]: Environment is supported by OpenSimulator.");
            }
            else
            {
                m_log.Warn("[OPENSIM MAIN]: Environment is not supported by OpenSimulator (" + supported + ")\n");
            }

            // Configure nIni aliases and localles
            Culture.SetCurrentCulture();

            // Validate that the user has the most basic configuration done
            // If not, offer to do the most basic configuration for them warning them along the way of the importance of
            // reading these files.

            /*
             * m_log.Info("Checking for reguired configuration...\n");
             *
             * bool OpenSim_Ini = (File.Exists(Path.Combine(Util.configDir(), "OpenSim.ini")))
             || (File.Exists(Path.Combine(Util.configDir(), "opensim.ini")))
             || (File.Exists(Path.Combine(Util.configDir(), "openSim.ini")))
             || (File.Exists(Path.Combine(Util.configDir(), "Opensim.ini")));
             ||
             ||bool StanaloneCommon_ProperCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini"));
             ||bool StanaloneCommon_lowercased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "standalonecommon.ini"));
             ||bool GridCommon_ProperCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "GridCommon.ini"));
             ||bool GridCommon_lowerCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "gridcommon.ini"));
             ||
             ||if ((OpenSim_Ini)
             || && (
             || (StanaloneCommon_ProperCased
             || StanaloneCommon_lowercased
             || GridCommon_ProperCased
             || GridCommon_lowerCased
             || )))
             ||{
             || m_log.Info("Required Configuration Files Found\n");
             ||}
             ||else
             ||{
             || MainConsole.Instance = new LocalConsole("Region");
             || string resp = MainConsole.Instance.CmdPrompt(
             ||                         "\n\n*************Required Configuration files not found.*************\n\n   OpenSimulator will not run without these files.\n\nRemember, these file names are Case Sensitive in Linux and Proper Cased.\n1. ./OpenSim.ini\nand\n2. ./config-include/StandaloneCommon.ini \nor\n3. ./config-include/GridCommon.ini\n\nAlso, you will want to examine these files in great detail because only the basic system will load by default. OpenSimulator can do a LOT more if you spend a little time going through these files.\n\n" + ": " + "Do you want to copy the most basic Defaults from standalone?",
             ||                         "yes");
             || if (resp == "yes")
             || {
             ||
             ||         if (!(OpenSim_Ini))
             ||         {
             ||             try
             ||             {
             ||                 File.Copy(Path.Combine(Util.configDir(), "OpenSim.ini.example"),
             ||                           Path.Combine(Util.configDir(), "OpenSim.ini"));
             ||             } catch (UnauthorizedAccessException)
             ||             {
             ||                 MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, Make sure OpenSim has have the required permissions\n");
             ||             } catch (ArgumentException)
             ||             {
             ||                 MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, The current directory is invalid.\n");
             ||             } catch (System.IO.PathTooLongException)
             ||             {
             ||                 MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the Path to these files is too long.\n");
             ||             } catch (System.IO.DirectoryNotFoundException)
             ||             {
             ||                 MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the current directory is reporting as not found.\n");
             ||             } catch (System.IO.FileNotFoundException)
             ||             {
             ||                 MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n");
             ||             } catch (System.IO.IOException)
             ||             {
             ||                 // Destination file exists already or a hard drive failure...   ..    so we can just drop this one
             ||                 //MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n");
             ||             } catch (System.NotSupportedException)
             ||             {
             ||                 MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, The current directory is invalid.\n");
             ||             }
             ||
             ||         }
             ||         if (!(StanaloneCommon_ProperCased || StanaloneCommon_lowercased))
             ||         {
             ||             try
             ||             {
             ||                 File.Copy(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini.example"),
             ||                           Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini"));
             ||             }
             ||             catch (UnauthorizedAccessException)
             ||             {
             ||                 MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, Make sure OpenSim has the required permissions\n");
             ||             }
             ||             catch (ArgumentException)
             ||             {
             ||                 MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, The current directory is invalid.\n");
             ||             }
             ||             catch (System.IO.PathTooLongException)
             ||             {
             ||                 MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the Path to these files is too long.\n");
             ||             }
             ||             catch (System.IO.DirectoryNotFoundException)
             ||             {
             ||                 MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the current directory is reporting as not found.\n");
             ||             }
             ||             catch (System.IO.FileNotFoundException)
             ||             {
             ||                 MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the example is not found, please make sure that the example files exist.\n");
             ||             }
             ||             catch (System.IO.IOException)
             ||             {
             ||                 // Destination file exists already or a hard drive failure...   ..    so we can just drop this one
             ||                 //MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n");
             ||             }
             ||             catch (System.NotSupportedException)
             ||             {
             ||                 MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, The current directory is invalid.\n");
             ||             }
             ||         }
             || }
             || MainConsole.Instance = null;
             ||}
             */
            configSource.Alias.AddAlias("On", true);
            configSource.Alias.AddAlias("Off", false);
            configSource.Alias.AddAlias("True", true);
            configSource.Alias.AddAlias("False", false);
            configSource.Alias.AddAlias("Yes", true);
            configSource.Alias.AddAlias("No", false);

            configSource.AddSwitch("Startup", "background");
            configSource.AddSwitch("Startup", "inifile");
            configSource.AddSwitch("Startup", "inimaster");
            configSource.AddSwitch("Startup", "inidirectory");
            configSource.AddSwitch("Startup", "physics");
            configSource.AddSwitch("Startup", "gui");
            configSource.AddSwitch("Startup", "console");
            configSource.AddSwitch("Startup", "save_crashes");
            configSource.AddSwitch("Startup", "crash_dir");

            configSource.AddConfig("StandAlone");
            configSource.AddConfig("Network");

            // Check if we're running in the background or not
            bool background = configSource.Configs["Startup"].GetBoolean("background", false);

            // Check if we're saving crashes
            m_saveCrashDumps = configSource.Configs["Startup"].GetBoolean("save_crashes", false);

            // load Crash directory config
            m_crashDir = configSource.Configs["Startup"].GetString("crash_dir", m_crashDir);

            if (background)
            {
                m_sim = new OpenSimBackground(configSource);
                m_sim.Startup();
            }
            else
            {
                m_sim = new OpenSim(configSource);

                m_sim.Startup();

                while (true)
                {
                    try
                    {
                        // Block thread here for input
                        MainConsole.Instance.Prompt();
                    }
                    catch (Exception e)
                    {
                        m_log.ErrorFormat("Command error: {0}", e);
                    }
                }
            }
        }
コード例 #57
0
ファイル: Catalog.cs プロジェクト: yf2009017/Treu-Structure
 /// <summary>
 /// Crea un catálogo vacío con nombre Default
 /// </summary>
 public Catalog() : this(Culture.Get("defaultCatalogName"), false)
 {
 }
コード例 #58
0
ファイル: AgentHandlers.cs プロジェクト: MXWest/opensimulator
        protected virtual void DoQueryAccess(Hashtable request, Hashtable responsedata, UUID agentID, UUID regionID)
        {
            Culture.SetCurrentCulture();

            EntityTransferContext ctx = new EntityTransferContext();

            if (m_SimulationService == null)
            {
                m_log.Debug("[AGENT HANDLER]: Agent QUERY called. Harmless but useless.");
                responsedata["content_type"]        = "application/json";
                responsedata["int_response_code"]   = HttpStatusCode.NotImplemented;
                responsedata["str_response_string"] = string.Empty;

                return;
            }

            // m_log.DebugFormat("[AGENT HANDLER]: Received QUERYACCESS with {0}", (string)request["body"]);
            OSDMap args = Utils.GetOSDMap((string)request["body"]);

            bool viaTeleport = true;

            if (args.ContainsKey("viaTeleport"))
            {
                viaTeleport = args["viaTeleport"].AsBoolean();
            }

            Vector3 position = Vector3.Zero;

            if (args.ContainsKey("position"))
            {
                position = Vector3.Parse(args["position"].AsString());
            }

            string agentHomeURI = null;

            if (args.ContainsKey("agent_home_uri"))
            {
                agentHomeURI = args["agent_home_uri"].AsString();
            }

            // Decode the legacy (string) version and extract the number
            float theirVersion = 0f;

            if (args.ContainsKey("my_version"))
            {
                string   theirVersionStr = args["my_version"].AsString();
                string[] parts           = theirVersionStr.Split(new char[] { '/' });
                if (parts.Length > 1)
                {
                    theirVersion = float.Parse(parts[1]);
                }
            }

            if (args.ContainsKey("context"))
            {
                ctx.Unpack((OSDMap)args["context"]);
            }

            // Decode the new versioning data
            float minVersionRequired = 0f;
            float maxVersionRequired = 0f;
            float minVersionProvided = 0f;
            float maxVersionProvided = 0f;

            if (args.ContainsKey("simulation_service_supported_min"))
            {
                minVersionProvided = (float)args["simulation_service_supported_min"].AsReal();
            }
            if (args.ContainsKey("simulation_service_supported_max"))
            {
                maxVersionProvided = (float)args["simulation_service_supported_max"].AsReal();
            }

            if (args.ContainsKey("simulation_service_accepted_min"))
            {
                minVersionRequired = (float)args["simulation_service_accepted_min"].AsReal();
            }
            if (args.ContainsKey("simulation_service_accepted_max"))
            {
                maxVersionRequired = (float)args["simulation_service_accepted_max"].AsReal();
            }

            responsedata["int_response_code"] = HttpStatusCode.OK;
            OSDMap resp = new OSDMap(3);

            float version = 0f;

            float outboundVersion = 0f;
            float inboundVersion  = 0f;

            if (minVersionProvided == 0f) // string version or older
            {
                // If there is no version in the packet at all we're looking at 0.6 or
                // even more ancient. Refuse it.
                if (theirVersion == 0f)
                {
                    resp["success"] = OSD.FromBoolean(false);
                    resp["reason"]  = OSD.FromString("Your region is running a old version of opensim no longer supported. Consider updating it");
                    responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true);
                    return;
                }

                version = theirVersion;

                if (version < VersionInfo.SimulationServiceVersionAcceptedMin ||
                    version > VersionInfo.SimulationServiceVersionAcceptedMax)
                {
                    resp["success"] = OSD.FromBoolean(false);
                    resp["reason"]  = OSD.FromString(String.Format("Your region protocol version is {0} and we accept only {1} - {2}. No version overlap.", theirVersion, VersionInfo.SimulationServiceVersionAcceptedMin, VersionInfo.SimulationServiceVersionAcceptedMax));
                    responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true);
                    return;
                }
            }
            else
            {
                // Test for no overlap
                if (minVersionProvided > VersionInfo.SimulationServiceVersionAcceptedMax ||
                    maxVersionProvided < VersionInfo.SimulationServiceVersionAcceptedMin)
                {
                    resp["success"] = OSD.FromBoolean(false);
                    resp["reason"]  = OSD.FromString(String.Format("Your region provide protocol versions {0} - {1} and we accept only {2} - {3}. No version overlap.", minVersionProvided, maxVersionProvided, VersionInfo.SimulationServiceVersionAcceptedMin, VersionInfo.SimulationServiceVersionAcceptedMax));
                    responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true);
                    return;
                }
                if (minVersionRequired > VersionInfo.SimulationServiceVersionSupportedMax ||
                    maxVersionRequired < VersionInfo.SimulationServiceVersionSupportedMin)
                {
                    resp["success"] = OSD.FromBoolean(false);
                    resp["reason"]  = OSD.FromString(String.Format("You require region protocol versions {0} - {1} and we provide only {2} - {3}. No version overlap.", minVersionRequired, maxVersionRequired, VersionInfo.SimulationServiceVersionSupportedMin, VersionInfo.SimulationServiceVersionSupportedMax));
                    responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true);
                    return;
                }

                // Determine versions to use
                // This is intentionally inverted. Inbound and Outbound refer to the direction of the transfer.
                // Therefore outbound means from the sender to the receier and inbound means from the receiver to the sender.
                // So outbound is what we will accept and inbound is what we will send. Confused yet?
                outboundVersion = Math.Min(maxVersionProvided, VersionInfo.SimulationServiceVersionAcceptedMax);
                inboundVersion  = Math.Min(maxVersionRequired, VersionInfo.SimulationServiceVersionSupportedMax);
            }

            List <UUID> features = new List <UUID>();

            if (args.ContainsKey("features"))
            {
                OSDArray array = (OSDArray)args["features"];

                foreach (OSD o in array)
                {
                    features.Add(new UUID(o.AsString()));
                }
            }

            GridRegion destination = new GridRegion();

            destination.RegionID = regionID;

            string reason;

            // We're sending the version numbers down to the local connector to do the varregion check.
            ctx.InboundVersion  = inboundVersion;
            ctx.OutboundVersion = outboundVersion;
            if (minVersionProvided == 0f)
            {
                ctx.InboundVersion  = version;
                ctx.OutboundVersion = version;
            }

            bool result = m_SimulationService.QueryAccess(destination, agentID, agentHomeURI, viaTeleport, position, features, ctx, out reason);

            m_log.DebugFormat("[AGENT HANDLER]: QueryAccess returned {0} ({1}). Version={2}, {3}/{4}",
                              result, reason, version, inboundVersion, outboundVersion);

            resp["success"] = OSD.FromBoolean(result);
            resp["reason"]  = OSD.FromString(reason);
            string legacyVersion = String.Format("SIMULATION/{0}", version);

            resp["version"] = OSD.FromString(legacyVersion);
            resp["negotiated_inbound_version"]  = OSD.FromReal(inboundVersion);
            resp["negotiated_outbound_version"] = OSD.FromReal(outboundVersion);

            OSDArray featuresWanted = new OSDArray();

            foreach (UUID feature in features)
            {
                featuresWanted.Add(OSD.FromString(feature.ToString()));
            }

            resp["features"] = featuresWanted;

            // We must preserve defaults here, otherwise a false "success" will not be put into the JSON map!
            responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true);

//            Console.WriteLine("str_response_string [{0}]", responsedata["str_response_string"]);
        }
コード例 #59
0
        public string GetRegions(string token, int?countryId = null, int offset = 0, int count = 20, string search = null, Culture culture = Culture.En, Order order = Order.Default, bool details = false)
        {
            if (!CheckToken(token))
            {
                return(null);
            }
            var regions = DataManager.Regions.GetRegions(countryId, offset, count, culture, search, order);

            return(ToJson(SFactory.Create(HttpContext, regions, culture, details)));
        }
コード例 #60
0
        /*
         * TODO: More work on the response codes.  Right now
         * returning 200 for success or 499 for exception
         */

        public void SendRequest()
        {
            Culture.SetCurrentCulture();
            HttpWebResponse response = null;
            StringBuilder   sb       = new StringBuilder();

            byte[] buf        = new byte[8192];
            string tempString = null;
            int    count      = 0;

            try
            {
                Request = (HttpWebRequest)WebRequest.Create(Url);

                Request.Method      = HttpMethod;
                Request.ContentType = HttpMIMEType;

                if (!HttpVerifyCert)
                {
                    // Connection Group Name is probably not used so we hijack it to identify
                    // a desired security exception
//                  Request.ConnectionGroupName="NoVerify";
                    Request.Headers.Add("NoVerifyCert", "true");
                }
//              else
//              {
//                  Request.ConnectionGroupName="Verify";
//              }

                if (!string.IsNullOrEmpty(proxyurl))
                {
                    if (!string.IsNullOrEmpty(proxyexcepts))
                    {
                        string[] elist = proxyexcepts.Split(';');
                        Request.Proxy = new WebProxy(proxyurl, true, elist);
                    }
                    else
                    {
                        Request.Proxy = new WebProxy(proxyurl, true);
                    }
                }

                foreach (KeyValuePair <string, string> entry in ResponseHeaders)
                {
                    if (entry.Key.ToLower().Equals("user-agent"))
                    {
                        Request.UserAgent = entry.Value;
                    }
                    else
                    {
                        Request.Headers[entry.Key] = entry.Value;
                    }
                }

                // Encode outbound data
                if (OutboundBody.Length > 0)
                {
                    byte[] data = Util.UTF8.GetBytes(OutboundBody);

                    Request.ContentLength = data.Length;
                    Stream bstream = Request.GetRequestStream();
                    bstream.Write(data, 0, data.Length);
                    bstream.Close();
                }

                Request.Timeout = HttpTimeout;
                // execute the request
                response = (HttpWebResponse)Request.GetResponse();

                Stream resStream = response.GetResponseStream();

                do
                {
                    // fill the buffer with data
                    count = resStream.Read(buf, 0, buf.Length);

                    // make sure we read some data
                    if (count != 0)
                    {
                        // translate from bytes to ASCII text
                        tempString = Util.UTF8.GetString(buf, 0, count);

                        // continue building the string
                        sb.Append(tempString);
                    }
                } while (count > 0); // any more data to read?

                ResponseBody = sb.ToString();

                if (ResponseBody.Length > MaxLength) //Cut it off then
                {
                    ResponseBody = ResponseBody.Remove(MaxLength);
                    //Add the metaData
                    Metadata = new object[2] {
                        0, MaxLength
                    };
                }
            }
            catch (Exception e)
            {
                if (e is WebException && ((WebException)e).Status == WebExceptionStatus.ProtocolError)
                {
                    HttpWebResponse webRsp = (HttpWebResponse)((WebException)e).Response;
                    Status       = (int)webRsp.StatusCode;
                    ResponseBody = webRsp.StatusDescription;
                }
                else
                {
                    Status       = (int)OSHttpStatusCode.ClientErrorJoker;
                    ResponseBody = e.Message;
                }

                _finished = true;
                return;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }

            Status    = (int)OSHttpStatusCode.SuccessOk;
            _finished = true;
        }