Ejemplo n.º 1
0
        /// <summary>
        /// Get the value of key. If the key does not exist the special value nil is returned.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task <T> GetAsync <T>(string key)
        {
            Check.NotEmpty(key, nameof(key));

            try
            {
                var db = GetDatabase();

                var value = await db
                            .StringGetAsync(key)
                            .ConfigureAwait(false);

                if (!string.IsNullOrWhiteSpace(value))
                {
                    return(JsonNet.Deserialize <T>(value));
                }
            }
            catch (Exception ex)
            {
                // Don't let cache server unavailability bring down the application.
                _logger.Error(ex, $"Unhandled exception trying to async GET '{key}'");
            }

            return(default(T));
        }
Ejemplo n.º 2
0
        public static CharlieModel LoadFromFile()
        {
            var model = new CharlieModel();

            if (!Directory.Exists(PrefenceDir) ||
                !File.Exists(PreferenceFile))
            {
                return(model);
            }

            var text = File.ReadAllText(PreferenceFile);
            var pref = JsonNet.Deserialize <Preferences>(text);

            model.WindowX      = pref.WindowX;
            model.WindowY      = pref.WindowY;
            model.WindowWidth  = pref.WindowWidth;
            model.WindowHeight = pref.WindowHeight;
            model.PreviousLoaded.Set(pref.PreviousLoadedSims);
            model.SimDelay          = pref.SimDelay;
            model.LogEveryIteration = pref.LogEveryIteration;
            model.RenderWidth       = pref.RenderWidth;
            model.RenderHeight      = pref.RenderHeight;

            return(model);
        }
Ejemplo n.º 3
0
        private void BtnIp_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var client = new RestClient("https://api-fusorario.herokuapp.com");
                client.Authenticator = new HttpBasicAuthenticator("username", "pippo");
                var request = new RestRequest("/ip", Method.GET);
                request.AddParameter("ip", ip.Text);
                IRestResponse response = client.Execute(request);

                var content = response.Content;
                if (response.StatusCode == System.Net.HttpStatusCode.OK && !content.Contains("error"))
                {
                    var resp = JsonNet.Deserialize <Dictionary <string, object> >(content);

                    //composizione output
                    timezone.Text  = " Ip : " + resp["ip"].ToString();
                    timezone.Text += "\r Numero della settimana : " + resp["week_number"].ToString();
                    timezone.Text += "\r Giorno dell'anno : " + resp["day_of_year"].ToString();
                    timezone.Text += "\r Giorno della settimana : " + resp["day_of_week"].ToString();
                    timezone.Text += "\r UTC : " + resp["utc_offset"].ToString();
                    timezone.Text += "\r Data : " + resp["date"].ToString();
                    timezone.Text += "\r Ora : " + resp["time"].ToString();
                    timezone.Text += "\r Zona di fuso orario : " + resp["timezone"].ToString();
                }
                else
                {
                    timezone.Text = "Errore";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Get the value of key. If the key does not exist the special value nil is returned. If the key does exist,
        /// set or update its expiration time.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="expiry"></param>
        /// <returns></returns>
        public T GetWithSlidingExpiration <T>(string key, TimeSpan expiry)
        {
            Check.NotEmpty(key, nameof(key));

            try
            {
                var db = GetDatabase();

                var redisResult = db
                                  .ScriptEvaluate(SLIDING_EXPIRATION_LUA_SCRIPT, new RedisKey[] { key }, new RedisValue[] { expiry.TotalSeconds });

                var value = (string)redisResult;
                if (!string.IsNullOrWhiteSpace(value))
                {
                    return(JsonNet.Deserialize <T>(value));
                }
            }
            catch (Exception ex)
            {
                // Don't let cache server unavailability bring down the application.
                _logger.Error(ex, $"Unhandled exception trying to GET/EXPIRE '{key}'");
            }

            return(default(T));
        }
Ejemplo n.º 5
0
        async Task RunAsync(NotificationDataModel data)
        {
            var myContent     = JsonNet.Serialize(data);
            var stringContent = new StringContent(myContent, UnicodeEncoding.UTF8, "application/json");

            HttpClient client = new HttpClient();

            //client.BaseAddress = new Uri("https://localhost:44333/api/SendPushNotificationPartners/");
            client.BaseAddress = new Uri("https://appi-atah.azurewebsites.net/api/SendPushNotificationPartners/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            try
            {
                var responsevar = "";
                HttpResponseMessage response = await client.PostAsync("https://appi-atah.azurewebsites.net/api/SendPushNotificationPartners/", stringContent);

                //HttpResponseMessage response = await client.PostAsync("https://localhost:44333/api/SendPushNotificationPartners/", stringContent);
                if (response.IsSuccessStatusCode)
                {
                    responsevar = await response.Content.ReadAsStringAsync();
                }
                Respuesta res = JsonNet.Deserialize <Respuesta>(responsevar);

                MessageBox.Show(res.mensaje);
                clean();
            }
            catch (Exception e) {
                string error = e.Message;
                MessageBox.Show("Error con el servicio intente màs tarde");
            }
        }
Ejemplo n.º 6
0
 static void Load()
 {
     try
     {
         if (!File.Exists(DEFAULT_CONF_FILE))
         {
             return;
         }
         conf = new SunfishConfiguration();
         conf = JsonNet.Deserialize <SunfishConfiguration>(File.ReadAllText(DEFAULT_CONF_FILE));
         if (conf.Services == null)
         {
             conf.Services = new List <SunfishServiceConfiguration>();
         }
         sroot.ShowMenu = conf.SunfishRoot;
         foreach (SunfishServiceConfiguration ssc in conf.Services)
         {
             srvs.Add(SunfishService.Instance(ssc));
         }
         if (conf.Active)
         {
             //Bypass set active check
             conf.Active = false;
             SetActive(true);
         }
     }
     catch { }
 }
Ejemplo n.º 7
0
        public void ConverterTest()
        {
            var petJson = JsonNet.Serialize(OriginalPet, DateConverter);

            var restoredPet = JsonNet.Deserialize <Pet>(petJson);

            Debug.Assert(restoredPet.birth.ToString() == OriginalPet.birth.ToString());
        }
Ejemplo n.º 8
0
        public void ConverterTest()
        {
            var petJson = JsonNet.Serialize(OriginalPet, DateConverter);

            var restoredPet = JsonNet.Deserialize <Pet>(petJson);

            Assert.AreEqual(restoredPet.birth.ToString(), OriginalPet.birth.ToString());
            Assert.Pass();
        }
Ejemplo n.º 9
0
        // Загрузка первичных ресурсов
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // Проверяем существование файла конфигурации
            if (File.Exists(configPath))
            {
                // Загрузка конфигурации, в противном случае останется переменная по умолчанию
                this.config = JsonNet.Deserialize <GameConfig>(File.ReadAllText(configPath));
            }

            // Настраиваем параметры окна
            // Двойная буферизация для предотвращения мерцания при обновлении изображения
            this.DoubleBuffered = true;

            // Настраиваем параметры окна из конфигурации
            this.Text       = config.Window.Title;
            this.Left       = config.Window.X;
            this.Top        = config.Window.Y;
            this.ClientSize = new Size(config.Window.Width, config.Window.Height);
            Console.WriteLine(this.Bounds);
            this.WindowState     = config.Window.IsMaximized ? FormWindowState.Maximized : FormWindowState.Normal;
            this.MaximumSize     = new Size(config.Window.MaxWidth, config.Window.MaxHeight);
            this.MinimumSize     = new Size(config.Window.MinWidth, config.Window.MinHeight);
            this.FormBorderStyle = config.Window.IsResizable ? FormBorderStyle.Sizable : FormBorderStyle.FixedDialog;
            this.MaximizeBox     = config.Window.AllowMaximizing;

            // Настраиваем параметры движка из конфигурации
            this.graphicalLoop.Interval = (int)(1000f / (float)this.config.Engine.GraphicalFPS);

            // Запускаем движок
            // Добавляем делегат который будет дёргать перерисовку формы
            this.graphicalLoop.Tick += (sender, args) => this.Refresh();
            this.graphicalLoop.Start();

            // Создаём новый логический поток и запускаем таймер на шаг
            Task.Run(() =>
            {
                var logicalLoop       = new System.Timers.Timer(1000f / (float)this.config.Engine.LogicalFPS);
                logicalLoop.AutoReset = true;
                logicalLoop.Elapsed  += (sender, args) =>
                {
                    // Обновление состояния игры
                    this.game.OnUpdate();
                    this.performance.LogicalRenderTick();
                };
                logicalLoop.Start();
            });

            // Настройка параметров виртуального экрана
            this.vScreen = new Bitmap(config.Engine.VScreenWidth, config.Engine.VScreenHeight);
            this.vGCtx   = Graphics.FromImage(this.vScreen);

            // Говорим игре что готовы работать
            this.game.OnLoad(this.config.Game, this.vScreen, this.vGCtx, this.input);
        }
Ejemplo n.º 10
0
    public InstallsManifest GetInstallsManifest(string ManifestPath)
    {
        var InstallsManifest = JsonNet.Deserialize <InstallsManifest>(File.ReadAllText(ManifestPath));

        if (InstallsManifest == null)
        {
            _loggerService.PrintFatalError(
                new Exception($"Cannot deserialize installs file at {ManifestPath}"));
        }
        return(InstallsManifest);
    }
Ejemplo n.º 11
0
        public void ListTest()
        {
            var json = "[{\"id\":2,\"Name\":\"Debendra\",\"Email\":\"[email protected]\"," +
                       "\"Dept\":\"IT\"},{\"id\":3,\"Name\":\"Manoj\",\"Email\":\"[email protected]\"," +
                       "\"Dept\":\"Sales\"},{\"id\":6,\"Name\":\"Kumar\",\"Email\":\"[email protected]\",\"Dept\":\"IT\"}]";

            var empList = JsonNet.Deserialize <Employee[]>(json);

            Assert.IsTrue(empList.Length == 3);
            Assert.AreEqual(empList.Last().Dept, "IT");
        }
Ejemplo n.º 12
0
 static Data()
 {
     if (!File.Exists(_settingFilePath))
     {
         SaveFile(JsonNet.Serialize(Setting.GetDefaultSetting()));
         _setting = Setting.GetDefaultSetting();
     }
     else
     {
         _setting = JsonNet.Deserialize <Setting>(GetFileData());
     }
 }
Ejemplo n.º 13
0
        private void Button1_Click(object sender, EventArgs e)
        {
            if ((email.Text == "") && (password.Text == ""))
            {
                MessageBox.Show("Informe os dados necessarios", "Alerta!", MessageBoxButtons.OK);
            }
            else
            {
                Usuario usuario = new Usuario();
                usuario.email    = email.Text;
                usuario.password = password.Text;

                try
                {
                    string         URL     = "http://10.42.0.1:8080/EasyListRest/usuario?email=" + usuario.email + "&password="******"GET";
                    request.Accept = "application/json";
                    WebResponse    webResponse   = request.GetResponse();
                    HttpStatusCode response_code = ((HttpWebResponse)webResponse).StatusCode;

                    Stream       webStream      = webResponse.GetResponseStream();
                    StreamReader responseReader = new StreamReader(webStream);
                    string       response       = responseReader.ReadToEnd();

                    if (response_code == HttpStatusCode.OK)
                    {
                        if (!String.IsNullOrEmpty(response))
                        {
                            //MessageBox.Show("Os valores são" + response, "Alerta do sistema", MessageBoxButtons.OK);
                            LocalStorage localStorage = new LocalStorage();
                            Login        login        = JsonNet.Deserialize <Login>(response);
                            //   MessageBox.Show("Os valores são" + login.id, "Alerta do sistema", MessageBoxButtons.OK);
                            Visible = false;
                            F_inicio f_Inicio = new F_inicio();
                            f_Inicio.Show();
                        }
                        else
                        {
                            MessageBox.Show("Valores em branco.", "Alerta do sistema", MessageBoxButtons.OK);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Erro no servidor:" + response, "Alerta do sistema", MessageBoxButtons.OK);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Erro no lado do servidor." + ex, "Alerta do sistema", MessageBoxButtons.OK);
                }
            }
        }
Ejemplo n.º 14
0
        public void TestBug002()
        {
            var bug002 = new Bug002 {
                interval = TimeSpan.FromMinutes(2)
            };

            var json = JsonNet.Serialize(bug002);

            var constructed = JsonNet.Deserialize <Bug002>(json);

            Assert.AreEqual(bug002.interval, constructed.interval);
        }
Ejemplo n.º 15
0
 public T GetPayload <T>()
 {
     if (Payload == null)
     {
         return(default(T));
     }
     if (Payload is T)
     {
         return((T)Payload);
     }
     return(JsonNet.Deserialize <T>(Payload.ToString()));
 }
Ejemplo n.º 16
0
        public string[] decodeFile(string path, string format)
        {
            path = path.Replace("file:", "");

            List <string> returnValues = new List <string>();

            if (!string.IsNullOrEmpty(path))
            {
                if (File.Exists(path))
                {
                    if (format.StartsWith("CSV", StringComparison.Ordinal))
                    {
                        using (var reader = new StreamReader(path))
                            using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                            {
                                csvStandard records = (ryuk.HeartbreakerLogin.csvStandard)csv.GetRecords <csvStandard>();

                                if (format == "CSV1")
                                {
                                    returnValues.Add(records.rowA);
                                }
                                else if (format == "CSV2")
                                {
                                    returnValues.Add(records.rowB);
                                }
                                else if (format == "CSV3")
                                {
                                    returnValues.Add(records.rowC);
                                }
                            }
                    }
                    else if (format == "N-LINE")
                    {
                        foreach (string item in File.ReadAllLines(path))
                        {
                            returnValues.Add(item);
                        }
                    }
                    else if (format == "JSON")
                    {
                        string text = File.ReadAllText(path);

                        foreach (string item in JsonNet.Deserialize <String[]>(text))
                        {
                            returnValues.Add(item);
                        }
                    }
                }
            }

            return(returnValues.ToArray());
        }
        public List <User> JsonToUsersList(string fileName)
        {
            List <User> users = new List <User>();

            using (StreamReader r = new StreamReader(fileName))
            {
                string json = r.ReadToEnd();
                users = JsonNet.Deserialize <List <User> >(json);
            }
            Console.WriteLine(users[0].FullName + " " + users[0].Country);
            Console.WriteLine("Users Count: " + users.Count);
            return(users);
        }
Ejemplo n.º 18
0
        public async void getMonster()
        {
            using (HttpClient http = new HttpClient())
            {
                var jsonMonsters = await http.GetAsync("https://www.dnd5eapi.co/api/monsters");

                MonsterList monsterList = JsonNet.Deserialize <MonsterList>(jsonMonsters.Content.ToString());
                string      randomMonsterApiEndpoint = monsterList.getMonsterApiEndpoint();

                var jsonMonsterDetail = await http.GetAsync("https://www.dnd5eapi.co/api/monsters/" + randomMonsterApiEndpoint);

                Console.WriteLine(jsonMonsterDetail);
            }
        }
Ejemplo n.º 19
0
        public void TestMethod1()
        {
            var json = "{\"list\":[],\"msg\":\"OK\"}";

            var bug1 = new Bug001()
            {
                list = new string[0],
                msg  = "OK"
            };

            var bug2 = JsonNet.Deserialize <Bug001>(json);

            Assert.IsTrue(bug2.list.Length == 0);
            Assert.AreEqual(bug1.msg, bug2.msg);
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            readInfo(URL + "$limit=5");

            var dataSet = JsonNet.Deserialize <Dictionary <string, string>[]> (DATA);



            Console.WriteLine(dataSet[0]);

            /*
             * the first number in seconds
             */
            Thread.Sleep(60 * (Int32)Math.Pow(10, 3));
        }
Ejemplo n.º 21
0
        public static string CreateExceptionMessage(string message, Exception exception)
        {
            string exMessage = $"{exception.GetType()} with {message}:";

            // Some exception messages include raw HTML from the remote endpoint
            var htmlCheck = new Regex("html|doctype", RegexOptions.IgnoreCase);

            if (htmlCheck.IsMatch(exception.Message))
            {
                exMessage += " Check the inner exception for the response from server. ";
            }
            else
            {
                var jsonResponseCode    = new Regex(@"Response Status Code: (?<code>\d+)", RegexOptions.IgnoreCase);
                var jsonResponseContent = new Regex(@"Response Content: (?<json>\{.*\})", RegexOptions.IgnoreCase);

                // if we have a valid json structured error, clean it up and use it
                Match jsonMatch = jsonResponseContent.Match(exception.Message);
                if (jsonMatch.Success)
                {
                    string            json      = jsonMatch.Groups["json"].Value;
                    JiraStandardError errorInfo = null;
                    try
                    {
                        errorInfo = JsonNet.Deserialize <JiraStandardError>(json);
                    }
                    catch (Exception ex)
                    {
                        throw new JiraModuleException($"Issue parsing Json in message [{exception.Message}", ex);
                    }

                    if (errorInfo.errorMessages?.Length > 0)
                    {
                        exMessage += $" Message [{errorInfo.errorMessages[0]}]";
                    }

                    foreach (string key in errorInfo.errors.Keys)
                    {
                        exMessage += $" [{errorInfo.errors[key]}]";
                    }
                }
                else
                {
                    exMessage += $" Message [{exception.Message}]";
                }
            }
            return(exMessage);
        }
Ejemplo n.º 22
0
        public void CamelCaseDeserializationTest()
        {
            var restoredPet = JsonNet.Deserialize <Pet>(originalPetJson, PropertyNameTransforms.TitleToCamelCase);

            Assert.AreEqual(restoredPet.Id, OriginalPet.Id);
            Assert.AreEqual(restoredPet.Name, OriginalPet.Name);
            Assert.AreEqual(restoredPet.Gender, OriginalPet.Gender);
            Assert.AreEqual(restoredPet.Alive, OriginalPet.Alive);
            Assert.AreEqual(restoredPet.Birth.ToString(), OriginalPet.Birth.ToString());
            Assert.AreEqual(restoredPet.DictType["Key1"], OriginalPet.DictType["Key1"]);
            Assert.AreEqual(restoredPet.DictType["Key2"], OriginalPet.DictType["Key2"]);
            Assert.AreEqual(restoredPet.IntArray[0], OriginalPet.IntArray[0]);
            Assert.AreEqual(restoredPet.IntArray[1], OriginalPet.IntArray[1]);
            Assert.AreEqual(restoredPet.Owner.Id, OriginalPet.Owner.Id);
            Assert.AreEqual(restoredPet.Owner.Name, OriginalPet.Owner.Name);
        }
Ejemplo n.º 23
0
        public void DeserializationTest()
        {
            var restoredPet = JsonNet.Deserialize <Pet>(
                string.Join("\n", OriginalPetJsonFormatted));

            Assert.AreEqual(restoredPet.id, OriginalPet.id);
            Assert.AreEqual(restoredPet.name, OriginalPet.name);
            Assert.AreEqual(restoredPet.gender, OriginalPet.gender);
            Assert.AreEqual(restoredPet.alive, OriginalPet.alive);
            Assert.AreEqual(restoredPet.birth.ToString(), OriginalPet.birth.ToString());
            Assert.AreEqual(restoredPet.dictType["Key1"], OriginalPet.dictType["Key1"]);
            Assert.AreEqual(restoredPet.dictType["Key2"], OriginalPet.dictType["Key2"]);
            Assert.AreEqual(restoredPet.intArray[0], OriginalPet.intArray[0]);
            Assert.AreEqual(restoredPet.intArray[1], OriginalPet.intArray[1]);
            Assert.AreEqual(restoredPet.intArray[2], OriginalPet.intArray[2]);
        }
Ejemplo n.º 24
0
        public async Task <Image[]> GetImages()
        {
            try
            {
                HttpResponseMessage response = await this.httpClient.GetAsync(this.picsumUrl);

                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();

                Image[] images = JsonNet.Deserialize <Image[]>(responseBody);

                return(images);
            }
            catch (Exception e)
            {
                return(new Image[0]);
            }
        }
Ejemplo n.º 25
0
    public ConfigurationManifest Process(string filePath)
    {
        if (filePath == null || Path.GetExtension(filePath) != ".json")
        {
            throw new Exception($"Failed to open configuration file at {filePath}");
        }

        var deserialised = JsonNet.Deserialize <ConfigurationManifest>(File.ReadAllText(filePath));

        if (deserialised == null)
        {
            throw new Exception($"Failed to deserialise configuration file at {filePath}");
        }
        else
        {
            deserialised.ManifestPath = filePath;
            return(deserialised);
        }
    }
Ejemplo n.º 26
0
 private void MenuItem_Load(object sender, RoutedEventArgs e)
 {
     handleDialog(new System.Windows.Forms.OpenFileDialog(),
                  path =>
     {
         var read = JsonNet.Deserialize <int[][]>(File.ReadAllText(path));
         forEachCell((row, col, box) =>
         {
             box.Text       = (read[row][col] > 0 ? Convert.ToString(read[row][col], CULTURE) : "");
             box.Foreground = Brushes.Black;
         }
                     );
         if (fillMode == FillMode.Direct)
         {
             currentInput  = getUserInput();
             currentSudoku = CreateSudoku(currentInput);
             ShowResult(currentSudoku, DIRECT_CONCLUSION);
         }
     });
 }
Ejemplo n.º 27
0
        static void Main(string[] args)
        {
            var json = File.ReadAllText("user.json");

            Console.WriteLine(json);

            User usuario = new User()
            {
                Name = "du", Age = 20, Email = "*****@*****.**"
            };


            json    = JsonNet.Serialize(usuario);
            usuario = JsonNet.Deserialize <User>(json);

            // Console.WriteLine(usuario.Name);
            // Console.WriteLine(usuario.Age);
            // Console.WriteLine(usuario.Email);

            File.WriteAllText("user.json", json);
        }
Ejemplo n.º 28
0
        public static void Main(string[] args)
        {
            string input = "{\"status\":404,\"userMessage\":\"ERROR CODE: EBE04005 | SEVERITY: E | SOURCE IDENTIFIER: EBE04 | DESCRIPTION: The User Profile Retrieval Service was unable to process due to an unavailable Data Source: | Additional Info: Prodcucer Detail Not Found In Producer DB For Producer Code: 123456\"}";

            Data data = JsonNet.Deserialize <Data>(input);

            string[] messages = data.userMessage.Split('|');

            Dictionary <string, string> messageDict = new Dictionary <string, string>();

            foreach (string message in messages)
            {
                string[] tmp = message.Split(':');
                messageDict.Add(tmp[0].Trim(), tmp[1].Trim());
            }

            foreach (string key in messageDict.Keys)
            {
                Console.WriteLine($"Key: {key} Value: {messageDict[key]}");
            }
        }
Ejemplo n.º 29
0
        // Issue 9
        public void JsonNetIgnoreAttributeTest()
        {
            var test_object = new TestClass005
            {
                Id          = 81,
                Name        = "Tester 005",
                SecurityKey = "Top Secret",
                NickName    = "Superman"
            };

            var json_text = JsonNet.Serialize(test_object);

            Assert.AreEqual(json_text, "{\"Id\":81,\"Name\":\"Tester 005\",\"NickName\":\"Superman\"}");

            json_text = "{\"Id\":81,\"Name\":\"Tester 005\",\"SecurityKey\":\"Top Secret\",\"NickName\":\"Superman\"}";

            var test_object2 = JsonNet.Deserialize <TestClass005>(json_text);

            Assert.AreEqual(test_object.Id, test_object2.Id);
            Assert.AreEqual(test_object.Name, test_object2.Name);
            Assert.AreNotEqual(test_object.SecurityKey, test_object2.SecurityKey);
            Assert.AreEqual(test_object.NickName, test_object2.NickName);
        }
Ejemplo n.º 30
0
        private void LoadIngredient()
        {
            ingredientStr = Intent.GetStringExtra(Constants.IngredientString);
            if (ingredientStr != null)
            {
                original.Text = ingredientStr;
            }

            string stringExtra = Intent.GetStringExtra(Constants.Ingredient);

            if (stringExtra != null)
            {
                ingredient = JsonNet.Deserialize <Ingredient>(stringExtra);
                AssighnFormFields();
            }
            else
            {
                ingredient = new Ingredient();
                if (ingredient.TryToParseFromString(ingredientStr))
                {
                    AssighnFormFields();
                }
            }
        }