Ejemplo n.º 1
0
            public CharacterCache()
            {
                lastUpdatedPlayer=DateTime.Today;
                          lastPreformedNonCombatAction=DateTime.Today;
                          bIsIncapacitated=false;
                          bIsRooted=false;
                          bIsInTown=false;
                          dcurrentHealthPct=0d;
                          dCurrentEnergy=0d;
                          dCurrentEnergyPct=0d;
                          dDiscipline=0d;
                          dDisciplinePct=0d;
                          //EnergyRegenerationRate=0;
                          bWaitingForReserveEnergy=false;
                          iMyDynamicID=0;
                          iMyLevel=1;
                          iMyParagonLevel=0;
                          iSceneID=-1;
                          iCurrentWorldID=-1;
                          BackPack=new Backpack();
                          PetData=new Pets();
                          PickupRadius=1;

                            LastCachedTarget=Funky.FakeCacheObject;
                          fCharacterRadius=0f;
                          //iCurrentGameDifficulty=GameDifficulty.Invalid;
                          IsRunningOOCBehavior=false;
                          ShouldBackTrack=false;
                          BackTrackVector=Vector3.Zero;
            }
Ejemplo n.º 2
0
 public CharacterCache()
 {
     lastUpdatedPlayer = DateTime.Today;
     lastPreformedNonCombatAction = DateTime.Today;
     bIsIncapacitated = false;
     bIsRooted = false;
     bIsInTown = false;
     bIsInBossEncounter = false;
     dcurrentHealthPct = 0d;
     dCurrentEnergy = 0d;
     dCurrentEnergyPct = 0d;
     dDiscipline = 0d;
     dDisciplinePct = 0d;
     iMyDynamicID = 0;
     iMyLevel = 1;
     iSceneID = -1;
     iCurrentWorldID = -1;
     iCurrentLevelID = -1;
     BackPack = new Backpack();
     PetData = new Pets();
     PickupRadius = 1;
     coinage = 0;
     fCharacterRadius = 0f;
     CurrentExp = 0;
 }
Ejemplo n.º 3
0
 public Environment()
 {
     HeroPets = new Pets();
     bAnyLootableItemsNearby = false;
     iElitesWithinRange = new[] { 0, 0, 0, 0, 0, 0, 0, 0 };
     iAnythingWithinRange = new[] { 0, 0, 0, 0, 0, 0, 0, 0 };
     iNonRendedTargets_6 = 0;
     bAnyBossesInRange = false;
     bAnyChampionsPresent = false;
     bAnyTreasureGoblinsPresent = false;
     bAnyNonWWIgnoreMobsInRange = false;
     SurroundingUnits = 0;
 }
Ejemplo n.º 4
0
        public async Task <IActionResult> PutPets(int id, Pets pets)
        {
            // If the ID in the URL does not match the ID in the supplied request body, return a bad request
            if (id != pets.Id)
            {
                return(BadRequest());
            }

            // Tell the database to consider everything in pets to be _updated_ values. When
            // the save happens the database will _replace_ the values in the database with the ones from pets
            _context.Entry(pets).State = EntityState.Modified;

            try
            {
                // Try to save these changes.
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                // Ooops, looks like there was an error, so check to see if the record we were
                // updating no longer exists.
                if (!PetsExists(id))
                {
                    // If the record we tried to update was already deleted by someone else,
                    // return a `404` not found
                    return(NotFound());
                }
                else
                {
                    // Otherwise throw the error back, which will cause the request to fail
                    // and generate an error to the client.
                    throw;
                }
            }

            // return NoContent to indicate the update was done. Alternatively you can use the
            // following to send back a copy of the updated data.
            //
            // return Ok(pets)
            //
            return(NoContent());
        }
Ejemplo n.º 5
0
        public void RemoveChild(Child child)
        {
            foreach (var interest in ChildInterests.ToList())
            {
                if (child.Id == interest.ChildId)
                {
                    ChildInterests.Remove(interest);
                }
            }

            foreach (var pet in child.Pets.ToList())
            {
                Pets.Remove(pet);
            }

            Children.Remove(child);
            WriteChildrenToFile();
            WriteChildInterestToFile();
            WritePetsToFile();
        }
Ejemplo n.º 6
0
        // [Route("UpPets/{id}")]
        // [ProducesResponseType((int)HttpStatusCode.OK)]
        // [ProducesResponseType((int)HttpStatusCode.BadRequest)]
        public async Task <IActionResult> UpPets([Bind("Name")] Pets cancelOrder, int?id)
        {
            await Task.Delay(100);

            _logger.LogInformation($"Session:{ HttpContext.Session.Id}--fzf003:{HttpContext.Session.GetString("fzf003")}");

            if (!ModelState.IsValid)
            {
                _logger.LogInformation($"Success:{!ModelState.IsValid}");

                return(this.NotFound(new { Error = "出错了,不是你想的那个样子!" }));
            }
            else
            {
                _logger.LogInformation($"id:{id}");
                //throw new Exception("my error!!!");
            }

            return(this.Ok(cancelOrder));
        }
Ejemplo n.º 7
0
 public Schema()
     : base()
 {
     InstanceType = typeof(__RadioPag__);
     ClassName    = "RadioPage";
     Properties.ClearExposed();
     Html = Add <__TString__>("Html");
     Html.DefaultValue = "/KitchenSink/RadioPage.html";
     Html.SetCustomAccessors((_p_) => { return(((__RadioPag__)_p_).__bf__Html__); }, (_p_, _v_) => { ((__RadioPag__)_p_).__bf__Html__ = (System.String)_v_; }, false);
     Pets = Add <__TArray__>("Pets");
     Pets.SetCustomGetElementType((arr) => { return(__RaPetsElem__.DefaultTemplate); });
     Pets.SetCustomAccessors((_p_) => { return(((__RadioPag__)_p_).__bf__Pets__); }, (_p_, _v_) => { ((__RadioPag__)_p_).__bf__Pets__ = (__Arr__)_v_; }, false);
     SelectedPet = Add <__TString__>("SelectedPet$");
     SelectedPet.DefaultValue = "";
     SelectedPet.Editable     = true;
     SelectedPet.SetCustomAccessors((_p_) => { return(((__RadioPag__)_p_).__bf__SelectedPet__); }, (_p_, _v_) => { ((__RadioPag__)_p_).__bf__SelectedPet__ = (System.String)_v_; }, false);
     PetReaction = Add <__TString__>("PetReaction", bind: "CalculatedPetReaction");
     PetReaction.DefaultValue = "";
     PetReaction.SetCustomAccessors((_p_) => { return(((__RadioPag__)_p_).__bf__PetReaction__); }, (_p_, _v_) => { ((__RadioPag__)_p_).__bf__PetReaction__ = (System.String)_v_; }, false);
 }
        public IHttpActionResult PostPets(Pets pets)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            int   id   = pets.UserId;
            Users user = db.Users.Find(id);

            if (user != null)
            {
                user.PetsCount += 1;
            }
            db.Entry(user).State = EntityState.Modified;
            db.Pets.Add(pets);
            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = pets.PetsId }, pets));
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Deletes the user from the database.
        /// </summary>
        /// <param name="pet"></param>
        public void DeletePet(Pets pet)
        {
            try
            {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    conn.Open();
                    SqlCommand cmd = new SqlCommand("DELETE FROM Pets WHERE id = @id;", conn);
                    cmd.Parameters.AddWithValue("@id", pet.Id);

                    cmd.ExecuteNonQuery();

                    return;
                }
            }
            catch (SqlException ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 10
0
        public static async Task <bool> Execute()
        {
            if (await Chocobo.HandleChocobo())
            {
                return(true);
            }

            if (Core.Me.IsCasting)
            {
                return(true);
            }

            await Casting.CheckForSuccessfulCast();

            SpellQueueLogic.SpellQueue.Clear();
            Globals.InParty       = PartyManager.IsInParty || Globals.InGcInstance;
            Globals.PartyInCombat = Globals.InParty && Utilities.Combat.Enemies.Any(r => r.TaggerType == 2);

            return(await Pets.Summon());
        }
Ejemplo n.º 11
0
        public IActionResult Pets(Pets pets)
        {
            if (ModelState.IsValid)
            {
                var petInInstExist = _context.PatientInstitution.Where(pe => pe.IdInst == pets.SelectedInst && pe.IdPatient == pets.SelectedPet).SingleOrDefault();
                if (petInInstExist == null)
                {
                    PatientInstitution petInInst = new PatientInstitution
                    {
                        IdPatient = pets.SelectedPet,
                        IdInst    = pets.SelectedInst
                    };

                    _context.Add(petInInst);
                    _context.SaveChanges();
                }
            }

            return(RedirectToAction("Pets"));
        }
 public Schema()
     : base()
 {
     InstanceType = typeof(__Datagrid__);
     ClassName    = "DatagridPage";
     Properties.ClearExposed();
     Html = Add <__TString__>("Html");
     Html.DefaultValue = "/KitchenSink/DatagridPage.html";
     Html.SetCustomAccessors((_p_) => { return(((__Datagrid__)_p_).__bf__Html__); }, (_p_, _v_) => { ((__Datagrid__)_p_).__bf__Html__ = (System.String)_v_; }, false);
     Pets = Add <__TArray__>("Pets");
     Pets.SetCustomGetElementType((arr) => { return(__Datagrid1__.DefaultTemplate); });
     Pets.SetCustomAccessors((_p_) => { return(((__Datagrid__)_p_).__bf__Pets__); }, (_p_, _v_) => { ((__Datagrid__)_p_).__bf__Pets__ = (__Arr__)_v_; }, false);
     AddPet = Add <__TLong__>("AddPet$");
     AddPet.DefaultValue = 0L;
     AddPet.Editable     = true;
     AddPet.SetCustomAccessors((_p_) => { return(((__Datagrid__)_p_).__bf__AddPet__); }, (_p_, _v_) => { ((__Datagrid__)_p_).__bf__AddPet__ = (System.Int64)_v_; }, false);
     AddPet.AddHandler((Json pup, Property <Int64> prop, Int64 value) => { return(new Input.AddPet()
         {
             App = (DatagridPage)pup, Template = (TLong)prop, Value = value
         }); }, (Json pup, Starcounter.Input <Int64> input) => { ((DatagridPage)pup).Handle((Input.AddPet)input); });
 }
Ejemplo n.º 13
0
        public IActionResult Create([Bind("Name, Email, Phone, Password, AnimalType, AnimalSubType, AnimalName")] CreateOwnerModel customer)
        {
            CreateOwnerModel cm = new CreateOwnerModel();

            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }
            try
            {
                Owners o = new Owners();
                o.Name     = customer.Name;
                o.Password = customer.Password;
                o.Email    = customer.Email;
                o.Phone    = customer.Phone;

                using (var context = new VetSystemContext())
                {
                    context.Owners.Add(o);
                    context.SaveChanges();

                    Pets pet = new Pets
                    {
                        Name            = customer.AnimalName,
                        OwnerId         = o.Id,
                        AnimalSubTypeId = int.Parse(customer.AnimalSubType),
                        AnimalTypeId    = int.Parse(customer.AnimalType)
                    };

                    context.Pets.Add(pet);
                    context.SaveChanges();
                }
            }
            catch (Exception e)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }
            return(View(cm));
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            Pets pet1 = new Pets("dog", "Shadow", "Jose", 42.6);

            Console.WriteLine("Name: " + pet1.name);
            Console.WriteLine("Weight: " + pet1.weight);
            Console.WriteLine(pet1.getTag());

            Dogs dog1 = new Dog("Daisy", "Kent", 23.4);

            Console.WriteLine("Name: " + dog1.name);
            Console.WriteLine("Weight: " + dog1.weight);
            Console.WriteLine(dog1.getTag());
            Console.WriteLine(dog1.bark(4));

            Cats cat1 = new Cat("Simba", "Maria", 5.2);

            Console.WriteLine("Name: " + cat1.name);
            Console.WriteLine("Weight: " + cat1.weight);
            Console.WriteLine(cat1.getTag());
            Console.WriteLine(cat1.meow(3));
        }
Ejemplo n.º 15
0
        public ActionResult Alterar(Pets objPet)
        {
            if (ModelState.IsValid)
            {
                //buscar o objeto no banco para poder alterar
                Pets petDoBanco = Banco.Pets.First(p => p.PetId == objPet.PetId);

                //colocando os valos que chegou no objeto novo no objeto que esta no banco

                petDoBanco.NomedoPet = objPet.NomedoPet;
                petDoBanco.Raca      = objPet.Raca;
                petDoBanco.Idade     = objPet.Idade;
                petDoBanco.Sexo      = objPet.Sexo;
                petDoBanco.NomeDono  = objPet.NomeDono;
                petDoBanco.Endereco  = objPet.Endereco;

                return(RedirectToAction("Listar"));
            }

            TempData["Mensagem"] = "Preencher todos os campos obrigatirio.";
            return(View(objPet));
        }
Ejemplo n.º 16
0
        public void Can_deserialise_an_entity_containing_a_polymorphic_property_serialized_by_datacontractjsonserializer()
        {
            Func <string, Type> typeFinder = value => {
                var regex    = new Regex(@"^(?<type>[^:]+):#(?<namespace>.*)$");
                var match    = regex.Match(value);
                var typeName = string.Format("{0}.{1}", match.Groups["namespace"].Value, match.Groups["type"].Value.Replace(".", "+"));
                return(AssemblyUtils.FindType(typeName));
            };

            try {
                var originalPets = new Pets {
                    Cat = new Cat {
                        Name = "Tigger"
                    }, Dog = new Dog {
                        Name = "Fido"
                    }
                };

                var dataContractJsonSerializer = new DataContractJsonSerializer(typeof(Pets), new[] { typeof(Dog), typeof(Cat) }, int.MaxValue, true, null, true);
                JsConfig.TypeFinder = typeFinder;
                Pets deserializedPets = null;
                using (var stream = new MemoryStream()) {
                    dataContractJsonSerializer.WriteObject(stream, originalPets);
                    stream.Position = 0;
                    using (var reader = new StreamReader(stream)) {
                        var json = reader.ReadToEnd();
                        deserializedPets = JsonSerializer.DeserializeFromString <Pets>(json);
                    }
                }

                Assert.That(deserializedPets.Cat.GetType(), Is.EqualTo(originalPets.Cat.GetType()));
                Assert.That(deserializedPets.Dog.GetType(), Is.EqualTo(originalPets.Dog.GetType()));

                Assert.That(deserializedPets.Cat.Name, Is.EqualTo(originalPets.Cat.Name));
                Assert.That(deserializedPets.Dog.Name, Is.EqualTo(originalPets.Dog.Name));
            } finally {
                JsConfig.Reset();
            }
        }
Ejemplo n.º 17
0
        public void Insert(Pets pets)
        {
            try
            {
                MySqlCommand comando = new MySqlCommand();
                comando.CommandType = CommandType.Text;
                comando.CommandText = "Insert into Pets(nome,CodMorador,Especie,BA_Cod) " +
                                      "values(@nome,@CodMorador,@Especie,@BA_Cod)";

                comando.Parameters.AddWithValue("@nome", pets.Nome);
                comando.Parameters.AddWithValue("@CodMorador", pets.Moradores.CodMorador);
                comando.Parameters.AddWithValue("@Especie", pets.Especie);
                comando.Parameters.AddWithValue("@Ba_Cod", pets.BA.Ba_Cod);


                ConexaoBanco.CRUD(comando);
            }
            catch (Exception ex)
            {
                throw new Exception("Não foi possível se conectar" + ex.Message);
            }
        }
Ejemplo n.º 18
0
        protected override void ProcessAI()
        {
            if (Dead)
            {
                return;
            }

            //Search for target
            if (Envir.Time < SearchTime)
            {
                return;
            }
            SearchTime = Envir.Time + SearchDelay;

            //Cant agro when shocked
            if (Envir.Time < ShockTime)
            {
                Target = null;
                return;
            }
            //update targets all the time ?
            AgroAllMobsInRange();

            //Refresh Minions
            for (int i = Pets.Count - 1; i >= 0; i--)
            {
                if (Pets[i].Dead || Pets[i].Node == null)
                {
                    Pets[i].Despawn();
                    Pets.RemoveAt(i);
                }
            }

            //Keep Minions Updated
            if (Pets.Count < MaxMinions)
            {
                SpawnMinion();
            }
        }
Ejemplo n.º 19
0
        public string AddPet(Pets pet)
        {
            var str = "could not add pet";

            try
            {
                using (SqlConnection sqlConnection = new SqlConnection())
                {
                    //sqlConnection.ConnectionString = _configuration.GetConnectionString("DefaultConnection");
                    sqlConnection.ConnectionString = ConStr;
                    sqlConnection.Open();
                    using (var cmd = new SqlCommand("add_pet", sqlConnection))
                    {
                        cmd.CommandType = System.Data.CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@userid", pet.Userid);
                        cmd.Parameters.AddWithValue("@name", pet.Name);
                        cmd.Parameters.AddWithValue("@type", pet.Type);
                        cmd.Parameters.AddWithValue("@size", pet.Size);
                        cmd.Parameters.AddWithValue("@gender", pet.Gender);
                        cmd.Parameters.AddWithValue("@breed", pet.Breed);
                        cmd.Parameters.AddWithValue("@allergies", pet.Allergies);
                        cmd.Parameters.AddWithValue("@age", pet.Age);
                        cmd.Parameters.AddWithValue("@moreinfo", pet.Moreinfo);

                        var _output = cmd.Parameters.Add("@ret", SqlDbType.VarChar, 100);
                        _output.Direction = ParameterDirection.Output;
                        cmd.ExecuteScalar();
                        str = _output.Value.ToString();
                    }
                }
            }
            catch (Exception e)
            {
                str = e.Message;
                throw e;
            }
            return(str);
        }
    public static void Test()
    {
        string      baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        ServiceHost host        = new ServiceHost(typeof(Service), new Uri(baseAddress));

        host.AddServiceEndpoint(typeof(ITest), GetBinding(), "");
        host.Open();
        Console.WriteLine("Host opened");
        ChannelFactory <ITest> factory = new ChannelFactory <ITest>(GetBinding(), new EndpointAddress(baseAddress));
        ITest proxy = factory.CreateChannel();
        Pets  pets  = new Pets {
            Cats = new string[] { "Max" }, Dogs = new string[] { "Fido", "Duke" }
        };

        proxy.SavePets(new SavePetsRequest {
            Pets = pets
        });
        ((IClientChannel)proxy).Close();
        factory.Close();
        WebClient c = new WebClient();

        c.Headers[HttpRequestHeader.ContentType] = "text/xml";
        c.Headers["SOAPAction"] = "urn:ITest/SavePets";
        string reqBody = @"<s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"">
                    <s:Body>
                        <Pets>
                            <Dog>Fido</Dog>
                            <Dog>Duke</Dog>
                            <Cat>Max</Cat>
                        </Pets>
                    </s:Body>
                </s:Envelope>";

        Console.WriteLine(c.UploadString(baseAddress, reqBody));
        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            var player = new Hockey();

            player.isReady = false;
            player.name    = "Jamie";
            player.ReadyUp(player.name);
            player.Laps(34);

            var topChef = new Chef();

            topChef.name      = "Bobby Flay";
            topChef.isEating  = true;
            topChef._location = "Husk";
            topChef.isHungry(topChef.name);
            topChef.Restaurant(topChef.name, topChef._location);

            var coder = new Code(50);

            coder.isCoding   = false;
            coder.name       = "Will Smith";
            coder._codeHours = 45;
            coder.Coding(coder.name);
            coder.codeCount(coder.name, coder._codeHours);

            var fluffy = new Pets();

            Console.WriteLine("What is your new pets name?");
            fluffy.name = Console.ReadLine();
            Console.WriteLine($"Hi, {fluffy.name}. Is {fluffy.name} a Cat or a Dog.");
            fluffy.type = Console.ReadLine();
            fluffy.PetType(fluffy.name, fluffy.type);
            Console.WriteLine($"What does {fluffy.name} want to say? Type out the message");
            fluffy.speaks = Console.ReadLine();
            fluffy.PetSpeak(fluffy.name, fluffy.type, fluffy.speaks);

            Console.ReadLine();
        }
Ejemplo n.º 22
0
 public override void Process()
 {
     MaxMinions = PetLevel + 1;
     if (!Dead && Summoned)
     {
         bool selfDestruct = false;
         if (Master != null)
         {
             if (FindObject(Master.ObjectID, 15) == null)
             {
                 selfDestruct = true;
             }
             if (Summoned && Envir.Time > AliveTime)
             {
                 selfDestruct = true;
             }
             if (selfDestruct && Master != null)
             {
                 //Kill Minions
                 for (int i = Pets.Count - 1; i >= 0; i--)
                 {
                     if (!Pets[i].Dead && Pets[i].Node != null)
                     {
                         Pets[i].Die();
                         Pets.RemoveAt(i);
                     }
                 }
                 Die();
                 DieTime = Envir.Time + 3000;
             }
         }
         base.Process();
     }
     else if (Envir.Time >= DieTime)
     {
         Despawn();
     }
 }
Ejemplo n.º 23
0
        public ActionResult AddMainFoto(HttpPostedFileBase f, string kittenName)
        {
            _logger.Info("Add main photo for kittenName=" + kittenName);

            var copy = new MemoryStream();

            f.InputStream.CopyTo(copy);

            string path       = SaveMainPicture(kittenName, f.InputStream);
            string redirectTo = "AdminChangeKittens";

            if (!String.IsNullOrEmpty(path))
            {
                Pets kitten         = _kittensRepository.GetKittenByName(kittenName);
                var  oldMainPicture = _picturesRepository.GetCollection().FirstOrDefault(i => i.IsMainPicture && i.Pet.ID == kitten.ID);

                if (oldMainPicture != null)
                {
                    _picturesRepository.Delete(oldMainPicture.ID);
                }

                _picturesRepository.Insert(new Pictures()
                {
                    Image = path, IsMainPicture = true, Pet = kitten, PetID = kitten.ID
                });
                _picturesRepository.Save();

                redirectTo = kitten.IsParent ? "AdminChangeParents" : "AdminChangeKittens";

                _kittensRepository.Update(kitten);
                _kittensRepository.Save();

                //Save main photo for kittens main page.
                AddPhoto(copy, kittenName);
            }

            return(RedirectToAction(redirectTo));
        }
Ejemplo n.º 24
0
        async Task ExecuteLoadPetsCommand()
        {
            IsBusy = true;

            try
            {
                Pets.Clear();
                var pets = await DataStore.GetPetsAsync(true);

                foreach (var pet in pets)
                {
                    Pets.Add(pet);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
Ejemplo n.º 25
0
        public void Update(Pets pets)
        {
            try
            {
                MySqlCommand comando = new MySqlCommand();
                comando.CommandType = CommandType.Text;
                comando.CommandText = "Update Pets set nome=@nome, CodMorador=@CodMorador, Especie=@Especie, " +
                                      "Ba_Cod=@Ba_Cod where CodPet=@CodPet";

                comando.Parameters.AddWithValue("@nome", pets.Nome);
                comando.Parameters.AddWithValue("@CodMorador", pets.Moradores.CodMorador);
                comando.Parameters.AddWithValue("@Especie", pets.Especie);
                comando.Parameters.AddWithValue("@Ba_Cod", pets.BA.Ba_Cod);
                comando.Parameters.AddWithValue("@CodPet", pets.CodPet);


                ConexaoBanco.CRUD(comando);
            }
            catch (Exception ex)
            {
                throw new Exception("Não foi possível se conectar" + ex.Message);
            }
        }
Ejemplo n.º 26
0
        public Pets GetPetById(int id)
        {
            Pets pet = new Pets();

            pet.Id = id;

            try
            {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    conn.Open();
                    SqlCommand cmd = new SqlCommand("SELECT * FROM Pets WHERE id = @id;", conn);
                    cmd.Parameters.AddWithValue("@id", pet.Id);

                    SqlDataReader reader = cmd.ExecuteReader();

                    while (reader.Read())
                    {
                        pet.Id          = Convert.ToInt32(reader["id"]);
                        pet.Name        = Convert.ToString(reader["name"]);
                        pet.Personality = Convert.ToString(reader["personality"]);
                        pet.Photo       = Convert.ToString(reader["photo"]);
                        pet.Type        = Convert.ToString(reader["type"]);
                        pet.UserId      = Convert.ToInt32(reader["userId"]);
                        pet.Weight      = Convert.ToInt32(reader["weight"]);
                        pet.Breed       = Convert.ToString(reader["breed"]);
                        pet.Age         = Convert.ToInt32(reader["age"]);
                    }
                }

                return(pet);
            }
            catch (SqlException ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 27
0
    //Should be moved to Pet class.
    public void LoadPetsFromString(string data)
    {
        string[] lines = data.Split((char)17)[0].Split((char)16);
        foreach (string line in lines)
        {
            if (line.Length > 1)
            {
                Pet      newPet = new Pet();
                string[] info   = line.Split((char)15)[0].Split((char)14);
                newPet.Name        = info[0];
                newPet.Description = info[1];
                newPet.Nickname    = info[2];

                newPet.MinLevel = int.Parse(info[3]);

                newPet.Affinity = info[4];

                newPet.Identifier = info[5];
                string skillString = line.Split((char)15)[1];

                newPet.SetSkills(Extensions.GetSkillsFromString(skillString));
                if (Pets.Find(x => x.Name == info[0]) == null)
                {
                    Pets.Add(newPet);
                }
            }
        }
        if (data.Split((char)17).Length > 1)
        {
            if (data.Split((char)17)[1] == "None")
            {
                return;
            }
            ActivePet = Pets.Find(x => x.Name == data.Split((char)17)[1]);
        }
    }
Ejemplo n.º 28
0
        static void Main(string[] args)
        {
            Dogs dog1 = new Dogs();

            dog1.name  = "Шарик";
            dog1.owner = "Василий Иванович";
            Puppe dog2 = new Puppe();

            dog2.name  = "Бобик";
            dog2.owner = "Афанасий Иванович";
            var dogs = new Pets[] { dog1, dog2 };

            foreach (var dog in dogs)
            {
                dog.Info();
                dog.ShowSkils();
            }
            Rectangle  f1 = new Rectangle(10, 20);
            VRectangle f2 = new VRectangle(10, 20, 5);

            Console.WriteLine(f1.Square());
            Console.WriteLine(f2.Square());
            Console.ReadLine();
        }
Ejemplo n.º 29
0
 public IActionResult AddEditPet([FromBody] Pets model)
 {
     try
     {
         if (model.Id == 0)
         {
             _pet.Add(model);
             _pet.Save();
             return(_jsonResponse.GenerateJsonResult(1, "Owner save Successfully"));
         }
         var edit = _pet.GetSingle(x => x.Id == model.Id);
         edit.owner_id = model.owner_id;
         edit.type     = model.type;
         edit.name     = model.name;
         edit.age      = model.age;
         _pet.Update(edit);
         _pet.Save();
         return(_jsonResponse.GenerateJsonResult(1, "Owner update Successfully"));
     }
     catch (Exception ex)
     {
         return(_jsonResponse.GenerateJsonResult(0, "UnhandledError"));
     }
 }
Ejemplo n.º 30
0
        public ActionResult DeleteOnePet(int?key)
        {
            if (key is null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            pethouseContext db  = new pethouseContext();
            Pets            pet = db.Pets.Find(key);

            try
            {
                if (pet != null)
                {
                    db.Pets.Remove(pet);
                    db.SaveChanges();
                    return(Ok("Pet " + key + " removed"));
                }
                else
                {
                    return(NotFound("Pet " + key + " not found."));
                }
            }catch (Exception ex) { return(BadRequest(ex.ToString())); }
        }
Ejemplo n.º 31
0
        static void Main(string[] args)
        {
            var petsDomain             = new Pets();
            var groupedCatsResponseDto = petsDomain.GetCatsGroupedByOwnerGender(OrderBy.Ascending);

            if (groupedCatsResponseDto.Success)
            {
                foreach (var group in groupedCatsResponseDto.GroupedByOwner)
                {
                    Console.WriteLine(group.Key);
                    Console.WriteLine(new string('-', group.Key.Length));
                    foreach (var map in group)
                    {
                        Console.WriteLine("{0}", map.Pet.name);
                    }
                    Console.WriteLine();
                }
            }
            else
            {
                Console.WriteLine("Unable to get cats. Error message: \"{0}\"", groupedCatsResponseDto.Message);
            }
            Console.ReadLine();
        }
Ejemplo n.º 32
0
        public void Test_Query_Join_Outer_Left_Compound__Right_Clear()
        {
            // Example of a left outer join, using query expression
            // and anonymous types, of People to Pets, and
            // because there are no pets, all 4 people
            // will be without a pet.

            Pets.Clear();

            var owners =
                from person in People
                join pet in Pets
                on new
            {
                person.Id,
                person.Age,
            }
            equals new
            {
                pet.Id,
                Age = pet.Age * 2,     // when owner is twice age of pet
            }
            into pets
            from pet in pets.DefaultIfEmpty()
            select new PetOwner
            {
                Person = person,
                Pet    = pet,
            };

            var countOfOwnersWithoutPets = owners.Count(o => o.Pet is null);
            var petNameOfOwnerJoe        = owners.FirstOrDefault(o => o.Person.Name == "Joe").Pet?.Name;

            Assert.AreEqual(countOfOwnersWithoutPets, 4);
            Assert.IsNull(petNameOfOwnerJoe);
        }
Ejemplo n.º 33
0
        public ActionResult RemoveKitten(int id)
        {
            Pets   kitten     = _kittensRepository.GetByID(id);
            bool   isParent   = kitten.IsParent;
            string redirectTo = isParent ? "AdminChangeParents" : "AdminChangeKittens";

            _logger.Info("Remove kittten id=" + kitten.ID);
            if (!_kittensRepository.IsKittenExists(kitten))
            {
                return(Error("Котенка с таким именем не существует!!!"));
            }

            if (isParent && _kittensRepository.IsKittenExistsWithParent(kitten))
            {
                return(Error("Родитель не может быть удален, так как есть котята с таким родителем!!!"));
            }

            RemoveAllPictures(kitten.Pictures.ToList());

            _kittensRepository.Delete(kitten.ID);
            _kittensRepository.Save();

            return(RedirectToAction(redirectTo));
        }
		public void Can_exclude_specific_TypeInfo()
		{
			JsConfig<ICat>.ExcludeTypeInfo = true;
			var pets = new Pets {
				Cat = new Cat { Name = "Cat" },
				Dog = new Dog { Name = "Dog" },
			};

			Assert.That(pets.ToJson(), Is.EqualTo(
				@"{""Cat"":{""Name"":""Cat""},""Dog"":{""__type"":""ServiceStack.Text.Tests.JsonTests.Dog, ServiceStack.Text.Tests"",""Name"":""Dog""}}"));
		}
		public void Can_deserialise_an_entity_containing_a_polymorphic_property_serialized_by_datacontractjsonserializer()
		{
		    Func<string, Type> typeFinder = value => {
                    var regex = new Regex(@"^(?<type>[^:]+):#(?<namespace>.*)$");
		            var match = regex.Match(value);
		            var typeName = string.Format("{0}.{1}", match.Groups["namespace"].Value, match.Groups["type"].Value.Replace(".", "+"));
		            return Type.GetType(typeName);
		        };

            try {
                var originalPets = new Pets {Cat = new Cat {Name = "Tigger"}, Dog = new Dog {Name = "Fido"}};

		        var dataContractJsonSerializer = new DataContractJsonSerializer(typeof (Pets), new[] {typeof (Dog), typeof (Cat)}, int.MaxValue, true, null, true);
                JsConfig.TypeFinder = typeFinder;
		        Pets deserializedPets = null;
		        using (var stream = new MemoryStream()) {
                    dataContractJsonSerializer.WriteObject(stream, originalPets);
		            stream.Position = 0;
                    using (var reader = new StreamReader(stream)) {
                        var json = reader.ReadToEnd();
		                deserializedPets = JsonSerializer.DeserializeFromString<Pets>(json);
                    }
		        }

			    Assert.That(deserializedPets.Cat.GetType(), Is.EqualTo(originalPets.Cat.GetType()));
			    Assert.That(deserializedPets.Dog.GetType(), Is.EqualTo(originalPets.Dog.GetType()));

			    Assert.That(deserializedPets.Cat.Name, Is.EqualTo(originalPets.Cat.Name));
			    Assert.That(deserializedPets.Dog.Name, Is.EqualTo(originalPets.Dog.Name));
            } finally {
                JsConfig.Reset();
            }
		}
		public void Can_serialize_and_deserialize_an_entity_containing_a_polymorphic_item_with_additional_properties_correctly()
		{
		    Pets pets = new Pets { Cat = new Cat { Name = "Kitty"}, Dog = new Collie { Name = "Lassie", IsLassie = true}};
		    string serializedPets = JsonSerializer.SerializeToString(pets);
		    Pets deserialized = JsonSerializer.DeserializeFromString<Pets>(serializedPets);

		    Assert.That(deserialized.Cat, Is.TypeOf(typeof(Cat)));
		    Assert.That(deserialized.Cat.Name, Is.EqualTo("Kitty"));

		    Assert.That(deserialized.Dog, Is.TypeOf(typeof(Collie)));
		    Assert.That(deserialized.Dog.Name, Is.EqualTo("Lassie"));
		    Assert.That(((Collie)deserialized.Dog).IsLassie, Is.True);
		}