Exemplo n.º 1
0
        public FileStreamResult Picture(int id, int size = 128)
        {
            using (System.Data.SqlClient.SqlConnection conn = DBHelper.GetNewConnection())
            {
                ProfileImage          img = null;
                System.Drawing.Bitmap userBitmap;

                // id == -1 means whitelisted user, whitelist users do not have profiles/profileimages so don't check the db.
                if (id != -1)
                {
                    img = DBHelper.GetUserProfileImage(id, conn);
                    try
                    {
                        userBitmap = img.GetProfileImage();
                    }
                    catch (Exception)
                    {
                        IdenticonRenderer renderer = new IdenticonRenderer();
                        userBitmap = renderer.Render(DBHelper.GetUserProfile(id, conn).UserName.GetHashCode(), 128);

                        MemoryStream mStream = new MemoryStream();
                        userBitmap.Save(mStream, System.Drawing.Imaging.ImageFormat.Png);
                        mStream.Position = 0;

                        DBHelper.SetUserProfileImage(id, mStream.ToArray(), conn);
                    }
                }
                else
                {
                    IdenticonRenderer renderer = new IdenticonRenderer();
                    userBitmap = renderer.Render(1, 128);
                }

                if (size != 128)
                {
                    Bitmap   bmp   = new Bitmap(userBitmap, size, size);
                    Graphics graph = Graphics.FromImage(userBitmap);
                    graph.InterpolationMode  = InterpolationMode.High;
                    graph.CompositingQuality = CompositingQuality.HighQuality;
                    graph.SmoothingMode      = SmoothingMode.AntiAlias;
                    graph.DrawImage(bmp, new Rectangle(0, 0, size, size));
                    userBitmap = bmp;
                }
                else
                {
                }

                MemoryStream stream = new MemoryStream();
                userBitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                stream.Position = 0;
                return(new FileStreamResult(stream, "image/png"));
            }
        }
        protected override void WriteFile(HttpResponseBase response)
        {
            response.Clear();
            if (!string.IsNullOrEmpty(Etag))
            {
                response.AppendHeader("ETag", Etag);
            }
            response.ContentType = "image/png";

            var renderer = new IdenticonRenderer();

            using (Bitmap b = renderer.Render(Code, Size))
            {
                using (var stream = new MemoryStream())
                {
                    b.Save(stream, ImageFormat.Png);
                    stream.WriteTo(response.OutputStream);
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Returns the profile picture for the supplied user id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public FileStreamResult Picture(int id, int size = 128)
        {
            try
            {
                //invalid user ID?
                if (id < 1)
                {
                    return(DefaultPicture(size));
                }

                using (SqlConnection conn = DBHelper.GetNewConnection())
                {
                    ProfileImage image = conn.Query <ProfileImage>("FROM ProfileImages p " +
                                                                   "WHERE UserID=@UserId" +
                                                                   "Select p", new { UserId = CurrentUser.ID }).Single();

                    //ProfileImage image = //Db.ProfileImages.Where(p => p.UserID == id).FirstOrDefault();
                    IdenticonRenderer renderer = new IdenticonRenderer();
                    Bitmap            userBitmap;
                    if (image != null)
                    {
                        try
                        {
                            userBitmap = image.GetProfileImage();
                        }
                        catch (Exception)
                        {
                            userBitmap = renderer.Render(image.GetHashCode(), 128);
                            //.SetProfileImage(userBitmap);
                            //Db.SaveChanges();
                        }
                    }
                    else
                    {
                        UserProfile user = conn.Query <UserProfile>("FROM UserProfiles u " +
                                                                    "WHERE u.Id = @UserId " +
                                                                    "SELECT u").Single();
                        //(Db.Users.Where(u => u.Id == id).FirstOrDefault());
                        if (user != null && user.ProfileImage == null)
                        {
                            try
                            {
                                user.SetProfileImage(renderer.Render(user.Email.GetHashCode(), 128));
                                userBitmap = user.ProfileImage.GetProfileImage();
                                //Db.SaveChanges();
                            }
                            catch (Exception)
                            {
                                userBitmap = renderer.Render(1, 128);
                            }
                        }
                        else
                        {
                            userBitmap = renderer.Render(1, 128);
                        }
                    }

                    if (size != 128)
                    {
                        Bitmap   bmp   = new Bitmap(userBitmap, size, size);
                        Graphics graph = Graphics.FromImage(userBitmap);
                        graph.InterpolationMode  = InterpolationMode.High;
                        graph.CompositingQuality = CompositingQuality.HighQuality;
                        graph.SmoothingMode      = SmoothingMode.AntiAlias;
                        graph.DrawImage(bmp, new Rectangle(0, 0, size, size));
                        userBitmap = bmp;
                    }

                    MemoryStream stream = new MemoryStream();
                    userBitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                    stream.Position = 0;
                    return(new FileStreamResult(stream, "image/png"));
                }
            }
            catch (Exception ex)
            {
                //LogErrorMessage(ex);
                return(null);
            }
        }
Exemplo n.º 4
0
        private void GenerateCivIdenticons()
        {
            List <Entity> civs  = Entities.Where(entity => entity.IsCiv).ToList();
            List <string> races = Entities.Where(entity => entity.IsCiv).GroupBy(entity => entity.Race).Select(entity => entity.Key).OrderBy(entity => entity).ToList();

            int    identiconSeed = Events.Count;
            Random code          = new Random(identiconSeed);

            //Calculates color
            //Creates a variety of colors
            //Races 1 to 6 get a medium color
            //Races 7 to 12 get a light color
            //Races 13 to 18 get a dark color
            //19+ reduced color variance
            int maxHue = 300;
            int colorVariance;

            if (races.Count <= 1)
            {
                colorVariance = 0;
            }
            else if (races.Count <= 6)
            {
                colorVariance = Convert.ToInt32(Math.Floor(maxHue / Convert.ToDouble(races.Count - 1)));
            }
            else if (races.Count > 18)
            {
                colorVariance = Convert.ToInt32(Math.Floor(maxHue / (Math.Ceiling(races.Count / 3.0) - 1)));
            }
            else
            {
                colorVariance = 60;
            }

            foreach (Entity civ in civs)
            {
                int   colorIndex = races.IndexOf(civ.Race);
                Color raceColor;
                if (colorIndex * colorVariance < 360)
                {
                    raceColor = Formatting.HsvToRgb(colorIndex * colorVariance, 1, 1.0);
                }
                else if (colorIndex * colorVariance < 720)
                {
                    raceColor = Formatting.HsvToRgb(colorIndex * colorVariance - 360, 0.4, 1);
                }
                else if (colorIndex * colorVariance < 1080)
                {
                    raceColor = Formatting.HsvToRgb(colorIndex * colorVariance - 720, 1, 0.4);
                }
                else
                {
                    raceColor = Color.Black;
                }


                int identiconCode;
                IdenticonRenderer identiconRenderer = new IdenticonRenderer();

                identiconCode     = code.Next();
                civ.IdenticonCode = identiconCode;

                int alpha;
                if (races.Count <= 12)
                {
                    alpha = 175;
                }
                else
                {
                    alpha = 175;
                }

                if (!MainRaces.ContainsKey(civ.Race))
                {
                    MainRaces.Add(civ.Race, raceColor);
                }
                civ.IdenticonColor = Color.FromArgb(alpha, raceColor);
                civ.LineColor      = raceColor;

                using (MemoryStream identiconStream = new MemoryStream())
                {
                    using (Bitmap identicon = identiconRenderer.Render(identiconCode, 64, civ.IdenticonColor))
                    {
                        identicon.Save(identiconStream, System.Drawing.Imaging.ImageFormat.Png);
                        byte[] identiconBytes = identiconStream.GetBuffer();
                        civ.Identicon       = new Bitmap(identicon);
                        civ.IdenticonString = Convert.ToBase64String(identiconBytes);
                    }
                }

                using (MemoryStream smallIdenticonStream = new MemoryStream())
                {
                    using (Bitmap smallIdenticon = identiconRenderer.Render(identiconCode, 24, civ.IdenticonColor))
                    {
                        smallIdenticon.Save(smallIdenticonStream, System.Drawing.Imaging.ImageFormat.Png);
                        byte[] smallIdenticonBytes = smallIdenticonStream.GetBuffer();
                        civ.SmallIdenticonString = Convert.ToBase64String(smallIdenticonBytes);
                    }
                }

                foreach (Entity group in civ.Groups)
                {
                    group.Identicon            = civ.Identicon;
                    group.SmallIdenticonString = civ.SmallIdenticonString;
                }
            }

            Bitmap nullIdenticon = new Bitmap(64, 64);

            using (Graphics nullGraphics = Graphics.FromImage(nullIdenticon))
            {
                using (SolidBrush nullBrush = new SolidBrush(Color.FromArgb(150, Color.Red)))
                    nullGraphics.FillRectangle(nullBrush, new Rectangle(0, 0, 64, 64));
                Entities.Where(entity => entity.Identicon == null).ToList().ForEach(entity => entity.Identicon = nullIdenticon);
            }
        }
Exemplo n.º 5
0
        public Bitmap GetIdenticon(int size)
        {
            IdenticonRenderer identiconRenderer = new IdenticonRenderer();

            return(identiconRenderer.Render(IdenticonCode, size, IdenticonColor));
        }
Exemplo n.º 6
0
        public ActionResult Picture(HttpPostedFileBase file)
        {
            try
            {
                //two options: user uploaded a profile picture
                //             OR user requested a default profile picture
                if (Request.Params["upload"] != null)
                {
                    //if the file is null, check the Request.Files construct before giving up
                    if (file == null)
                    {
                        try
                        {
                            file = Request.Files["file"];
                        }
                        catch (Exception)
                        {
                        }
                    }
                    if (file != null) // Upload Picture
                    {
                        Bitmap image;
                        try
                        {
                            image = new Bitmap(file.InputStream);
                        }
                        catch
                        {   // If image format is invalid, discard it.
                            image = null;
                        }

                        if (image != null)
                        {
                            int thumbSize = 128;

                            // Crop image to a square.
                            int square = Math.Min(image.Width, image.Height);
                            using (Bitmap cropImage = new Bitmap(square, square))
                            {
                                using (Bitmap finalImage = new Bitmap(thumbSize, thumbSize))
                                {
                                    Graphics cropGraphics  = Graphics.FromImage(cropImage);
                                    Graphics finalGraphics = Graphics.FromImage(finalImage);

                                    // Center cropped image horizontally, leave at the top vertically. (better focus on subject)
                                    cropGraphics.DrawImage(image, -(image.Width - cropImage.Width) / 2, 0);

                                    // Convert to thumbnail.
                                    finalGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

                                    finalGraphics.DrawImage(cropImage,
                                                            new Rectangle(0, 0, thumbSize, thumbSize),
                                                            new Rectangle(0, 0, square, square),
                                                            GraphicsUnit.Pixel);

                                    // Write image to user's profile
                                    CurrentUser.SetProfileImage(finalImage);
                                }
                            }
                        }
                    }
                }
                else
                {
                    //reset to default profile picture
                    IdenticonRenderer renderer = new IdenticonRenderer();
                    CurrentUser.SetProfileImage(renderer.Render(CurrentUser.Email.GetHashCode(), 128));
                }
                return(RedirectToAction("Edit"));
            }
            catch (Exception ex)
            {
                LogErrorMessage(ex);
                return(RedirectToAction("Index", "Error"));
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Returns the profile picture for the supplied user id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public FileStreamResult Picture(int id, int size = 128)
        {
            try
            {
                //invalid user ID?
                if (id < 1)
                {
                    return(DefaultPicture(size));
                }

                ProfileImage          image    = Db.ProfileImages.Where(p => p.UserID == id).FirstOrDefault();
                IdenticonRenderer     renderer = new IdenticonRenderer();
                System.Drawing.Bitmap userBitmap;
                if (image != null)
                {
                    try
                    {
                        userBitmap = image.GetProfileImage();
                    }
                    catch (Exception)
                    {
                        userBitmap = renderer.Render(image.User.Email.GetHashCode(), 128);
                        image.SetProfileImage(userBitmap);
                        Db.SaveChanges();
                    }
                }
                else
                {
                    OsbideUser user = Db.Users.Where(u => u.Id == id).FirstOrDefault();
                    if (user != null && user.ProfileImage == null)
                    {
                        try
                        {
                            user.SetProfileImage(renderer.Render(user.Email.GetHashCode(), 128));
                            userBitmap = user.ProfileImage.GetProfileImage();
                            Db.SaveChanges();
                        }
                        catch (Exception)
                        {
                            userBitmap = renderer.Render(1, 128);
                        }
                    }
                    else
                    {
                        userBitmap = renderer.Render(1, 128);
                    }
                }

                if (size != 128)
                {
                    Bitmap   bmp   = new Bitmap(userBitmap, size, size);
                    Graphics graph = Graphics.FromImage(userBitmap);
                    graph.InterpolationMode  = InterpolationMode.High;
                    graph.CompositingQuality = CompositingQuality.HighQuality;
                    graph.SmoothingMode      = SmoothingMode.AntiAlias;
                    graph.DrawImage(bmp, new Rectangle(0, 0, size, size));
                    userBitmap = bmp;
                }

                MemoryStream stream = new MemoryStream();
                userBitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                stream.Position = 0;
                return(new FileStreamResult(stream, "image/png"));
            }
            catch (Exception ex)
            {
                LogErrorMessage(ex);
                return(null);
            }
        }
Exemplo n.º 8
0
        public static void Seed(OsbideContext context)
        {
            //add in some sample schools
            School wsu = new School()
            {
                Name = "Washington State University"
            };

            context.Schools.Add(wsu);
            context.Schools.Add(new School()
            {
                Name = "Other Institution"
            });
            context.SaveChanges();

            //add in default chat rooms
            context.ChatRooms.Add(new ChatRoom()
            {
                Name = "General Chat", SchoolId = wsu.Id, IsDefaultRoom = true
            });
            context.ChatRooms.Add(new ChatRoom()
            {
                Name = "CptS 121 Chat", SchoolId = wsu.Id, IsDefaultRoom = false
            });
            context.ChatRooms.Add(new ChatRoom()
            {
                Name = "CptS 122 Chat", SchoolId = wsu.Id, IsDefaultRoom = false
            });
            context.ChatRooms.Add(new ChatRoom()
            {
                Name = "CptS 223 Chat", SchoolId = wsu.Id, IsDefaultRoom = false
            });

            //[obsolete]
            //add in some default subscriptions
            //context.UserSubscriptions.Add(new UserSubscription() { ObserverInstitutionId = 123, ObserverSchoolId = 1, SubjectSchoolId = 1, SubjectInstitutionId = 456 });
            //context.UserSubscriptions.Add(new UserSubscription() { ObserverInstitutionId = 123, ObserverSchoolId = 1, SubjectSchoolId = 1, SubjectInstitutionId = 789, IsRequiredSubscription = true });
            //context.UserSubscriptions.Add(new UserSubscription() { ObserverInstitutionId = 456, ObserverSchoolId = 1, SubjectSchoolId = 1, SubjectInstitutionId = 789, IsRequiredSubscription = true });

            //also set up some courses
            context.Courses.Add(new Course()
            {
                Name        = "OSBIDE 101",
                Year        = 2014,
                Season      = "Spring",
                SchoolId    = 1,
                Description = "Everything you ever wanted to know about OSBIDE."
            }
                                );

            context.Courses.Add(new Course()
            {
                Name        = "CptS 121",
                Year        = 2014,
                Season      = "Spring",
                SchoolId    = 1,
                Description = "Formulation of problems and top-down design of programs in a modern structured language for their solution on a digital computer."
            }
                                );

            context.Courses.Add(new Course()
            {
                Name        = "CptS 122",
                Year        = 2014,
                Season      = "Spring",
                SchoolId    = 1,
                Description = "This course is about advanced programming techniques, data structures, recursion, sorting, searching, and basic algorithm analysis."
            }
                                );

            context.Courses.Add(new Course()
            {
                Name        = "CptS 223",
                Year        = 2014,
                Season      = "Spring",
                SchoolId    = 1,
                Description = "Advanced data structures, object oriented programming concepts, concurrency, and program design principles."
            }
                                );

            context.Courses.Add(new Course()
            {
                Name        = "CptS 483",
                Year        = 2014,
                Season      = "Spring",
                SchoolId    = 1,
                Description = "Web development"
            }
                                );

            context.SaveChanges();

            //add some test users
            IdenticonRenderer renderer = new IdenticonRenderer();
            OsbideUser        joe      = new OsbideUser()
            {
                FirstName       = "Joe",
                LastName        = "User",
                Email           = "*****@*****.**",
                InstitutionId   = 123,
                SchoolId        = wsu.Id,
                Role            = SystemRole.Student,
                Gender          = Gender.Male,
                DefaultCourseId = 1
            };

            joe.SetProfileImage(renderer.Render(joe.Email.GetHashCode(), 128));
            context.Users.Add(joe);

            OsbideUser betty = new OsbideUser()
            {
                FirstName       = "Betty",
                LastName        = "Rogers",
                Email           = "*****@*****.**",
                InstitutionId   = 456,
                SchoolId        = wsu.Id,
                Role            = SystemRole.Student,
                Gender          = Gender.Female,
                DefaultCourseId = 1
            };

            betty.SetProfileImage(renderer.Render(betty.Email.GetHashCode(), 128));
            context.Users.Add(betty);
            context.SaveChanges();

            OsbideUser adam = new OsbideUser()
            {
                FirstName       = "Adam",
                LastName        = "Carter",
                Email           = "*****@*****.**",
                InstitutionId   = 789,
                SchoolId        = wsu.Id,
                Role            = SystemRole.Instructor,
                Gender          = Gender.Male,
                DefaultCourseId = 1
            };

            adam.SetProfileImage(renderer.Render(adam.Email.GetHashCode(), 128));
            context.Users.Add(adam);
            context.SaveChanges();

            //...and set their passwords
            UserPassword up = new UserPassword();

            up.UserId   = joe.Id;
            up.Password = UserPassword.EncryptPassword("123123", joe);
            context.UserPasswords.Add(up);

            up          = new UserPassword();
            up.UserId   = betty.Id;
            up.Password = UserPassword.EncryptPassword("123123", betty);
            context.UserPasswords.Add(up);

            up          = new UserPassword();
            up.UserId   = adam.Id;
            up.Password = UserPassword.EncryptPassword("123123", adam);
            context.UserPasswords.Add(up);
            context.SaveChanges();

            //add students to the courses
            context.Courses.Find(1).CourseUserRelationships.Add(new CourseUserRelationship()
            {
                UserId = 3, CourseId = 1, Role = CourseRole.Coordinator
            });
            context.Courses.Find(1).CourseUserRelationships.Add(new CourseUserRelationship()
            {
                UserId = 1, CourseId = 1, Role = CourseRole.Student
            });
            context.Courses.Find(1).CourseUserRelationships.Add(new CourseUserRelationship()
            {
                UserId = 2, CourseId = 1, Role = CourseRole.Assistant
            });

            context.Courses.Find(2).CourseUserRelationships.Add(new CourseUserRelationship()
            {
                UserId = 3, CourseId = 2, Role = CourseRole.Coordinator
            });
            context.Courses.Find(2).CourseUserRelationships.Add(new CourseUserRelationship()
            {
                UserId = 1, CourseId = 2, Role = CourseRole.Student
            });
            context.Courses.Find(2).CourseUserRelationships.Add(new CourseUserRelationship()
            {
                UserId = 2, CourseId = 2, Role = CourseRole.Assistant
            });
            context.SaveChanges();
        }