Exemplo n.º 1
0
 private void Render()
 {
     using (var context = visual.RenderOpen())
     {
         var rect = new Rectangle(0, 0, (int)ActualWidth, (int)ActualHeight);
         Identicon.FromValue(Value, Math.Min(rect.Width, rect.Height)).Draw(context, rect);
     }
 }
Exemplo n.º 2
0
        private void DrawIcon()
        {
            var bitmap = new Bitmap(64, 64);
            var g      = Graphics.FromImage(bitmap);

            Identicon.FromValue(tokenID, 64).Draw(g, new Rectangle(0, 0, 64, 64));

            TokenIcon.Fill = new ImageBrush(Helper.BitmapToImageSource(bitmap));
        }
Exemplo n.º 3
0
        public string GenerateAndSaveAvatar(string username)
        {
            var icon = Identicon.FromValue(username, size: 512);

            var filename   = GenerateFilename() + ".png";
            var pathToSave = GetFullAvatarPath(filename);

            icon.SaveAsPng(pathToSave);
            return(filename);
        }
Exemplo n.º 4
0
        public ActionResult UserImage(int?size, string UserId)
        {
            if (size == null)
            {
                size = 100;
            }
            if (UserId != null)
            {
            }
            else
            {
                if (User.Identity.IsAuthenticated)
                {
                    UserId = User.Identity.GetUserId();
                }
            }

            // Check for image in DB
            using (var db = new ZapContext())
            {
                MemoryStream ms = new MemoryStream();

                if (db.Users.Where(u => u.AppId == UserId).Count() > 0)
                {
                    var img = db.Users.Where(u => u.AppId == UserId).First().ProfileImage;
                    if (img.Image != null)
                    {
                        Image  png   = Image.FromStream(new MemoryStream(img.Image));
                        Bitmap thumb = ImageExtensions.ResizeImage(png, (int)size, (int)size);
                        byte[] data  = thumb.ToByteArray(ImageFormat.Png);

                        return(File(data, "image/png"));
                    }
                }
                // Alternative if userId was username
                else if (db.Users.Where(u => u.Name == UserId).Count() > 0)
                {
                    var userAppId = db.Users.Where(u => u.Name == UserId).FirstOrDefault().AppId;
                    var img       = db.Users.Where(u => u.AppId == userAppId).First().ProfileImage;
                    if (img.Image != null)
                    {
                        Image  png   = Image.FromStream(new MemoryStream(img.Image));
                        Bitmap thumb = ImageExtensions.ResizeImage(png, (int)size, (int)size);
                        byte[] data  = thumb.ToByteArray(ImageFormat.Png);

                        return(File(data, "image/png"));
                    }
                }

                var icon = Identicon.FromValue(UserId, size: (int)size);

                icon.SaveAsPng(ms);
                return(File(ms.ToArray(), "image/png"));
            }
        }
Exemplo n.º 5
0
        public void Identicon_Png()
        {
            var icon = Identicon.FromValue("Jdenticon", 100);

            var expected = icon.SaveAsPng();

            AssertEqualRewinded("SaveAsPng()", expected, icon.SaveAsPng());
            AssertEqualStream("SaveAsPng(stream)", expected, stream => icon.SaveAsPng(stream));
            AssertEqualFile("SaveAsPng(path)", expected, path => icon.SaveAsPng(path));
            AssertEqualStream("SaveAsPngAsync(stream)", expected, stream => icon.SaveAsPngAsync(stream));
            AssertEqualFile("SaveAsPngAsync(path)", expected, path => icon.SaveAsPngAsync(path));
        }
Exemplo n.º 6
0
        protected override void OnAppearing()
        {
            base.OnAppearing();
            LabelUsername.Text = Application.Current.Properties["username"].ToString();
            Stream stream = new MemoryStream();

            stream = Identicon.FromValue(Application.Current.Properties["username"].ToString(), 150).SaveAsPng();

            ImageSource avatarSource = ImageSource.FromStream(() => stream);

            AvatarImage.Source = avatarSource;
        }
Exemplo n.º 7
0
        public void Identicon_Emf()
        {
            var icon = Identicon.FromValue("Jdenticon", 100);

            // Dry run since the first file seems to be a little different
            icon.SaveAsEmf();

            var expected = icon.SaveAsEmf();

            AssertEqualRewinded("SaveAsEmf()", expected, icon.SaveAsEmf());
            AssertEqualStream("SaveAsEmf(stream)", expected, stream => icon.SaveAsEmf(stream));
            AssertEqualFile("SaveAsEmf(path)", expected, path => icon.SaveAsEmf(path));
            AssertEqualStream("SaveAsEmfAsync(stream)", expected, stream => icon.SaveAsEmfAsync(stream));
            AssertEqualFile("SaveAsEmfAsync(path)", expected, path => icon.SaveAsEmfAsync(path));
        }
Exemplo n.º 8
0
        public static string GenerateIcon(string username)
        {
            var tmpdir    = Path.GetTempPath();
            var appFolder = Path.Combine(tmpdir, AppConstants.AppName);

            Directory.CreateDirectory(appFolder);

            var imgFile = Path.Combine(appFolder, username + ".png");

            if (File.Exists(imgFile) == false)
            {
                Identicon.FromValue(username, 160).SaveAsPng(imgFile);
            }
            return(imgFile);
        }
Exemplo n.º 9
0
        public Bitmap GetIdenticon(int size)
        {
            Color fillColor;

            byte r = byte.Parse(Revision.Diff.HashOfDiff.Substring(0, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
            byte g = byte.Parse(Revision.Diff.HashOfDiff.Substring(2, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
            byte b = byte.Parse(Revision.Diff.HashOfDiff.Substring(4, 2), System.Globalization.NumberStyles.AllowHexSpecifier);

            fillColor = Color.FromArgb(r, g, b);

            var identicon = Identicon.FromValue(Revision.Diff.HashOfDiff, size);

            identicon.Style           = new IdenticonStyle();
            identicon.Style.BackColor = Jdenticon.Rendering.Color.FromArgb(255, fillColor.R, fillColor.G, fillColor.B);

            return(identicon.ToBitmap());
        }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            var icon = Identicon.FromValue("df", 160);

            icon.Style.BackColor = Jdenticon.Rendering.Color.Transparent;

            icon.SaveAsPng("M:\\test1509-own.png");

            using (var bmp = icon.ToBitmap())
            {
                bmp.Save("M:\\test1509-gdi.png", System.Drawing.Imaging.ImageFormat.Png);
            }

            //return;

            Benchmarker.Run("Own", () =>
            {
                using (var stream = new MemoryStream())
                {
                    icon.SaveAsPng(stream);
                }
            }, 200);
            Benchmarker.Run("Gdi", () =>
            {
                using (var stream = new MemoryStream())
                {
                    icon.ToBitmap().Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                }
            }, 200);

            Benchmarker.Run("Own", () =>
            {
                using (var stream = new MemoryStream())
                {
                    icon.SaveAsPng(stream);
                }
            }, 200);
            Benchmarker.Run("Gdi", () =>
            {
                using (var stream = new MemoryStream())
                {
                    icon.ToBitmap().Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                }
            }, 200);
        }
Exemplo n.º 11
0
        public void CreateIdenticon(string identifier)
        {
            //these are fine tuned. Fabric should be not too light, as there is quite a bit of white space in the design

            //identicon
            var identiconId    = identifier;
            var identiconStyle = new IdenticonStyle
            {
                ColorLightness      = Range.Create(0.22f, 0.75f),
                GrayscaleLightness  = Range.Create(0.52f, 0.7f),
                GrayscaleSaturation = 0.10f,
                ColorSaturation     = 0.75f,
                Padding             = 0f
            };

            var identicon = Identicon.FromValue(identiconId, size: 80);

            identicon.Style = identiconStyle;

            if (!File.Exists(IdenticonImagePath()))
            {
                identicon.SaveAsPng(IdenticonImagePath());
            }


            //fabric
            var fabricId    = ReverseString(identifier);
            var fabricStyle = new IdenticonStyle
            {
                ColorLightness      = Range.Create(0.33f, 0.48f),
                GrayscaleLightness  = Range.Create(0.30f, 0.45f),
                ColorSaturation     = 0.7f,
                GrayscaleSaturation = 0.7f,
                Padding             = 0f
            };

            var fabricIcon = Identicon.FromValue(fabricId, size: 13);

            fabricIcon.Style = fabricStyle;

            if (!File.Exists(FabricImagePath()))
            {
                fabricIcon.SaveAsPng(FabricImagePath());
            }
        }
Exemplo n.º 12
0
        private static void Test(int iconNumber, IdenticonStyle style)
        {
            var icon = Identicon.FromValue(iconNumber, 50);

            if (style != null)
            {
                icon.Style = style;
            }

            using (var actualStream = new MemoryStream())
            {
                icon.SaveAsPng(actualStream);

                var actualBytes = actualStream.ToArray();

                using (var expectedStream = GetExpectedIcon($"{iconNumber}.png"))
                {
                    // +1 to be able to detect a too short actual icon
                    var expectedBytes     = new byte[actualBytes.Length + 1];
                    var expectedByteCount = expectedStream.Read(expectedBytes, 0, actualBytes.Length);

                    if (expectedByteCount != actualBytes.Length ||
                        expectedBytes.Take(expectedByteCount).SequenceEqual(actualBytes) == false)
                    {
                        Assert.Fail("Icon '{0}' failed PNG rendering test.", iconNumber);
                    }
                }
            }

            var actualSvg = icon.ToSvg();

            using (var expectedStream = GetExpectedIcon($"{iconNumber}.svg"))
            {
                using (var reader = new StreamReader(expectedStream))
                {
                    var expectedSvg = reader.ReadToEnd();

                    if (actualSvg != expectedSvg)
                    {
                        Assert.Fail("Icon '{0}' failed SVG rendering test.", iconNumber);
                    }
                }
            }
        }
Exemplo n.º 13
0
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
     if (value is string information)
     {
         var data    = information.ToLower().Replace(" ", "");
         var imgFile = Path.Combine(Path.GetTempPath(), data + ".png");
         if (File.Exists(imgFile))
         {
             return(imgFile);
         }
         else
         {
             Identicon.FromValue(data, size: 160)
             .SaveAsPng(imgFile);
             return(imgFile);
         }
     }
     return(string.Empty);
 }
Exemplo n.º 14
0
    public void LoadJdenticon(string address)
    {
        Identicon icon = Identicon.FromValue(address, 100);

        Identicon.DefaultStyle.BackColor = Jdenticon.Rendering.Color.Transparent;
        icon.SaveAsPng(Application.persistentDataPath + "/icon.png");

        Texture2D tex = null;

        byte[] fileData;
        if (File.Exists(Application.persistentDataPath + "/icon.png"))
        {
            fileData = File.ReadAllBytes(Application.persistentDataPath + "/icon.png");
            tex      = new Texture2D(2, 2);
            tex.LoadImage(fileData);
        }

        Icon.sprite  = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
        Address.text = address;
    }
Exemplo n.º 15
0
        private static void Test(int iconNumber, IdenticonStyle style)
        {
            var icon = Identicon.FromValue(iconNumber, 50);

            if (style != null)
            {
                icon.Style = style;
            }

            using (var actualStream = new MemoryStream())
            {
                icon.SaveAsPng(actualStream);

                actualStream.Position = 0;
                testBed.AssertEqual(actualStream, $"{iconNumber}.png");
            }

            var actualSvg = icon.ToSvg();

            testBed.AssertEqual(actualSvg, $"{iconNumber}.svg");
        }
Exemplo n.º 16
0
        private void SetImage(Address address)
        {
            var image   = Identicon.FromValue(address, 62);
            var bgColor = image.Style.BackColor;

            image.Style.BackColor = Jdenticon.Rendering.Color.FromRgba(bgColor.R, bgColor.G, bgColor.B, 0);
            var ms = new MemoryStream();

            image.SaveAsPng(ms);
            var buffer = new byte[ms.Length];

            ms.Read(buffer, 0, buffer.Length);
            var t = new Texture2D(8, 8);

            if (t.LoadImage(ms.ToArray()))
            {
                var sprite = Sprite.Create(t, new Rect(0, 0, t.width, t.height), Vector2.zero);
                accountImage.overrideSprite = sprite;
                accountImage.SetNativeSize();
                accountAddressText.text = address.ToString();
                accountAddressText.gameObject.SetActive(true);
            }
        }
Exemplo n.º 17
0
        public async Task <IActionResult> GetAvatarResult <T>(T entity, bool useIdenticon = true) where T : IIdentifiable <Guid>
        {
            if (entity == null)
            {
                return(new NotFoundResult());
            }

            var avatar = await GetAvatarBlob(entity);

            Stream imageStream;

            if (await avatar.ExistsAsync())
            {
                imageStream = await avatar.OpenReadAsync();
            }
            else if (useIdenticon)
            {
                imageStream = new MemoryStream();
                await Identicon
                .FromValue(entity.Id.ToString(), _configuration.GetSection("Avatars").GetValue <int>("Width"))
                .SaveAsPngAsync(imageStream);

                imageStream.Position = 0;
            }
            else
            {
                using Image image = Image.Load("projectdefault.png");
                imageStream       = new MemoryStream();
                image.SaveAsPng(imageStream);
                imageStream.Position = 0;
            }

            return(new FileStreamResult(imageStream, "image/png")
            {
                FileDownloadName = entity.Id.ToString("D") + ".png"
            });
        }
Exemplo n.º 18
0
        public async Task <SignUpAccountResponse> SignUpAccountAsync(Dictionary <ParameterTypeEnum, object> parameters)
        {
            telemetryClient.TrackTrace("Starting helper");

            SignUpAccountResponse result = new SignUpAccountResponse
            {
                IsSucceded = true,
                ResultId   = (int)SignUpAccountResultEnum.Success
            };

            try
            {
                telemetryClient.TrackTrace("Getting parameters");

                parameters.TryGetValue(ParameterTypeEnum.Username, out global::System.Object ousername);
                string username = ousername.ToString().ToLower();

                parameters.TryGetValue(ParameterTypeEnum.Password, out global::System.Object opassword);
                string password = opassword.ToString();

                parameters.TryGetValue(ParameterTypeEnum.AccountImagesContainer, out global::System.Object oaccountImagesContainer);
                string accountImagesContainer = oaccountImagesContainer.ToString();

                parameters.TryGetValue(ParameterTypeEnum.FunctionDirectory, out global::System.Object ofunctionDirectory);
                string functionDirectory = ofunctionDirectory.ToString();

                //database helpers
                DBUserAccountHelper dbUserAccountHelper = new DBUserAccountHelper(DBCONNECTION_INFO);

                telemetryClient.TrackTrace("Validating username length");

                //validate username length
                if (!RegexValidation.IsValidUsername(username))
                {
                    result.IsSucceded = false;
                    result.ResultId   = (int)SignUpAccountResultEnum.InvalidUsernameLength;
                    return(result);
                }

                telemetryClient.TrackTrace("Validating username existance");

                //validate if account exists
                UserAccount userAccount = dbUserAccountHelper.GetUser(username);

                if (userAccount != null)
                {
                    result.IsSucceded = false;
                    result.ResultId   = (int)SignUpAccountResultEnum.AlreadyExists;
                    return(result);
                }

                telemetryClient.TrackTrace("Adding account to database");

                //save username and account in mongodb
                userAccount = new UserAccount()
                {
                    username    = username,
                    password    = MD5Hash.CalculateMD5Hash(password),
                    createdDate = Timezone.GetCustomTimeZone()
                };

                //perform insert in mongodb
                await dbUserAccountHelper.CreateUserAccount(userAccount);

                telemetryClient.TrackTrace("Adding account image to storage");

                //create unique icon, upload and delete it
                var imageName = $"{username}.png";
                try
                {
                    var directory = Path.Combine(functionDirectory, "images");
                    var filePath  = Path.Combine(directory, imageName);

                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }

                    Identicon.FromValue(username, size: 160).SaveAsPng(filePath);
                    await UploadAccountImageAsync(accountImagesContainer, imageName, filePath);

                    File.Delete(filePath);
                }
                catch
                {
                    //it doesn't matter if for some reason the icon generation fails, then ignore it and proceed as success
                }

                result.Image = imageName;
            }
            catch (AggregateException ex)
            {
                foreach (var innerException in ex.Flatten().InnerExceptions)
                {
                    telemetryClient.TrackException(innerException);
                }
                result.IsSucceded = false;
                result.ResultId   = (int)SignUpAccountResultEnum.Failed;
            }
            catch (Exception ex)
            {
                telemetryClient.TrackException(ex);
                result.IsSucceded = false;
                result.ResultId   = (int)SignUpAccountResultEnum.Failed;
            }

            telemetryClient.TrackTrace("Finishing helper");
            return(result);
        }
Exemplo n.º 19
0
        private async void CercaPersone(object obj)
        {
            ListaAmici.Children.Clear();
            //Metti la logica della ricerca qua
            List <UserModel> usersFound = await App.apiHelper.searchUsersByUsername(EntrySearch.Text);

            foreach (UserModel user in usersFound)
            {
                if (user.id != Application.Current.Properties["id"].ToString())
                {
                    StackLayout stackUser = new StackLayout {
                        Margin        = new Thickness(10, 0, 10, 0),
                        Orientation   = StackOrientation.Horizontal,
                        Padding       = 0,
                        HeightRequest = 50
                    };
                    ListaAmici.Children.Add(stackUser);
                    stackUser.Children.Add(new Image
                    {
                        Source            = ImageSource.FromStream(() => Identicon.FromValue(user.username, 150).SaveAsPng()),
                        VerticalOptions   = LayoutOptions.CenterAndExpand,
                        HorizontalOptions = LayoutOptions.Start,
                        HeightRequest     = 50,
                        WidthRequest      = 50,
                        Clip = new EllipseGeometry(new Point(25, 25), 25, 25)
                    });
                    stackUser.Children.Add(new Label {
                        Text                  = user.username,
                        TextColor             = Color.Black,
                        FontAttributes        = FontAttributes.Bold,
                        FontSize              = 16,
                        HorizontalOptions     = LayoutOptions.Start,
                        VerticalOptions       = LayoutOptions.CenterAndExpand,
                        VerticalTextAlignment = TextAlignment.Center
                    });
                    if (friendList.Where(o => o.id == user.id).ToList().Count > 0)
                    {
                        stackUser.Children.Add(new Button
                        {
                            Text              = FontLoader.FriendIcon,
                            FontFamily        = "icon_font",
                            Padding           = 0,
                            FontSize          = 25,
                            TextColor         = Color.Black,
                            BackgroundColor   = Color.Transparent,
                            VerticalOptions   = LayoutOptions.CenterAndExpand,
                            HorizontalOptions = LayoutOptions.EndAndExpand
                        });
                    }
                    else
                    {
                        Button addFriendBtn = new Button
                        {
                            Text              = FontLoader.PlusIcon,
                            FontFamily        = "icon_font",
                            Padding           = 0,
                            FontSize          = 25,
                            TextColor         = Color.Green,
                            BackgroundColor   = Color.Transparent,
                            VerticalOptions   = LayoutOptions.CenterAndExpand,
                            HorizontalOptions = LayoutOptions.EndAndExpand,
                        };
                        addFriendBtn.Clicked += async(sender, e) => {
                            await App.apiHelper.createNewFriendship(user.id);

                            App.apiHelper.sendNotification(user.id, "Nuova richiesta", App.Current.Properties["username"] + " ti ha inviato una richiesta di amicizia");
                            notificationSystem.AddNewNotification("Aggiunto!", "Hai mandato una richiesta di amicizia a " + user.username, Color.Green);
                        };
                        stackUser.Children.Add(addFriendBtn);
                    }
                }
            }
        }
Exemplo n.º 20
0
        private static void Main(string[] args)
        {
            Task.Run(() =>
            {
                try
                {
                    // initialize settings
                    Init();

                    Console.WriteLine($"Take it easy, the console will display important messages, actually, it's running!! :)");

                    ConnectionFactory factory = new ConnectionFactory();
                    factory.UserName          = ApplicationSettings.RabbitMQUsername;
                    factory.Password          = ApplicationSettings.RabbitMQPassword;
                    factory.HostName          = ApplicationSettings.RabbitMQHostname;
                    factory.Port = ApplicationSettings.RabbitMQPort;
                    factory.RequestedHeartbeat     = 60;
                    factory.DispatchConsumersAsync = true;

                    var connection = factory.CreateConnection();
                    var channel    = connection.CreateModel();

                    channel.QueueDeclare(queue: ApplicationSettings.UserRegistrationQueueName,
                                         durable: true,
                                         exclusive: false,
                                         autoDelete: false,
                                         arguments: null);

                    channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);

                    var consumer       = new AsyncEventingBasicConsumer(channel);
                    consumer.Received += async(model, ea) =>
                    {
                        UserRegistrationResponse response = new UserRegistrationResponse
                        {
                            IsSucceded = true,
                            ResultId   = (int)UserRegistrationResponseEnum.Success
                        };

                        // forced-to-disposal
                        WalletRegistrationInfo walletInfo       = null;
                        NBitcoin.Wordlist nwordlist             = null;
                        Nethereum.HdWallet.Wallet wallet        = null;
                        Nethereum.Web3.Accounts.Account account = null;
                        string jsonDecrypted = string.Empty;
                        string jsonEncrypted = string.Empty;
                        User user            = null;
                        UserActivationDataHelper userActivationDataHelper = null;
                        MailHelper mailHelper = null;

                        try
                        {
                            byte[] body = ea.Body;
                            var message = Encoding.UTF8.GetString(body);

                            var decrypted = string.Empty;
                            decrypted     = NETCore.Encrypt.EncryptProvider.AESDecrypt(message, secret);

                            var obj_decrypted = JsonConvert.DeserializeObject <UserRegistrationMessage>(decrypted);

                            var aeskey_wallet = NETCore.Encrypt.EncryptProvider.CreateAesKey();
                            var key_wallet    = aeskey_wallet.Key;

                            nwordlist = new NBitcoin.Wordlist(wordlist.ToArray(), ' ', "english");
                            wallet    = new Nethereum.HdWallet.Wallet(nwordlist, NBitcoin.WordCount.Eighteen, key_wallet);
                            account   = wallet.GetAccount(0);

                            walletInfo = new WalletRegistrationInfo();

                            walletInfo.address    = account.Address;
                            walletInfo.privateKey = account.PrivateKey;
                            walletInfo.password   = key_wallet;
                            walletInfo.mnemonic   = string.Join(" ", wallet.Words);

                            jsonDecrypted = JsonConvert.SerializeObject(walletInfo);

                            var aeskey_data = NETCore.Encrypt.EncryptProvider.CreateAesKey();
                            var key_data    = aeskey_data.Key;
                            jsonEncrypted   = NETCore.Encrypt.EncryptProvider.AESEncrypt(jsonDecrypted, key_data);

                            string identicon = string.Empty;
                            try
                            {
                                Identicon.FromValue($"{account.Address}", size: 160).SaveAsPng($"{account.Address}.png");
                                byte[] binary = System.IO.File.ReadAllBytes($"{account.Address}.png");
                                identicon     = Convert.ToBase64String(binary);
                                System.IO.File.Delete($"{account.Address}.png");
                                Console.WriteLine($">> Identicon deleted from local storage");
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine($">> Exception: {ex.Message}, StackTrace: {ex.StackTrace}");

                                if (ex.InnerException != null)
                                {
                                    Console.WriteLine($">> Inner Exception Message: {ex.InnerException.Message}, Inner Exception StackTrace: {ex.InnerException.StackTrace}");
                                }

                                try
                                {
                                    System.IO.File.Delete($"{account.Address}.png");
                                    Console.WriteLine($">> Identicon deleted from local storage");
                                }
                                catch { }
                            }

                            userActivationDataHelper = new UserActivationDataHelper(mongoDBConnectionInfo);

                            // get user by email
                            user = userActivationDataHelper.GetUser(obj_decrypted.email);

                            if (user != null)
                            {
                                throw new BusinessException((int)UserRegistrationResponseEnum.FailedEmailAlreadyExists);
                            }

                            user           = new User();
                            user.fullname  = obj_decrypted.fullname;
                            user.email     = obj_decrypted.email;
                            user.address   = account.Address;
                            user.dataenc   = jsonEncrypted;
                            user.datakey   = key_data;
                            user.identicon = identicon;

                            // register user
                            await userActivationDataHelper.RegisterUserAsync(user);

                            mailHelper = new MailHelper();

                            // send email
                            await mailHelper.SendRegistrationEmailAsync(user.email, user.fullname);
                            Console.WriteLine($">> Email: {user.email} activated successfully");

                            channel.BasicAck(ea.DeliveryTag, false);
                            Console.WriteLine($">> Acknowledgement completed, delivery tag: {ea.DeliveryTag}");
                        }
                        catch (Exception ex)
                        {
                            if (ex is BusinessException)
                            {
                                response.IsSucceded = false;
                                response.ResultId   = ((BusinessException)ex).ResultId;

                                string message = EnumDescription.GetEnumDescription((UserRegistrationResponseEnum)response.ResultId);
                                Console.WriteLine($">> Message information: {message}");
                            }
                            else
                            {
                                Console.WriteLine($">> Exception: {ex.Message}, StackTrace: {ex.StackTrace}");

                                if (ex.InnerException != null)
                                {
                                    Console.WriteLine($">> Inner Exception Message: {ex.InnerException.Message}, Inner Exception StackTrace: {ex.InnerException.StackTrace}");
                                }
                            }
                        }
                        finally
                        {
                            nwordlist     = null;
                            wallet        = null;
                            account       = null;
                            walletInfo    = null;
                            jsonDecrypted = null;
                            jsonEncrypted = null;
                            user          = null;
                            userActivationDataHelper.Dispose();
                            mailHelper.Dispose();
                        }
                    };

                    String consumerTag = channel.BasicConsume(ApplicationSettings.UserRegistrationQueueName, false, consumer);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($">> Exception: {ex.Message}, StackTrace: {ex.StackTrace}");

                    if (ex.InnerException != null)
                    {
                        Console.WriteLine($">> Inner Exception Message: {ex.InnerException.Message}, Inner Exception StackTrace: {ex.InnerException.StackTrace}");
                    }
                }
            });

            // handle Control+C or Control+Break
            Console.CancelKeyPress += (o, e) =>
            {
                Console.WriteLine("Exit");

                // allow the manin thread to continue and exit...
                waitHandle.Set();
            };

            // wait
            waitHandle.WaitOne();
        }
Exemplo n.º 21
0
        public async void OnAnimationStarted(bool isPopAnimation)
        {
            if (!isPopAnimation)
            {
                friendList = await App.apiHelper.getAllFriendsOfCurrentUser();

                foreach (UserModel user in friendList)
                {
                    StackLayout stackUser = new StackLayout
                    {
                        Margin        = new Thickness(10, 0, 10, 0),
                        Orientation   = StackOrientation.Horizontal,
                        Padding       = 0,
                        HeightRequest = 50
                    };
                    ListaAmici.Children.Add(stackUser);
                    stackUser.Children.Add(new Image
                    {
                        Source            = ImageSource.FromStream(() => Identicon.FromValue(user.username, 150).SaveAsPng()),
                        VerticalOptions   = LayoutOptions.CenterAndExpand,
                        HorizontalOptions = LayoutOptions.Start,
                        HeightRequest     = 50,
                        WidthRequest      = 50,
                        Clip = new EllipseGeometry(new Point(25, 25), 25, 25)
                    });
                    stackUser.Children.Add(new Label
                    {
                        Text                  = user.username,
                        TextColor             = Color.Black,
                        FontAttributes        = FontAttributes.Bold,
                        FontSize              = 16,
                        HorizontalOptions     = LayoutOptions.Start,
                        VerticalOptions       = LayoutOptions.CenterAndExpand,
                        VerticalTextAlignment = TextAlignment.Center
                    });

                    if (user.friendStatusWithCurrent == "toAccept")
                    {
                        Button refuseBtn = new Button
                        {
                            Text              = FontLoader.CrossIcon,
                            FontFamily        = "icon_font",
                            Padding           = 0,
                            FontSize          = 25,
                            TextColor         = Color.Red,
                            BackgroundColor   = Color.Transparent,
                            VerticalOptions   = LayoutOptions.CenterAndExpand,
                            HorizontalOptions = LayoutOptions.EndAndExpand
                        };
                        refuseBtn.Clicked += async(sender, e) => {
                            await App.apiHelper.refuseFriendshipByIds(user.id, App.Current.Properties["id"].ToString());

                            App.apiHelper.sendNotification(user.id, "Peggio della friendzone", App.Current.Properties["username"] + " ha rifiutato la tua richiesta d'amicizia :(");
                            notificationSystem.AddNewNotification("Rifiutato", "Hai rifiutato la richiesta di " + user.username, Color.Red);
                            ListaAmici.Children.Remove(stackUser);
                            friendList.Remove(friendList.Where(o => o.id == user.id).ToList()[0]);
                        };
                        stackUser.Children.Add(refuseBtn);

                        Button acceptBtn = new Button
                        {
                            Text              = FontLoader.PlusIcon,
                            FontFamily        = "icon_font",
                            Padding           = 0,
                            FontSize          = 25,
                            TextColor         = Color.Green,
                            BackgroundColor   = Color.Transparent,
                            VerticalOptions   = LayoutOptions.CenterAndExpand,
                            HorizontalOptions = LayoutOptions.EndAndExpand
                        };
                        acceptBtn.Clicked += async(sender, e) => {
                            await App.apiHelper.acceptFriendshipByIds(user.id, App.Current.Properties["id"].ToString());

                            App.apiHelper.sendNotification(user.id, "Accettato!", App.Current.Properties["username"] + " ha accettato la tua richiesta d'amicizia :)");
                            notificationSystem.AddNewNotification("Accettato", "Hai accettato la richiesta di " + user.username, Color.Green);
                            friendList.Where(o => o.id == user.id).ToList()[0].friendStatusWithCurrent = "accepted";

                            stackUser.Children.Remove(refuseBtn);
                            stackUser.Children.Remove(acceptBtn);
                            stackUser.Children.Add(new Button
                            {
                                Text              = FontLoader.FriendIcon,
                                FontFamily        = "icon_font",
                                Padding           = 0,
                                FontSize          = 25,
                                TextColor         = Color.Black,
                                BackgroundColor   = Color.Transparent,
                                VerticalOptions   = LayoutOptions.CenterAndExpand,
                                HorizontalOptions = LayoutOptions.EndAndExpand
                            });
                        };
                        stackUser.Children.Add(acceptBtn);
                    }
                    else
                    {
                        stackUser.Children.Add(new Label
                        {
                            Text                    = await App.apiHelper.getBalanceFromWallet(user.walletid),
                            TextColor               = Color.Black,
                            FontSize                = 18,
                            VerticalOptions         = LayoutOptions.CenterAndExpand,
                            HorizontalOptions       = LayoutOptions.CenterAndExpand,
                            VerticalTextAlignment   = TextAlignment.Center,
                            HorizontalTextAlignment = TextAlignment.Center
                        });
                        stackUser.Children.Add(new Button
                        {
                            Text              = FontLoader.FriendIcon,
                            FontFamily        = "icon_font",
                            Padding           = 0,
                            FontSize          = 25,
                            TextColor         = Color.Black,
                            BackgroundColor   = Color.Transparent,
                            VerticalOptions   = LayoutOptions.CenterAndExpand,
                            HorizontalOptions = LayoutOptions.EndAndExpand
                        });
                    }
                }
            }
        }
Exemplo n.º 22
0
 /// <summary>
 /// Creates an <see cref="IdenticonResult"/> instance with a hash of the specified object.
 /// </summary>
 /// <param name="value">The string representation of this object will be hashed and used as base for this icon. Null values are supported and handled as empty strings.</param>
 /// <param name="size">The size of the icon in pixels.</param>
 /// <param name="format">The format of the generated icon.</param>
 /// <param name="hashAlgorithmName">The name of the hash algorithm to use for hashing.</param>
 /// <exception cref="ArgumentOutOfRangeException"><paramref name="size"/> was less than 1.</exception>
 public static IdenticonResult FromValue(object value, int size, ExportImageFormat format = ExportImageFormat.Png, string hashAlgorithmName = "SHA1")
 {
     return(new IdenticonResult(Identicon.FromValue(value, size, hashAlgorithmName), format));
 }
Exemplo n.º 23
0
        public IActionResult Get([FromRoute, SwaggerParameter("The ERC 725 identity for the node", Required = true)] string identity, [FromRoute, SwaggerParameter("The theme (mainly used for the website). Options are: light, dark", Required = true)] string theme, [FromRoute, SwaggerParameter("The size of the image in pixels. Options are: 16, 24, 32, 48 and 64", Required = true)] int size)
        {
            if (theme != "dark" && theme != "light")
            {
                theme = "light";
            }

            if (identity.Length != 42 || !identity.StartsWith("0x") || !identity.All(Char.IsLetterOrDigit))
            {
                return(BadRequest());
            }

            if (size > 64)
            {
                size = 64;
            }
            else if (size != 16 && size != 48 && size != 24 && size != 32 && size != 64)
            {
                size = 16;
            }

            Response.Headers["Cache-Control"] = "public,max-age=604800";

            string path;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                path = $@"icons\node\{theme}\{size}\{identity}.png";
            }
            else
            {
                path = $@"icons/node/{theme}/{size}/{identity}.png";
            }

            if (System.IO.File.Exists(path))
            {
                var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous | FileOptions.SequentialScan);
                return(File(fs, "image/png"));
            }

            string firstChar = identity.Substring(2, 1);

            if (!letterToHueDictionary.TryGetValue(firstChar, out var val))
            {
                val = 216;
            }

            var style = new IdenticonStyle
            {
                Hues = new HueCollection {
                    { val, HueUnit.Degrees }
                },
                Padding             = 0.1F,
                BackColor           = theme == "light" ? Color.FromRgb(241, 242, 247) : Color.FromRgb(89, 99, 114),
                ColorSaturation     = 1.0f,
                GrayscaleSaturation = 0.2f,
                ColorLightness      = Jdenticon.Range.Create(0.1f, 0.9f),
                GrayscaleLightness  = Jdenticon.Range.Create(0.1f, 0.5f),
            };

            var icon = Identicon.FromValue("identity:" + identity, size);

            icon.Style = style;

            var folder = Directory.GetParent(path);

            if (!folder.Exists)
            {
                folder.Create();
            }

            using (var ms = new MemoryStream())
                using (var fs = System.IO.File.Open(path, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    icon.SaveAsPng(fs);
                    icon.SaveAsPng(ms);
                    return(File(ms.ToArray(), "image/png"));
                }
        }
Exemplo n.º 24
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();

            //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;
                }

                var alpha = 176;

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

                var iconStyle = new IdenticonStyle
                {
                    BackColor = Jdenticon.Rendering.Color.FromArgb(alpha, raceColor.R, raceColor.G, raceColor.B)
                };
                var identicon = Identicon.FromValue(civ.Name, 128);
                identicon.Style = iconStyle;
                civ.Identicon   = identicon.ToBitmap();
                using (MemoryStream identiconStream = new MemoryStream())
                {
                    civ.Identicon.Save(identiconStream, ImageFormat.Png);
                    byte[] identiconBytes = identiconStream.GetBuffer();
                    civ.IdenticonString = Convert.ToBase64String(identiconBytes);
                }
                var small = Identicon.FromValue(civ.Name, 32);
                small.Style = iconStyle;
                var smallIdenticon = small.ToBitmap();
                using (MemoryStream smallIdenticonStream = new MemoryStream())
                {
                    smallIdenticon.Save(smallIdenticonStream, ImageFormat.Png);
                    byte[] smallIdenticonBytes = smallIdenticonStream.GetBuffer();
                    civ.SmallIdenticonString = Convert.ToBase64String(smallIdenticonBytes);
                }
                foreach (var childGroup in civ.Groups)
                {
                    childGroup.Identicon = civ.Identicon;
                    childGroup.LineColor = civ.LineColor;
                }
            }

            foreach (var entity in Entities.Where(entity => entity.Identicon == null))
            {
                var identicon = Identicon.FromValue(entity.Name, 128);
                entity.Identicon = identicon.ToBitmap();
            }
        }