Beispiel #1
0
        protected SqlResult ExecuteReader(
            IDbConnection connection,
            string commandText,
            int timeLimit = DefaultTimeLimit)
        {
            using (var command = connection.CreateCommand())
            {
                command.CommandText = commandText;

                using (var reader = command.ExecuteReader())
                {
                    var sqlTestResult = new SqlResult();
                    sqlTestResult.Completed = CodeHelpers.ExecuteWithTimeLimit(
                        TimeSpan.FromMilliseconds(timeLimit),
                        () =>
                    {
                        do
                        {
                            while (reader.Read())
                            {
                                for (var i = 0; i < reader.FieldCount; i++)
                                {
                                    var fieldValue = this.GetDataRecordFieldValue(reader, i);

                                    sqlTestResult.Results.Add(fieldValue);
                                }
                            }
                        }while (reader.NextResult());
                    });

                    return(sqlTestResult);
                }
            }
        }
Beispiel #2
0
        public static async Task <PingListEntry> AddEntryToList(Pinglist list, string username, int?userId, string remarks, DataContext ctx)
        {
            username = username?.Trim();
            var frUser = await(username != null ? FRHelpers.GetOrUpdateFRUser(username, ctx) : FRHelpers.GetOrUpdateFRUser(userId.Value, ctx));

            if (frUser == null)
            {
                throw new System.Exception($"Could not validate the existence of user '{username ?? userId.ToString()}.'");
            }

            if (ctx.Pinglists.Find(list.Id).Entries.Any(x => x.FRUser.Id == frUser.Id))
            {
                return(list.Entries.FirstOrDefault(x => x.FRUser.Id == frUser.Id));
            }

            var entry = new PingListEntry
            {
                FRUser      = frUser,
                GeneratedId = CodeHelpers.GenerateId(5, list.Entries.Select(x => x.GeneratedId).ToList()),
                SecretKey   = CodeHelpers.GenerateId(),
                Remarks     = remarks
            };

            list.Entries.Add(entry);

            return(entry);
        }
Beispiel #3
0
        protected bool ExecuteNonQuery(IDbConnection connection, string commandText, int timeLimit = DefaultTimeLimit)
        {
            using (var command = connection.CreateCommand())
            {
                command.CommandText = this.FixCommandText(commandText);

                return(CodeHelpers.ExecuteWithTimeLimit(
                           TimeSpan.FromMilliseconds(timeLimit),
                           () => command.ExecuteNonQuery()));
            }
        }
Beispiel #4
0
        public ActionResult AddToCart(int productID, int count, int productAttributeValueID = 0)
        {
            // Retrieve the album from the database
            var product = productRepository.Products.Single(x => x.ProductID == productID);
            // Add it to the shopping cart
            var cart = EFCartRepository.GetCart(this.HttpContext);

            cart.AddToCart(product, count, CodeHelpers.CreateXmlForAttribute(productAttributeValueID));
            // Go back to the main store page for more shopping
            return(RedirectToAction("Index"));
        }
Beispiel #5
0
        private CodeMemberProperty GenerateGetSetProperty(
            CodeTypeDeclaration owningClass,
            string name,
            Type type,
            MemberAttributes attributes,
            bool useBaseProperty = false)
        {
            // generate the property
            var prop = new CodeMemberProperty();

            prop.Name       = name;
            prop.Type       = new CodeTypeReference(type);
            prop.Attributes = attributes;

            if (useBaseProperty)
            {
                prop.GetStatements.Add(
                    new CodeMethodReturnStatement(CodeHelpers.BaseProperty(name)));
                prop.SetStatements.Add(
                    new CodeAssignStatement(
                        CodeHelpers.BaseProperty(name),
                        new CodePropertySetValueReferenceExpression()));
            }
            else
            {
                // generate the backing field for this property
                var backingField = new CodeMemberField();
                backingField.Name = "backing" + name;
                backingField.Type = new CodeTypeReference(type);
                owningClass.Members.Add(backingField);

                prop.GetStatements.Add(
                    new CodeMethodReturnStatement(CodeHelpers.ThisField(backingField.Name)));
                prop.SetStatements.Add(
                    new CodeAssignStatement(
                        CodeHelpers.ThisField(backingField.Name),
                        new CodePropertySetValueReferenceExpression()));
            }

            owningClass.Members.Add(prop);

            return(prop);
        }
Beispiel #6
0
        public ActionResult Create(CreatePinglistViewModel model)
        {
            var pinglist = DataContext.Pinglists.Add(new Pinglist());

            pinglist.GeneratedId = CodeHelpers.GenerateId(5, DataContext.Pinglists.Select(x => x.GeneratedId).ToList());
            pinglist.SecretKey   = CodeHelpers.GenerateId();
            pinglist.Name        = model.Name;
            pinglist.IsPublic    = model.IsPublic;

            if (Request.IsAuthenticated)
            {
                int userId = HttpContext.GetOwinContext().Authentication.User.Identity.GetUserId <int>();
                pinglist.Creator = DataContext.Users.Find(userId);
            }
            else
            {
                TempData["NewList"] = (pinglist.GeneratedId, pinglist.SecretKey);
            }

            DataContext.SaveChanges();

            return(RedirectToRoute("PinglistDirect", new { listId = pinglist.GeneratedId, secretKey = pinglist.SecretKey }));
        }
        public ActionResult Index(string productLinkText)
        {
            int productInventory = 0;

            if (string.IsNullOrWhiteSpace(productLinkText))
            {
                return(RedirectToAction("Index", "Home", new{ page = 1 }));
            }

            var product = productRepository.Products.Where(x => x.ProductURLText == productLinkText).SingleOrDefault();

            if (product == null)
            {
                return(RedirectToAction("Index", "Home", new { page = 1 }));
            }
            ProductAttribute firstProductAttribute = product.ProductAttributes.FirstOrDefault();

            if (firstProductAttribute == null)
            {
                productInventory = product.Inventory;
            }
            else
            {
                List <ProductAttributeValue>            firstProductAttributeValues            = firstProductAttribute.ProductAttributeValues;
                List <ProductAttributeValueTranslation> firstProductAttributeValueTranslations = new List <ProductAttributeValueTranslation>();

                foreach (ProductAttributeValue productAttributeValue in firstProductAttributeValues)
                {
                    firstProductAttributeValueTranslations.Add(productAttributeValue.ProductAttributeValueTranslations
                                                               .Where(x => x.Language.LanguageCode == CodeHelpers.GetLanguageCode()).First());
                    productInventory += productAttributeValue.Inventory;
                }
                ViewBag.ProductAttributeValueID = new SelectList(firstProductAttributeValueTranslations, "ProductAttributeValueID", "ProductAttributeValueName");
            }
            ViewBag.ProductInventory = productInventory > 10 ? 10 : productInventory;
            return(View(product));
        }
Beispiel #8
0
        private CodeTypeDeclaration CreateUpdateClass(
            IMap map,
            IDictionary <Type, IMap> maps,
            CodeGeneratorConfig codeGeneratorConfig)
        {
            // public class Post_Update
            var updateClass =
                new CodeTypeDeclaration(map.Type.Name + codeGeneratorConfig.UpdateClassSuffix)
            {
                IsClass        = true,
                TypeAttributes = TypeAttributes.Public
            };

            updateClass.BaseTypes.Add(map.Type);
            updateClass.BaseTypes.Add(typeof(IUpdateClass));

            // public IList<string> UpdatedProperties { get; set; }
            this.GenerateGetSetProperty(
                updateClass,
                "UpdatedProperties",
                typeof(IList <>).MakeGenericType(typeof(string)),
                FinalPublic);

            // public bool IsConstructed { get; set; }
            this.GenerateGetSetProperty(updateClass, "IsConstructed", typeof(bool), FinalPublic);

            // public Post_Update() {
            //   this.IsConstructed = true;
            //   this.backingUpdatedProperties = new List<string>();
            // }
            var constructor = new CodeConstructor {
                Attributes = MemberAttributes.Public
            };

            constructor.Statements.Add(new CodeAssignStatement(CodeHelpers.ThisProperty("IsConstructed"), new CodePrimitiveExpression(true)));
            constructor.Statements.Add(new CodeAssignStatement(CodeHelpers.ThisProperty("UpdatedProperties"), new CodeObjectCreateExpression(typeof(List <>).MakeGenericType(typeof(string)))));
            updateClass.Members.Add(constructor);

            // public override IList<Comment> Comments {
            //   get {
            //     return this.backingComments;
            //   }
            //   set {
            //     if (this.IsConstructed) {
            //       this.UpdatedProperties.Add("Comments");
            //     }
            //     this.backingComments = value;
            //   }
            // }
            foreach (var column in map.Columns.Where(c => !c.Value.IsIgnored))
            {
                var prop = this.GenerateGetSetProperty(
                    updateClass,
                    column.Key,
                    column.Value.Type,
                    MemberAttributes.Public | MemberAttributes.Override,
                    true);

                var ifIsConstructed = CodeHelpers.ThisPropertyIsTrue("IsConstructed");

                var addColumnToUpdatedProperties =
                    new CodeExpressionStatement(
                        new CodeMethodInvokeExpression(
                            CodeHelpers.ThisProperty("UpdatedProperties"),
                            "Add",
                            new CodePrimitiveExpression(column.Key)));

                prop.SetStatements.Insert(0, new CodeConditionStatement(ifIsConstructed, addColumnToUpdatedProperties));
            }

            return(updateClass);
        }
Beispiel #9
0
        private CodeTypeDeclaration CreateFkClass(
            IMap map,
            IDictionary <Type, IMap> maps,
            CodeGeneratorConfig codeGeneratorConfig)
        {
            // generate the foreign key access class based on the original class
            var foreignKeyClass =
                new CodeTypeDeclaration(
                    map.Type.Name + codeGeneratorConfig.ForeignKeyAccessClassSuffix);

            foreignKeyClass.IsClass        = true;
            foreignKeyClass.TypeAttributes = TypeAttributes.Public;
            foreignKeyClass.BaseTypes.Add(map.Type);

            foreach (
                var column in
                map.Columns.Where(c => c.Value.Relationship == RelationshipType.ManyToOne || c.Value.Relationship == RelationshipType.OneToOne))
            {
                if (!column.Value.Map.Type.GetProperty(column.Value.Name).GetGetMethod().IsVirtual ||
                    !column.Value.Map.Type.GetProperty(column.Value.Name).CanWrite)
                {
                    // TODO: send a warning back to the programmer, did they mean to do this?
                    continue;
                }

                // create a backing property for storing the FK
                var backingType = column.Value.DbType.GetCLRType();
                if (backingType.IsValueType)
                {
                    backingType = typeof(Nullable <>).MakeGenericType(backingType);
                }

                var foreignKeyBackingProperty = this.GenerateGetSetProperty(
                    foreignKeyClass,
                    column.Value.DbName,
                    backingType,
                    FinalPublic);

                // create a backing field for storing the related entity
                var backingField = new CodeMemberField(
                    column.Value.Type,
                    column.Value.Name + codeGeneratorConfig.ForeignKeyAccessEntityFieldSuffix);
                foreignKeyClass.Members.Add(backingField);

                // override the property getter and setter to use the backingfield
                var property = new CodeMemberProperty();
                property.Name       = column.Value.Name;
                property.Type       = new CodeTypeReference(column.Value.Type);
                property.Attributes = MemberAttributes.Public | MemberAttributes.Override;
                property.GetStatements.Add(
                    new CodeConditionStatement(
                        //// if backingField != null or Fk backing field is null return
                        new CodeBinaryOperatorExpression(
                            CodeHelpers.ThisFieldIsNotNull(backingField.Name),
                            CodeBinaryOperatorType.BooleanOr,
                            CodeHelpers.ThisPropertyIsNull(foreignKeyBackingProperty.Name)),
                        new CodeStatement[] {
                    // true
                    new CodeMethodReturnStatement(
                        CodeHelpers.ThisField(backingField.Name))
                },
                        new CodeStatement[] {
                    // false, return new object with foreign key set
                    new CodeVariableDeclarationStatement(
                        column.Value.Type,
                        "val",
                        new CodeObjectCreateExpression(
                            column.Value.Type)),
                    new CodeAssignStatement(
                        new CodeFieldReferenceExpression(
                            new CodeVariableReferenceExpression("val"),
                            maps[column.Value.Type].PrimaryKey.Name),
                        new CodePropertyReferenceExpression(
                            CodeHelpers.ThisProperty(
                                foreignKeyBackingProperty.Name),
                            "Value")),
                    new CodeAssignStatement(
                        CodeHelpers.ThisField(backingField.Name),
                        new CodeVariableReferenceExpression("val")),
                    new CodeMethodReturnStatement(
                        new CodeVariableReferenceExpression("val"))
                }));
                property.SetStatements.Add(
                    new CodeAssignStatement(
                        CodeHelpers.ThisField(backingField.Name),
                        new CodePropertySetValueReferenceExpression()));
                foreignKeyClass.Members.Add(property);
            }

            return(foreignKeyClass);
        }
Beispiel #10
0
        private CodeTypeDeclaration CreateTrackingClass(
            IMap map,
            CodeGeneratorConfig codeGeneratorConfig)
        {
            var trackingClass =
                new CodeTypeDeclaration(map.Type.Name + codeGeneratorConfig.TrackedClassSuffix);

            trackingClass.IsClass        = true;
            trackingClass.TypeAttributes = TypeAttributes.Public;
            trackingClass.BaseTypes.Add(
                map.Type.Name + codeGeneratorConfig.ForeignKeyAccessClassSuffix);
            trackingClass.BaseTypes.Add(typeof(ITrackedEntity));

            // add in change tracking properties
            this.GenerateGetSetProperty(trackingClass, "IsTracking", typeof(bool), FinalPublic);
            this.GenerateGetSetProperty(
                trackingClass,
                "DirtyProperties",
                typeof(ISet <>).MakeGenericType(typeof(string)),
                FinalPublic);
            this.GenerateGetSetProperty(
                trackingClass,
                "OldValues",
                typeof(IDictionary <,>).MakeGenericType(typeof(string), typeof(object)),
                FinalPublic);
            this.GenerateGetSetProperty(
                trackingClass,
                "NewValues",
                typeof(IDictionary <,>).MakeGenericType(typeof(string), typeof(object)),
                FinalPublic);
            this.GenerateGetSetProperty(
                trackingClass,
                "AddedEntities",
                typeof(IDictionary <,>).MakeGenericType(
                    typeof(string),
                    typeof(IList <>).MakeGenericType(typeof(object))),
                FinalPublic);
            this.GenerateGetSetProperty(
                trackingClass,
                "DeletedEntities",
                typeof(IDictionary <,>).MakeGenericType(
                    typeof(string),
                    typeof(IList <>).MakeGenericType(typeof(object))),
                FinalPublic);

            // add in a constructor to initialise collections
            var constructor = new CodeConstructor();

            constructor.Attributes = MemberAttributes.Public;
            constructor.Statements.Add(
                new CodeAssignStatement(
                    CodeHelpers.ThisField("DirtyProperties"),
                    new CodeObjectCreateExpression(
                        typeof(HashSet <>).MakeGenericType(typeof(string)))));
            constructor.Statements.Add(
                new CodeAssignStatement(
                    CodeHelpers.ThisField("OldValues"),
                    new CodeObjectCreateExpression(
                        typeof(Dictionary <,>).MakeGenericType(typeof(string), typeof(object)))));
            constructor.Statements.Add(
                new CodeAssignStatement(
                    CodeHelpers.ThisField("NewValues"),
                    new CodeObjectCreateExpression(
                        typeof(Dictionary <,>).MakeGenericType(typeof(string), typeof(object)))));
            constructor.Statements.Add(
                new CodeAssignStatement(
                    CodeHelpers.ThisField("AddedEntities"),
                    new CodeObjectCreateExpression(
                        typeof(Dictionary <,>).MakeGenericType(
                            typeof(string),
                            typeof(IList <>).MakeGenericType(typeof(object))))));
            constructor.Statements.Add(
                new CodeAssignStatement(
                    CodeHelpers.ThisField("DeletedEntities"),
                    new CodeObjectCreateExpression(
                        typeof(Dictionary <,>).MakeGenericType(
                            typeof(string),
                            typeof(IList <>).MakeGenericType(typeof(object))))));

            // these constructor statements override the collection properties to use observable collections
            foreach (var collectionColumn in map.Columns.Where(c => c.Value.Type.IsCollection()))
            {
                if (
                    !collectionColumn.Value.Map.Type.GetProperty(collectionColumn.Value.Name)
                    .GetGetMethod()
                    .IsVirtual)
                {
                    // TODO: send a warning back to the programmer, did they mean to do this?
                    continue;
                }

                constructor.Statements.Add(
                    new CodeConditionStatement(
                        new CodeBinaryOperatorExpression(
                            new CodeFieldReferenceExpression(
                                new CodeThisReferenceExpression(),
                                collectionColumn.Key),
                            CodeBinaryOperatorType.IdentityEquality,
                            new CodePrimitiveExpression(null)),
                        new CodeStatement[] {
                    new CodeAssignStatement(
                        new CodePropertyReferenceExpression(
                            new CodeThisReferenceExpression(),
                            collectionColumn.Key),
                        new CodeObjectCreateExpression(
                            "Dashing.CodeGeneration.TrackingCollection<" + trackingClass.Name
                            + "," + collectionColumn.Value.Type.GenericTypeArguments.First()
                            + ">",
                            new CodeThisReferenceExpression(),
                            new CodePrimitiveExpression(collectionColumn.Key)))
                },
                        new CodeStatement[] {
                    new CodeAssignStatement(
                        new CodePropertyReferenceExpression(
                            new CodeThisReferenceExpression(),
                            collectionColumn.Key),
                        new CodeObjectCreateExpression(
                            "Dashing.CodeGeneration.TrackingCollection<" + trackingClass.Name
                            + "," + collectionColumn.Value.Type.GenericTypeArguments.First()
                            + ">",
                            new CodeThisReferenceExpression(),
                            new CodePrimitiveExpression(collectionColumn.Key),
                            new CodePropertyReferenceExpression(
                                new CodeThisReferenceExpression(),
                                collectionColumn.Key)))
                }));
            }

            // override value type properties to perform dirty checking
            foreach (
                var valueTypeColumn in
                map.Columns.Where(c => !c.Value.Type.IsCollection() && !c.Value.IsIgnored))
            {
                if (
                    !valueTypeColumn.Value.Map.Type.GetProperty(valueTypeColumn.Value.Name)
                    .GetGetMethod()
                    .IsVirtual)
                {
                    // TODO: send a warning back to the programmer, did they mean to do this?
                    continue;
                }

                var prop = this.GenerateGetSetProperty(
                    trackingClass,
                    valueTypeColumn.Key,
                    valueTypeColumn.Value.Type,
                    MemberAttributes.Public | MemberAttributes.Override,
                    true);

                // override the setter
                // if isTracking && !this.DirtyProperties.ContainsKey(prop) add to dirty props and add oldvalue
                bool propertyCanBeNull = valueTypeColumn.Value.Type.IsNullable() ||
                                         !valueTypeColumn.Value.Type.IsValueType;
                var changeCheck = new CodeBinaryOperatorExpression();
                if (!propertyCanBeNull)
                {
                    // can't be null so just check values
                    changeCheck.Left =
                        new CodeMethodInvokeExpression(
                            CodeHelpers.BaseProperty(valueTypeColumn.Key),
                            "Equals",
                            new CodePropertySetValueReferenceExpression());
                    changeCheck.Operator = CodeBinaryOperatorType.IdentityEquality;
                    changeCheck.Right    = new CodePrimitiveExpression(false);
                }
                else
                {
                    // can be null, need to be careful of null reference exceptions
                    changeCheck.Left =
                        new CodeBinaryOperatorExpression(
                            CodeHelpers.BasePropertyIsNull(valueTypeColumn.Key),
                            CodeBinaryOperatorType.BooleanAnd,
                            new CodeBinaryOperatorExpression(
                                new CodePropertySetValueReferenceExpression(),
                                CodeBinaryOperatorType.IdentityInequality,
                                new CodePrimitiveExpression(null)));
                    changeCheck.Operator = CodeBinaryOperatorType.BooleanOr;
                    changeCheck.Right    =
                        new CodeBinaryOperatorExpression(
                            CodeHelpers.BasePropertyIsNotNull(valueTypeColumn.Key),
                            CodeBinaryOperatorType.BooleanAnd,
                            new CodeBinaryOperatorExpression(
                                new CodeMethodInvokeExpression(
                                    CodeHelpers.BaseProperty(valueTypeColumn.Key),
                                    "Equals",
                                    new CodePropertySetValueReferenceExpression()),
                                CodeBinaryOperatorType.IdentityEquality,
                                new CodePrimitiveExpression(false)));
                }

                prop.SetStatements.Insert(
                    0,
                    new CodeConditionStatement(
                        CodeHelpers.ThisPropertyIsTrue("IsTracking"),
                        new CodeStatement[] {
                    new CodeConditionStatement(
                        new CodeBinaryOperatorExpression(
                            new CodeBinaryOperatorExpression(
                                new CodeMethodInvokeExpression(
                                    CodeHelpers.ThisProperty("DirtyProperties"),
                                    "Contains",
                                    new CodePrimitiveExpression(prop.Name)),
                                CodeBinaryOperatorType.IdentityEquality,
                                new CodePrimitiveExpression(false)),
                            CodeBinaryOperatorType.BooleanAnd,
                            changeCheck),
                        new CodeStatement[] {
                        new CodeExpressionStatement(
                            new CodeMethodInvokeExpression(
                                CodeHelpers.ThisProperty("DirtyProperties"),
                                "Add",
                                new CodePrimitiveExpression(prop.Name))),
                        new CodeAssignStatement(
                            new CodeIndexerExpression(
                                CodeHelpers.ThisProperty("OldValues"),
                                new CodePrimitiveExpression(prop.Name)),
                            CodeHelpers.BaseField(prop.Name))
                    }),
                    new CodeAssignStatement(
                        new CodeIndexerExpression(
                            CodeHelpers.ThisProperty("NewValues"),
                            new CodePrimitiveExpression(prop.Name)),
                        new CodePropertySetValueReferenceExpression())
                }));
            }

            trackingClass.Members.Add(constructor);

            return(trackingClass);
        }
Beispiel #11
0
        public async Task <ActionResult> Upload(UploadModelPost model)
        {
            var azureImageService = new AzureImageService();

            var    randomizedId = CodeHelpers.GenerateId(5, DataContext.Skins.Select(x => x.GeneratedId).ToList());
            var    secretKey    = CodeHelpers.GenerateId(7);
            Bitmap skinImage    = null;

            try
            {
                skinImage = (Bitmap)Image.FromStream(model.Skin.InputStream);
                if (skinImage.Width != 350 || skinImage.Height != 350)
                {
                    AddErrorNotification("Image needs to be 350px x 350px. Just like FR.");
                    return(View());
                }
            }
            catch
            {
                AddErrorNotification("Upload is not a valid png image");
                return(View());
            }
            try
            {
                var fixPixelFormat = SkinTester.FixPixelFormat(skinImage);
                if (fixPixelFormat != null)
                {
                    skinImage = fixPixelFormat;
                }

                model.Skin.InputStream.Position = 0;
                var url = await azureImageService.WriteImage($@"skins\{randomizedId}.png", model.Skin.InputStream);

                Bitmap dragonImage = null;
                using (var client = new WebClient())
                {
                    var dwagonImageBytes = client.DownloadDataTaskAsync(string.Format(FRHelpers.DressingRoomDummyUrl, (int)model.DragonType, (int)model.Gender));
                    try
                    {
                        using (var memStream = new MemoryStream(await dwagonImageBytes, false))
                            dragonImage = (Bitmap)Image.FromStream(memStream);
                    }
                    catch
                    {
                    }
                }

                var skin = new Skin
                {
                    GeneratedId = randomizedId,
                    SecretKey   = secretKey,
                    Title       = model.Title,
                    Description = model.Description,
                    DragonType  = (int)model.DragonType,
                    GenderType  = (int)model.Gender,
                    Coverage    = GetCoveragePercentage(skinImage, dragonImage)
                };
                skinImage.Dispose();

                if (Request.IsAuthenticated)
                {
                    var userId = HttpContext.GetOwinContext().Authentication.User.Identity.GetUserId <int>();
                    skin.Creator    = DataContext.Users.FirstOrDefault(x => x.Id == userId);
                    skin.Visibility = skin.Creator.ProfileSettings.DefaultSkinsArePublic ? skin.Creator.ProfileSettings.DefaultShowSkinsInBrowse ? SkinVisiblity.Visible : SkinVisiblity.HideFromBrowse : SkinVisiblity.HideEverywhere;
                }

                DataContext.Skins.Add(skin);
                await DataContext.SaveChangesAsync();

                return(View("UploadResult", new UploadModelPostViewModel
                {
                    SkinId = randomizedId,
                    SecretKey = secretKey,
                    PreviewImageUrl = (await SkinTester.GenerateOrFetchDummyPreview(randomizedId, skin.Version)).Urls[0]
                }));
            }
            catch
            {
                AddErrorNotification("Something went wrong uploading");
                return(View());
            }
        }
Beispiel #12
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl, string error)
        {
            if (error == "access_denied")
            {
                AddErrorNotification("Login failed.");
                return(RedirectToRoute("Login"));
            }

            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                AddErrorNotification("Could not retrieve external login information from request, please try again.<br/>If the issue persists then please let me know <a href=\"https://github.com/Nensec/FRTools/issues/5\">here</a>.");
                return(RedirectToRoute("Login"));
            }
            loginInfo.Login.ProviderKey = GetProviderData(loginInfo);

            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            case SignInStatus.Success:
            {
                var user = await UserManager.FindAsync(loginInfo.Login);

                var providerData  = JsonConvert.DeserializeObject <UserStore.ProviderData>(loginInfo.Login.ProviderKey);
                var providerLogin = user.Logins.First(x => x.ProviderKey == providerData.ProviderKey && x.LoginProvider == loginInfo.Login.LoginProvider);
                if (providerLogin.ProviderUsername == null)
                {
                    providerLogin.ProviderUsername = providerData.ProviderUsername;
                    await UserManager.UpdateAsync(user);
                }
                if (returnUrl != null)
                {
                    return(RedirectToLocal(returnUrl));
                }
                return(RedirectToRoute("Home"));
            }

            case SignInStatus.Failure:
            default:
                if (ModelState.IsValid)
                {
                    async Task <(IdentityResult, User)> CreateNewUser(ExternalLoginInfo externalLoginInfo, string usernameAffix = null)
                    {
                        var providerData = JsonConvert.DeserializeObject <UserStore.ProviderData>(externalLoginInfo.Login.ProviderKey);
                        var user         = new User
                        {
                            UserName        = providerData.ProviderUsername + usernameAffix,
                            Email           = externalLoginInfo.Email,
                            ProfileSettings = new ProfileSettings()
                        };

                        return(await UserManager.CreateAsync(user), user);
                    };

                    async Task <ActionResult> LoginUser(User user)
                    {
                        var loginResult = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);

                        if (loginResult.Succeeded)
                        {
                            await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                            return(RedirectToLocal(returnUrl));
                        }
                        else
                        {
                            AddErrorNotification($"Could not login user:<br/><br/><ul>{string.Join("", loginResult.Errors.Select(x => $"<li>{x}</li>"))}</ul>");
                            return(RedirectToRoute("Login"));
                        }
                    };

                    string externalUsername = loginInfo.DefaultUserName ?? loginInfo.ExternalIdentity.FindFirst(ClaimTypes.NameIdentifier).Value;

                    var(newUser, identity) = await CreateNewUser(loginInfo);

                    if (newUser.Succeeded)
                    {
                        return(await LoginUser(identity));
                    }
                    else if (!identity.UserName.All(x => char.IsDigit(x)))
                    {
                        (newUser, identity) = await CreateNewUser(loginInfo, CodeHelpers.GenerateId(5));

                        if (newUser.Succeeded)
                        {
                            return(await LoginUser(identity));
                        }
                        AddErrorNotification($"Could not create user:<br/><br/><ul>{string.Join("", newUser.Errors.Select(x => $"<li>{x}</li>"))}</ul>");
                        return(RedirectToRoute("Login"));
                    }
                }

                AddErrorNotification("Something went wrong submitting the request");

                ViewBag.ReturnUrl = returnUrl;
                return(RedirectToRoute("Login"));
            }
        }