protected UserSettings PopulateUserSettingsFromCookies()
        {
            var entityC = Request.Cookies["Entity"];
            var languageC = Request.Cookies["Language"];
            var modeC = Request.Cookies["Mode"];
            var vendorNameC = Request.Cookies["VendorName"];
            var versionOfEAC = Request.Cookies["VersionOfEA"];

            var cookies = new[] { entityC, languageC, modeC, vendorNameC, versionOfEAC };
            if (cookies.Any(c => c == null) || cookies.Any(c => DateTime.MinValue < c.Expires && c.Expires < DateTime.Now))
            {
                return null;
            }

            UserMode mode;
            if (Enum.TryParse(modeC.Value, true, out mode))
            {
                ViewBag.Entity = entityC.Value;
                ViewBag.Language = languageC.Value;
                ViewBag.Mode = modeC.Value;
                return new UserSettings(vendorNameC.Value, versionOfEAC.Value, HttpContext.User.Identity.Name,
                                                 entityC.Value, languageC.Value, mode);
            }
            return null;
        }
        public static bool PositionSafeForSmartLink(Block ast, int start, int length)
        {
            if (ast == null) return true;
            var end = start + length;
            var blockTags = new[] {BlockTag.FencedCode, BlockTag.HtmlBlock, BlockTag.IndentedCode, BlockTag.ReferenceDefinition};
            var inlineTags = new[] {InlineTag.Code, InlineTag.Link, InlineTag.RawHtml, InlineTag.Image};
            var lastBlockTag = BlockTag.Document;

            foreach (var block in EnumerateBlocks(ast.FirstChild))
            {
                if (block.SourcePosition + block.SourceLength < start)
                {
                    lastBlockTag = block.Tag;
                    continue;
                }

                if (block.SourcePosition >= end) return !blockTags.Any(tag => tag == lastBlockTag);
                if (blockTags.Any(tag => tag == block.Tag)) return false;

                return !EnumerateInlines(block.InlineContent)
                    .TakeWhile(il => il.SourcePosition < end)
                    .Where(il => il.SourcePosition + il.SourceLength > start)
                    .Any(il => inlineTags.Any(tag => tag == il.Tag));
            }
            return true;
        }
        private static object GetAsMatchingObject(this string value)
        {
            var stringvalue = value as string ?? string.Empty;

            var cultures = new[] {
                CultureInfo.GetCultureInfo("de-DE"),
                CultureInfo.GetCultureInfo("en-US")
            };

            //  Datentyp decimal wurde erkannt >> Rückgabe des String als decimal
            var @decimal = value.GetAsMatchingDecimal();
            if(@decimal.HasValue)
            {
                return (double)@decimal.Value;
            }
            //  Datentyp DateTime wurde erkannt >> Rückgabe des String als DateTime
            var datetime = default(DateTime);
            if (cultures.Any(culture => DateTime.TryParse(value, culture, DateTimeStyles.None, out datetime)))
            {
                return datetime;
            }
            //  Datentyp DateTime wurde erkannt >> Rückgabe des String als DateTime
            var noexpressions = new[] { bool.TrueString.ToLower(), "ja", "yes" };
            var yesexpressions = new[] { bool.FalseString.ToLower(), "nein", "no" };
            if (
                noexpressions.Any(expression => expression == stringvalue.ToLower()) ||
                yesexpressions.Any(expression => expression == stringvalue.ToLower())
            )
            {
                return yesexpressions.Any(expression => expression == stringvalue.ToLower());
            }

            return stringvalue;
        }
Exemple #4
0
        public void LookupEnumeratorWithNull()
        {
            var lookup = new[] { "hi", "bye", "42" }.ToLookup(c => (Char.IsNumber(c[0]) ? null : c[0].ToString()));

            Assert.IsTrue(lookup.Any(g => g.Key == "h"));
            Assert.IsTrue(lookup.Any(g => g.Key == "b"));
            Assert.IsTrue(lookup.Any(g => g.Key == null));
        }
Exemple #5
0
 private static void DefineBaseClass(ConventionModelMapper mapper, System.Type[] baseEntityToIgnore)
 {
     if (baseEntityToIgnore == null) return;
     mapper.IsEntity((type, declared) =>
         baseEntityToIgnore.Any(x => x.IsAssignableFrom(type)) &&
         !baseEntityToIgnore.Any(x => x == type) &&
         !type.IsInterface);
     mapper.IsRootEntity((type, declared) => baseEntityToIgnore.Any(x => x == type.BaseType));
 }
        public static bool IsRootType(this Type type)
        {
            var rootTypes = new[]
            {
                typeof(object), 
                typeof(System.Web.Http.ApiController), 
                typeof(ServicesApiController), 
                typeof(EntityServiceBase<>),
                typeof(System.Web.Mvc.Controller)
            };

            return ((type.BaseType == null) || (rootTypes.Any(x => x.Name == type.Name)) || (rootTypes.Any(x => x.Name == type.BaseType.Name)));
        }
			public void Any_With_Collection()
			{
				string[] ids = new[] { "TEST1", "TEST2" };
				var result = _db.Customers.Where(c => ids.Any(id => c.CustomerID == id));
			
				AssertEqualIgnoringExtraWhitespaceAndCarriageReturn(_selectTestsSql.Any_With_Collection, result.GetQueryText());
			}
        private static bool IsValidResponse(dynamic response)
        {
            var invalidResponseMessages = 
                new[] { "Not Found" };

            return !invalidResponseMessages.Any(x => x.Equals(response.message, StringComparison.OrdinalIgnoreCase));
        }
        protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {
            //if (request.Method == HttpMethod.Options)
            //    return Task<HttpResponseMessage>.Factory.StartNew(() =>
            //    {
            //        var response = new HttpResponseMessage(HttpStatusCode.OK);
            //        response.Headers.Add("Access-Control-Allow-Origin", "*");
            //        var v =
            //            request.Headers.FirstOrDefault(
            //                x => x.Key.Equals("Access-Control-Request-Method", StringComparison.OrdinalIgnoreCase))
            //                .Value;
            //        response.Headers.Add("Access-Control-Allow-Methods", v);
            //        return response;
            //    });

            var verbs = new[] { "Post", "Put", "Get", "Delete" };
            var last = request.RequestUri.AbsolutePath.Split('/').LastOrDefault();
            var isDirectVerb = (verbs.Any(x => x.Equals(last, StringComparison.OrdinalIgnoreCase)));
            if (isDirectVerb || request.Headers.Contains(Header))
            {
                var method = isDirectVerb ? last : request.Headers.GetValues(Header).FirstOrDefault();
                if (!string.IsNullOrWhiteSpace(method))
                    request.Method = new HttpMethod(method);
            }
            return base.SendAsync(request, cancellationToken);
        }
 private static string FormatDescription([CanBeNull] string description)
 {
     var specialSymbols = new[] { ' ', '\'', '[', ']' };
     return description != null && specialSymbols.Any(description.Contains)
         ? "'" + description + "'"
         : description;
 }
		public void almost_all_controllers_should_have_security_attribute_case()
		{
			//arrange
			var excludeControllersType = new[] { typeof(HomeController), typeof(ErrorController),
				typeof(BaseController), typeof(CommonFunctionsController), typeof(GlobalPluginMapperController),
				typeof(AppraisalCompanySignUpController), typeof(PluginController),
				typeof(MenuController), typeof(WelcomeScreenController), typeof(ResetPasswordController), typeof(DashboardTabController), typeof(ACIController)};
			var targetAssembly = typeof(DVS.WebSite.MvcApplication).Assembly;
			var targetAttributeType = typeof(DVSAuthorizeFilterAttribute);
			//act
			var controllersTypes =
				targetAssembly.GetTypes().Where(e => e.GetInterfaces().Any(@interface => @interface == typeof(IController)));
			//assert
			foreach (var controllerType in controllersTypes)
			{
				if (excludeControllersType.Any(e => e == controllerType)) continue;

				var containAuthorizationAttribute =
					controllerType.GetCustomAttributes(false).Any(
						e => e.GetType() == targetAttributeType);

				if (!containAuthorizationAttribute)
					throw new Exception("Controller {" + controllerType.FullName + "} should contain {" + targetAttributeType + "} attribute.");
			}
		}
        public void ErrorDeserializingListHandled()
        {
            string json = @"[
  {
    ""Name"": ""Jim"",
    ""BirthDate"": ""\/Date(978048000000)\/"",
    ""LastModified"": ""\/Date(978048000000)\/""
  },
  {
    ""Name"": ""Jim"",
    ""BirthDate"": ""\/Date(978048000000)\/"",
    ""LastModified"": ""\/Date(978048000000)\/""
  }
]";

            var possibleMsgs = new[]
            {
                "[1] - Error message for member 1 = An item with the same key has already been added.",
                "[1] - Error message for member 1 = An element with the same key already exists in the dictionary." // mono
            };
            VersionKeyedCollection c = JsonConvert.DeserializeObject<VersionKeyedCollection>(json);
            Assert.AreEqual(1, c.Count);
            Assert.AreEqual(1, c.Messages.Count);
            Assert.IsTrue(possibleMsgs.Any(m => m == c.Messages[0]), "Expected One of: " + Environment.NewLine + string.Join(Environment.NewLine, possibleMsgs) + Environment.NewLine + "Was: " + Environment.NewLine + c.Messages[0]);
        }
		public OpponentWindow(GameV2 game)
		{
			InitializeComponent();
		    _game = game;
			//ListViewOpponent.ItemsSource = opponentDeck;
			//opponentDeck.CollectionChanged += OpponentDeckOnCollectionChanged;
			Height = Config.Instance.OpponentWindowHeight;
			if(Config.Instance.OpponentWindowLeft.HasValue)
				Left = Config.Instance.OpponentWindowLeft.Value;
			if(Config.Instance.OpponentWindowTop.HasValue)
				Top = Config.Instance.OpponentWindowTop.Value;
			Topmost = Config.Instance.WindowsTopmost;

			var titleBarCorners = new[]
			{
				new Point((int)Left + 5, (int)Top + 5),
				new Point((int)(Left + Width) - 5, (int)Top + 5),
				new Point((int)Left + 5, (int)(Top + TitlebarHeight) - 5),
				new Point((int)(Left + Width) - 5, (int)(Top + TitlebarHeight) - 5)
			};
			if(!Screen.AllScreens.Any(s => titleBarCorners.Any(c => s.WorkingArea.Contains(c))))
			{
				Top = 100;
				Left = 100;
			}
			Update();
		}
        public virtual IEnumerable<INodeFactory> ResolvePath(IContext context, string path)
        {
            Regex re = new Regex(@"^[-_a-z0-9:]+:/?");
            path = path.ToLowerInvariant().Replace('\\', '/');
            path = re.Replace(path, "");

            var factory = Root;

            var nodeMonikers = path.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            IEnumerable<INodeFactory> factories = new[] {factory};

            foreach (var nodeMoniker in nodeMonikers )
            {
                factories = factory.Resolve(context, nodeMoniker);
                if (null == factories || !factories.Any())
                {
                    return null;
                }

                factory = factories.First();
            }

            return factories;
        }
		private async Task<Deck> ImportDeckFromWeb()
		{
			var settings = new MetroDialogSettings();
			var clipboard = Clipboard.GetText();
			var validUrls = new[]
				{
					"hearthstats", "hss.io", "hearthpwn", "hearthhead", "hearthstoneplayers", "tempostorm",
					"hearthstonetopdeck", "hearthnews.fr", "arenavalue", "hearthstone-decks"
				};
			if(validUrls.Any(clipboard.Contains))
				settings.DefaultText = clipboard;

			//import dialog
			var url = await this.ShowInputAsync("Import deck", "Supported websites:\n" + validUrls.Aggregate((x, next) => x + ", " + next), settings);
			if(string.IsNullOrEmpty(url))
				return null;

			var controller = await this.ShowProgressAsync("Loading Deck...", "please wait");

			//var deck = await this._deckImporter.Import(url);
			var deck = await DeckImporter.Import(url);
			deck.Url = url;

			await controller.CloseAsync();
			return deck;
		}
        private static bool IsComplementaryMethod(MethodInfo actionMethod) {
            var propertyPrefixes = new[] {
                PrefixesAndRecognisedMethods.AutoCompletePrefix,
                PrefixesAndRecognisedMethods.ModifyPrefix,
                PrefixesAndRecognisedMethods.ClearPrefix,
                PrefixesAndRecognisedMethods.ChoicesPrefix,
                PrefixesAndRecognisedMethods.DefaultPrefix,
                PrefixesAndRecognisedMethods.ValidatePrefix,
                PrefixesAndRecognisedMethods.HidePrefix,
                PrefixesAndRecognisedMethods.DisablePrefix
            };

            var actionPrefixes = new[] {
                PrefixesAndRecognisedMethods.ValidatePrefix,
                PrefixesAndRecognisedMethods.HidePrefix,
                PrefixesAndRecognisedMethods.DisablePrefix
            };

            var parameterPrefixes = new[] {
                PrefixesAndRecognisedMethods.AutoCompletePrefix,
                PrefixesAndRecognisedMethods.ParameterChoicesPrefix,
                PrefixesAndRecognisedMethods.ParameterDefaultPrefix,
                PrefixesAndRecognisedMethods.ValidatePrefix
            };


            return propertyPrefixes.Any(prefix => IsComplementaryPropertyMethod(actionMethod, prefix)) ||
                   actionPrefixes.Any(prefix => IsComplementaryActionMethod(actionMethod, prefix)) ||
                   parameterPrefixes.Any(prefix => IsComplementaryParameterMethod(actionMethod, prefix));
        }
 public static bool IsImage(HttpPostedFileBase file)
 {
     if (file.ContentType.Contains("image"))
         return true;
     var formats = new[] { ".jpg", ".png", ".gif", ".jpeg" };
     return formats.Any(item => file.FileName.EndsWith(item, StringComparison.OrdinalIgnoreCase));
 }
Exemple #18
0
        private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            var j2KExts = new[] { ".jp2", ".j2k", ".j2c" };

            try
            {
                var files = await picker.PickMultipleFilesAsync();
                if (files == null) return;

                var streams =
                    await
                    Task.WhenAll(
                        files.Select(async file => (await file.OpenAsync(FileAccessMode.Read)).AsStreamForRead()));

                ImageSource image;
                if (streams.Length == 1
                    && j2KExts.Any(ext => files[0].FileType.Equals(ext, StringComparison.OrdinalIgnoreCase)))
                {
                    image = J2kImage.FromStream(streams[0]).As<ImageSource>();
                }
                else
                {
                    // If not already encoded, encode before decoding
                    var bytes = J2kImage.ToBytes(J2kImage.CreateEncodableSource(streams));
                    image = J2kImage.FromBytes(bytes).As<ImageSource>();
                }
                DecodedImage.Source = image;
                ImageName.Text = files[0].Path;
            }
            catch (Exception exc)
            {
                DecodedImage.Source = null;
                ImageName.Text = "Could not display file, reason: " + exc.Message;
            }
        }
 /// <summary>
 /// This is a performance tweak to check if this is a .css, .js or .ico, .jpg, .jpeg, .png, .gif file request since
 /// .Net will pass these requests through to the module when in integrated mode.
 /// We want to ignore all of these requests immediately.
 /// </summary>
 /// <param name="url"></param>
 /// <returns></returns>
 internal static bool IsClientSideRequest(this Uri url)
 {
     // fixme - IsClientSideRequest should not use an hard-coded list of extensions
     // a client-side request is anything that has an extension that is not .aspx?
     var toIgnore = new[] { ".js", ".css", ".ico", ".png", ".jpg", ".jpeg", ".gif", ".html", ".svg" };
     return toIgnore.Any(x => Path.GetExtension(url.LocalPath).InvariantEquals(x));
 }
		public OpponentWindow(Config config, ObservableCollection<Card> opponentDeck)
		{
			InitializeComponent();
			_config = config;
			ListViewOpponent.ItemsSource = opponentDeck;
			opponentDeck.CollectionChanged += OpponentDeckOnCollectionChanged;
			Height = _config.OpponentWindowHeight;
			if(_config.OpponentWindowLeft.HasValue)
				Left = _config.OpponentWindowLeft.Value;
			if(_config.OpponentWindowTop.HasValue)
				Top = _config.OpponentWindowTop.Value;
			Topmost = _config.WindowsTopmost;

			var titleBarCorners = new[]
			{
				new Point((int)Left + 5, (int)Top + 5),
				new Point((int)(Left + Width) - 5, (int)Top + 5),
				new Point((int)Left + 5, (int)(Top + TitlebarHeight) - 5),
				new Point((int)(Left + Width) - 5, (int)(Top + TitlebarHeight) - 5)
			};
			if(!Screen.AllScreens.Any(s => titleBarCorners.Any(c => s.WorkingArea.Contains(c))))
			{
				Top = 100;
				Left = 100;
			}
			Update();
		}
        public TimerWindow(Config config)
        {
            InitializeComponent();
            _config = config;

            Height = _config.TimerWindowHeight;
            Width = _config.TimerWindowWidth;

            if(_config.TimerWindowLeft.HasValue)
                Left = config.TimerWindowLeft.Value;
            if(_config.TimerWindowTop.HasValue)
                Top = config.TimerWindowTop.Value;
            Topmost = _config.TimerWindowTopmost;

            var titleBarCorners = new[]
                {
                    new Point((int)Left + 5, (int)Top + 5),
                    new Point((int)(Left + Width) - 5, (int)Top + 5),
                    new Point((int)Left + 5, (int)(Top + TitlebarHeight) - 5),
                    new Point((int)(Left + Width) - 5, (int)(Top + TitlebarHeight) - 5)
                };
            if(!Screen.AllScreens.Any(s => titleBarCorners.Any(c => s.WorkingArea.Contains(c))))
            {
                Top = 100;
                Left = 100;
            }
        }
		public static void PathEquals(this Uri u, string pathAndQueryString)
		{
			var paths = (pathAndQueryString ?? "").Split(new[] { '?' }, 2);

			string path = paths.First(), query = string.Empty;
			if (paths.Length > 1)
				query = paths.Last();

			var expectedUri = new UriBuilder("http", "localhost", u.Port, path, "?" + query).Uri;

			u.AbsolutePath.Should().Be(expectedUri.AbsolutePath);
			u = new UriBuilder(u.Scheme, u.Host, u.Port, u.AbsolutePath, u.Query.Replace("pretty=true&", "").Replace("pretty=true", "")).Uri;

			var queries = new[] { u.Query, expectedUri.Query };
			if (queries.All(string.IsNullOrWhiteSpace)) return;
			if (queries.Any(string.IsNullOrWhiteSpace))
			{
				queries.Last().Should().Be(queries.First());
				return;
			}

			var clientKeyValues = u.Query.Substring(1).Split('&')
				.Select(v => v.Split('='))
				.Where(k => !string.IsNullOrWhiteSpace(k[0]))
				.ToDictionary(k => k[0], v => v.Last());
			var expectedKeyValues = expectedUri.Query.Substring(1).Split('&')
				.Select(v => v.Split('='))
				.Where(k => !string.IsNullOrWhiteSpace(k[0]))
				.ToDictionary(k => k[0], v => v.Last());

			clientKeyValues.Count.Should().Be(expectedKeyValues.Count);
			clientKeyValues.Should().ContainKeys(expectedKeyValues.Keys.ToArray());
			clientKeyValues.Should().Equal(expectedKeyValues);
		}
		public ReplayViewer()
		{
			InitializeComponent();
			Height = Config.Instance.ReplayWindowHeight;
			Width = Config.Instance.ReplayWindowWidth;
			if(Config.Instance.ReplayWindowLeft.HasValue)
				Left = Config.Instance.ReplayWindowLeft.Value;
			if(Config.Instance.ReplayWindowTop.HasValue)
				Top = Config.Instance.ReplayWindowTop.Value;

			var titleBarCorners = new[]
			{
				new System.Drawing.Point((int)Left + 5, (int)Top + 5),
				new System.Drawing.Point((int)(Left + Width) - 5, (int)Top + 5),
				new System.Drawing.Point((int)Left + 5, (int)(Top + TitlebarHeight) - 5),
				new System.Drawing.Point((int)(Left + Width) - 5, (int)(Top + TitlebarHeight) - 5)
			};
			if(!Screen.AllScreens.Any(s => titleBarCorners.Any(c => s.WorkingArea.Contains(c))))
			{
				Top = 100;
				Left = 100;
			}
			_collapsedTurns = new List<int>();
			_showAllTurns = new List<int>();
			CheckBoxAttack.IsChecked = Config.Instance.ReplayViewerShowAttack;
			CheckBoxDeath.IsChecked = Config.Instance.ReplayViewerShowDeath;
			CheckBoxDiscard.IsChecked = Config.Instance.ReplayViewerShowDiscard;
			CheckBoxDraw.IsChecked = Config.Instance.ReplayViewerShowDraw;
			CheckBoxHeroPower.IsChecked = Config.Instance.ReplayViewerShowHeroPower;
			CheckBoxPlay.IsChecked = Config.Instance.ReplayViewerShowPlay;
			CheckBoxSecret.IsChecked = Config.Instance.ReplayViewerShowSecret;
			CheckBoxSummon.IsChecked = Config.Instance.ReplayViewerShowSummon;
			_initialized = true;
		}
        public override bool IsValid(object value)
        {
            var validImageMimeTypes = new[] { "image/jpg", "image/jpeg", "image/gif", "image/png" };

            var uploadFile = value as HttpPostedFileBase;
            return uploadFile != null ? validImageMimeTypes.Any(v => v.ToLowerTrim() == uploadFile.ContentType.ToLowerTrim()) : true;
        }
        public bool? InDesignMode()
        {
#if SILVERLIGHT
            if (Application.Current.RootVisual != null) {
                return System.ComponentModel.DesignerProperties.GetIsInDesignMode(Application.Current.RootVisual);
            }

            return false;
#elif NETFX_CORE
            return DesignMode.DesignModeEnabled;
#else
            var designEnvironments = new[] {
                "BLEND.EXE",
                "XDESPROC.EXE",
            };

            var entry = Assembly.GetEntryAssembly();
            if (entry != null) {
                var exeName = (new FileInfo(entry.Location)).Name.ToUpperInvariant();

                if (designEnvironments.Any(x => x.Contains(exeName))) {
                    return true;
                }
            }

            return false;
#endif
        }
		private static bool IsCorrectSolution(Solution solution, SubmissionResult runResult)
		{
			if (runResult == null)
				return false;

			if (runResult.IsInternalError)
				return false;

			var localValidationPrefixes = new[] { "Решение", "Строка", "Не нужно писать" };
			if (localValidationPrefixes.Any(s => solution.CompilationError.StartsWith(s)))
				return true;

			const string sphereEngineErrorMessage = "Ой-ой, Sphere Engine, проверяющий задачи, не работает. Попробуйте отправить решение позже.";
			if (solution.IsCompilationError && solution.CompilationError == sphereEngineErrorMessage)
				return true;

			const string oldCompilationError = "CompilationError";
			var isCompilationError = solution.IsCompilationError || solution.ActualOutput == oldCompilationError;
			var pseudoCompilationError = runResult.IsCompilationError || !string.IsNullOrEmpty(runResult.CompilationErrorMessage);

			if (isCompilationError != pseudoCompilationError && isCompilationError != runResult.IsCompilationError)
				return false;
			if (isCompilationError)
				return true;

			var output = runResult.GetOutput();
			var isRightAnswer = runResult.IsSuccess && solution.ExpectedOutput.Equals(output);
			return solution.IsRightAnswer == isRightAnswer;
		}
Exemple #27
0
        public virtual IEnumerable<IPathNode> ResolvePath(IProviderContext providerContext, string path)
        {
            if (string.IsNullOrEmpty(path))
                throw new ArgumentNullException(nameof(path));

            Regex re = new Regex(@"^[-_a-z0-9:]+:/?");
            path = path.ToLowerInvariant().Replace('\\', '/');
            path = re.Replace(path, "");

            var factory = Root;

            var nodeMonikers = path.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            IEnumerable<IPathNode> factories = new[] { factory };

            foreach (var nodeMoniker in nodeMonikers)
            {
                factories = factory.Resolve(providerContext, nodeMoniker);
                if (null == factories || !factories.Any())
                {
                    return null;
                }

                factory = factories.First();
            }

            return factories;
        }
		private static bool IfEitherIsEmptyReturnTheOtherOrEmpty(QueryBase leftQuery, QueryBase rightQuery, out QueryBase query)
		{
			var combined = new [] {leftQuery, rightQuery};
			var any = combined.Any(bf => bf == null || ((IQuery) bf).Conditionless); 
			query = any ?  combined.FirstOrDefault(bf => bf != null && !((IQuery)bf).Conditionless) : null;
			return any;
		}
        public static MvcHtmlString RenderAuthWarnings(this HtmlHelper htmlHelper)
        {
            var appSettingsKeys =
                new[]
                    {
                        "googleAppID", "googleAppSecret",
                        "facebookAppID", "facebookAppSecret",
                        "twitterConsumerKey", "twitterConsumerSecret"
                    };

            var noValueForSetting =
                appSettingsKeys
                    .Any(key => string.IsNullOrEmpty(ConfigurationManager.AppSettings[key]));

            var message = "";

            if (noValueForSetting)
            {
                message =
                    new HtmlTag("p")
                        .Attr("style", "color: Red;")
                        .Text("Not all key and secrets are filled in a configuration file.")
                        .ToHtmlString();
            }

            return
                new MvcHtmlString(message);
        }
Exemple #30
0
        public void Start()
        {
            var sp = Stopwatch.StartNew();
            var reader = Task.Factory.StartNew(ReadFile);
            var parser = Task.Factory.StartNew(ParseEntries);
            var processer = Task.Factory.StartNew(ProcessDisks);

            while (true)
            {
                var tasks = new[] { reader, parser, processer, Task.Delay(1000) };
                var array = tasks
                    .Where(x => x.IsCompleted == false)
                    .ToArray();
                if (tasks.Any(x => x.IsFaulted))
                {
                    tasks.First(x => x.IsFaulted).Wait();
                }
                if (array.Length <= 1)
                    break;
                Task.WaitAny(array);
                Console.Write("\r{0,10:#,#} sec reads: {1,10:#,#} parsed: {2,10:#,#} written: {3,10:#,#}", sp.Elapsed.TotalSeconds, reads,
                    parsed, writtern);
            }
            Console.WriteLine();
            Console.WriteLine("Total");
            Console.WriteLine("{0,10:#,#} reads: {1:10:#,#} parsed: {2:10:#,#} written: {3:10:#,#}", sp.ElapsedMilliseconds, reads,
                    parsed, writtern);
        }
        public async Task <bool> Initialize()
        {
            bool isChanged = Database.EnsureCreated();

            var newRoles = AppUser.Role.Names.Where(n => !Roles.Where(r => string.Equals(n, r.Name)).Any()).Select(n => new IdentityRole(n)).ToList();

            if (newRoles.Any())
            {
                await Roles.AddRangeAsync(newRoles);

                isChanged = true;
            }

            if (!Users.Any())
            {
                if (!await CreateUser(AppUser.DefaultAdminUserName, AppUser.DefaultAdminUserPassword, "", true))
                {
                    return(false);
                }

                var adminUser = await Users.Where(u => u.UserName == AppUser.DefaultAdminUserName).FirstOrDefaultAsync();

                var adminRole = await Roles.Where(r => r.Name == AppUser.Role.Admin).FirstOrDefaultAsync();

                await UserRoles.AddAsync(new IdentityUserRole <string>
                {
                    UserId = adminUser.Id,
                    RoleId = adminRole.Id,
                });

                isChanged = true;
            }

            if (!System.Any())
            {
                await System.AddAsync(new DBConfig.System
                {
                    Email = new DBConfig.System.EmailServer()
                });

                isChanged = true;
            }

            if (isChanged)
            {
                await SaveChangesAsync();
            }

            AppUser.Role.IdNameMap = await Roles.Where(r => AppUser.Role.Names.Contains(r.Name)).ToDictionaryAsync(r => r.Id, r => r.Name);

            AppUser.Role.NameIdMap = AppUser.Role.IdNameMap.ToDictionary(p => p.Value, p => p.Key);

            return(true);
        }