Esempio n. 1
0
        public void WhenColumnNameDiffersFromProperty_InsertQueryShouldUseColumnName()
        {
            // Arrange
            Person2 person = new Person2 {
                Name = "Bob", Age = 40, BirthDate = DateTime.Now
            };
            Dialect             dialect  = new SqlServerDialect();
            ColumnMapCollection mappings = MapRepository.Instance.GetColumns(typeof(Person2));
            var command = new System.Data.SqlClient.SqlCommand();
            var db      = MockRepository.GenerateStub <IDataMapper>();

            db.Expect(d => d.Command).Return(command);
            var mappingHelper = new MappingHelper(db);

            mappingHelper.CreateParameters <Person2>(person, mappings, true);
            string      targetTable = "PersonTable";
            InsertQuery query       = new InsertQuery(dialect, mappings, command, targetTable);

            // Act
            string queryText = query.Generate();

            // Assert
            Assert.IsTrue(queryText.Contains("[PersonName]"), "Query should contain column name");
            Assert.IsTrue(queryText.Contains("[PersonAge]"), "Query should contain column name");
            Assert.IsTrue(queryText.Contains("[BirthDate]"), "Query should contain property name");
            Assert.IsTrue(queryText.Contains("[IsHappy]"), "Query should contain property name");
        }
Esempio n. 2
0
        static void Main(string[] args)
        {
            var Kunde = new Kunde();
            var p     = new Person2();

            Console.WriteLine(Kunde.ID);
        }
    static void Main(string[] args)
    {
        var person = new Person1
        {
            Id      = 12345,
            Name    = "Fred",
            Address = new Address
            {
                Line1 = "Flat 1",
                Line2 = "The Meadows"
            }
        };

        //
        byte[]  arr       = Serialize(person);
        Person2 newPerson = Deserialize(arr);

        /*
         * using (var file = File.Create("person.bin"))
         * {
         *  Serializer.Serialize(file, person);
         * }
         * //
         * Person newPerson;
         * using (var file = File.OpenRead("person.bin"))
         * {
         *  newPerson = Serializer.Deserialize<Person>(file);
         * }
         */
    }
Esempio n. 4
0
        private async void sendJson_Click(object sender, RoutedEventArgs e)
        {
            Person p = new Person()
            {
                FirstName = firstname.Text,
                LastName  = lastname.Text
            };

            using (var client = new HttpClient())
            {
                using (var content = new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
                {
                    var image = await File.ReadAllBytesAsync(filename.Text);

                    var shortImageName = System.IO.Path.GetFileName(filename.Text);
                    content.Add(new StreamContent(new MemoryStream(image)), "postImage", shortImageName);
                    content.Add(new StringContent("4"), "Id");
                    using (var message = await client.PostAsync("http://localhost:5000/img/", content))
                    {
                        var input = await message.Content.ReadAsStringAsync();

                        Person2 answer = JsonSerializer.Deserialize <Person2>(input);
                    }
                }
            }
        }
Esempio n. 5
0
        public async Task TryUpdateModel_SettableCollectionModel_WithPrefix_GetsBound()
        {
            // Arrange
            var operationContext = ModelBindingTestHelper.GetOperationBindingContext(request =>
            {
                request.QueryString = QueryString.Create("prefix.Address[0].Street", "SomeStreet");
            });

            var modelState = new ModelStateDictionary();
            var model      = new Person2();
            // Act
            var result = await TryUpdateModel(model, "prefix", operationContext, modelState);

            // Assert
            Assert.True(result);

            // Model
            Assert.NotNull(model.Address);
            Assert.Equal(1, model.Address.Count);
            Assert.Equal("SomeStreet", model.Address[0].Street);

            // ModelState
            Assert.True(modelState.IsValid);

            Assert.Equal(1, modelState.Keys.Count);
            var key = Assert.Single(modelState.Keys, k => k == "prefix.Address[0].Street");

            Assert.NotNull(modelState[key].Value);
            Assert.Equal("SomeStreet", modelState[key].Value.AttemptedValue);
            Assert.Equal("SomeStreet", modelState[key].Value.RawValue);
            Assert.Empty(modelState[key].Errors);
            Assert.Equal(ModelValidationState.Valid, modelState[key].ValidationState);
        }
Esempio n. 6
0
        public ActionResult Edit(int id, Person2 person)
        {
            // all but password !
            if (ModelState.IsValidField("ID") &&
                ModelState.IsValidField("pType") &&
                ModelState.IsValidField("Timestamp") &&
                ModelState.IsValidField("FirstName") &&
                ModelState.IsValidField("LastName") &&
                ModelState.IsValidField("Email") &&
                ModelState.IsValidField("Username")
                )
            {
                try
                {
                    PersonModel.UpdatePerson(person);
                    return(RedirectToAction("Index"));
                }
                catch (GrException gex)
                {
                    if (person.Username == HttpContext.User.Identity.Name)
                    {
                        ModelState.AddModelError("", Messages.editSameUser);
                    }

                    ModelState.AddModelError("", gex.UserMessage);
                    return(View(person));
                }
            }
            else
            {
                // addinge extra error message here in case JS is deactivated on client.
                ModelState.AddModelError("", Messages.invalidData);
                return(View());
            }
        }
Esempio n. 7
0
        private static Person2 GetPerson2()
        {
            Person2 ilan = new Person2 {
                Age = 26 + 25, Name = "Ilan Zelingher"
            };

            ilan.Surprise = ilan;
            return(new Person2()
            {
                Age = 26,
                Name = "Elad Zelinger",
                Father = ilan,
                Day = Days.Tuesday,
                Surprise = new Person2()
                {
                    Age = 21,
                    Name = "Yosi Attias",
                    Surprise = ilan
                               //new object[]
                               //{
                               //    ilan, ilan, 342, "Hello",
                               //    new int[,]{{1,1},{2,3},{5,8}},
                               //    new int[]{1,1,2,3,5,8},
                               //    Days.Saturday
                               //}
                }
            });
        }
Esempio n. 8
0
        public void PropertyComparerFailsWithObjectNullException()
        {
            //This is the comparison class
            CompareLogic compareLogic = new CompareLogic();

            compareLogic.Config.SkipInvalidIndexers = true;

            //Create a couple objects to compare
            Person2 person1 = new Person2();

            person1.DateCreated = DateTime.Now;
            person1.Name        = "Greg";

            Person2 person2 = new Person2();

            person2.Name        = "John";
            person2.DateCreated = person1.DateCreated;

            //These will be different, write out the differences
            ComparisonResult result = compareLogic.Compare(person1, person2);

            if (!result.AreEqual)
            {
                Console.WriteLine(result.DifferencesString);
            }
        }
Esempio n. 9
0
        public void InsertDataTWithTablenameAttribute()
        {
            var person1 = new Person2
            {
                Firstname = "Marcel",
                Lastname  = "Elz",
                Birthday  = DateTime.MinValue,
            };

            var person2 = new Person2
            {
                Firstname = "Hans",
                Lastname  = "Mustermann",
                Birthday  = new DateTime(2015, 1, 1),
            };

            var person3 = new Person2
            {
                Firstname = "Optimus",
                Lastname  = "Prime",
                Birthday  = new DateTime(1942, 2, 2),
            };

            _sqliteConnector.InsertData(person1);
            _sqliteConnector.InsertData(person2);
            _sqliteConnector.InsertData(person3);

            Assert.IsTrue(VerifyDataInsert());
        }
Esempio n. 10
0
        public void signupchecker()
        {
            List <string> SU = new List <string>();

            SU.Add(Fn.Text);
            SU.Add(Ln.Text);
            SU.Add(Brtd.Text);
            SU.Add(Brtm.Text);
            SU.Add(Brty.Text);
            SU.Add(Email.Text);
            SU.Add(Mobil.Text);
            SU.Add(Telephone.Text);
            SU.Add(Gender.Text);
            SU.Add(Picture.Text);
            SU.Add(Username.Text);
            SU.Add(PassWord.Password);
            if (SED.Text == "خریدار")
            {
                SU.Add("1");
            }
            if (SED.Text == "مدیر")
            {
                SU.Add("0");
            }


            Person2 person2 = new Person2();

            person2.Add_Person(SU);
        }
Esempio n. 11
0
        public void Format_DataContract_CorrectlySerializesNamespaces()
        {
            var input = new Person2
            {
                theAddress = new Address
                {
                    street = "123 Main Street"
                }
            };

            const string expected =
                @"<PersonContract xmlns=""http://schemas.contoso.com"">
	<AddressMember>
		<StreetMember>123 Main Street</StreetMember>
	</AddressMember>
</PersonContract>";

            var writer = new XmlWriter(new DataWriterSettings(new DataContractResolverStrategy())
            {
                PrettyPrint = true
            });
            var actual = writer.Write(input);

            Assert.Equal(expected, actual);
        }
Esempio n. 12
0
        public void To_String_Nested_Deep()
        {
            Person2 person = null;
            IColumn column = sql.Col(() => person.Address.City.Country.Name);

            Assert.Equal("person.Address.City.Country.Name", column.ToString());
        }
Esempio n. 13
0
        public async void TestAsync()
        {
            PersonsService service = new PersonsService();

            Person2 newPerson = new Person2(new User(), "Jonaitis", "199-11-21", "2018-11-21", "test");

            Console.WriteLine("person: " + newPerson);
            try
            {
                var response = await service.AddNewPersonAsync(newPerson);

                if (response != null)
                {
                    Console.WriteLine("Done");
                }
                else
                {
                    Console.WriteLine("Error");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("error: " + ex);
            }

            /*     var response2 = await service.GetPersonsList();
             *
             *    foreach (Person2 person in response2)
             *        Console.WriteLine(person.Name);*/
        }
Esempio n. 14
0
        public void To_String()
        {
            Person2 person = null;
            IAlias  alias  = sql.Alias(() => person);

            Assert.Equal("Person2 AS person", alias.ToString());
        }
Esempio n. 15
0
 private static void FinalizerMethodExample()
 {
     for (long i = 0; i < 1500; i++)
     {
         Person2 p = new Person2();
         System.Threading.Thread.Sleep(3);
     }
 }
Esempio n. 16
0
 static void ChangePerson(Person2 p) //ref передаст ссылку и тогда нижная часть кода сработает тоже
 {
     p.name = "Alice";               // Сменит значение
     p      = new Person2 {
         name = "bill", age = 17
     };                                                      //Создастся новая копия
     Console.WriteLine("Name: {0} Age: {1}", p.name, p.age); //Выведет значения новой локальной копии
 }
        /// <summary>
        /// Run the application.
        /// </summary>
        public override BoolMessageItem Execute()
        {
            Console.WriteLine("====================================================");
            Console.WriteLine("Entity ");

            // Example 1 : Using Entity base class.
            IEntity entity = new Person()
            {
                Name = "kishore"
            };

            Console.WriteLine("Id, Persistant and Audit fields.");
            Console.WriteLine("These fields are set by EntityService if using CommonLibrary Entity-Model Services.");
            Console.WriteLine("Id            ", entity.Id);
            Console.WriteLine("IsPersistant  ", entity.IsPersistant());
            Console.WriteLine("CreateDate    ", entity.CreateDate);
            Console.WriteLine("CreateUser    ", entity.CreateUser);
            Console.WriteLine("UpdateDate    ", entity.UpdateDate);
            Console.WriteLine("UpdateUser    ", entity.UpdateUser);
            Console.WriteLine("UpdateComment ", entity.UpdateComment);

            // Example 2 : Using Entity<T> generic base class to get the parameterless CRUD methods.
            // 1st initialize the repositories.
            EntityRegistration.Register <Person2>(new RepositoryInMemory <Person2>("Id"), false);
            var p2 = new Person2()
            {
                Name = "kishore"
            };

            p2.Create();
            p2.Name = "updated";
            p2.Update();
            p2.GetAll();
            p2.Save();
            p2.Delete();

            // Example 3 : Implement IEntityVersionable to get versioning on the entities.
            // Wrap the real repository w/ the RepositoryVersionable decorator to get versioning behaviour.
            EntityRegistration.Register <Person3>(new RepositoryVersioned <Person3>(new RepositoryInMemory <Person3>("Id,Version,VersionRefId")), false);
            var p3 = new Person3();

            p3.Create();
            p3.Name = "updated";
            p3.Update();
            p3.GetAll();

            var p4 = new Person4();

            p4.Name         = "kishore";
            p4.Phone        = "111-111-1111";
            p4.RegisterDate = DateTime.Today;
            p4.About        = "artist";
            p4.Age          = 30;
            p4.Email        = "*****@*****.**";
            bool isValid = p4.IsValid;

            return(BoolMessageItem.True);
        }
Esempio n. 18
0
 public void Setup()
 {
     _personNormal = new Person1 {
         Age = 5, FirstName = "abc", Reference1 = new Person1(), Reference2 = new Person1()
     };
     _personSealed = new Person2 {
         Age = 5, FirstName = "abc", Reference1 = new Person2(), Reference2 = new Person2()
     };
 }
Esempio n. 19
0
        public void Expression()
        {
            Person2 person = null;
            IAlias  alias  = sql.Alias(() => person);

            QueryResult result = engine.Compile(alias);

            Assert.Equal("\"dbo\".\"Person\"", result.Sql);
        }
Esempio n. 20
0
        public void Expression_Column_Nested_Deep()
        {
            Person2 person = null;
            IColumn column = sql.Col(() => person.Address.City.Country.Name);

            QueryResult result = engine.Compile(column);

            Assert.Equal("\"person\".\"AddressCityCountryName\"", result.Sql);
        }
Esempio n. 21
0
 private void OnTriggerEnter2D(Collider2D other)
 {
     if (other.CompareTag("Person"))
     {
         Person2 p = other.transform.GetComponent <Person2>();
         p.Scare(damage);
         //	Debug.Log ("Scaring for "+damage+" damage.");
     }
 }
Esempio n. 22
0
        public void From_Expression()
        {
            Person2 person = null;
            IFrom   from   = sql.From(() => person);

            QueryResult result = engine.Compile(from);

            Assert.Equal("FROM \"dbo\".\"Person\" AS \"person\"", result.Sql);
        }
Esempio n. 23
0
        public void Sealed()
        {
            _ceras.Serialize(_personSealed, ref _buffer);

            Person2 clone  = null;
            int     offset = 0;

            _ceras.Deserialize(ref clone, _buffer, ref offset);
        }
Esempio n. 24
0
        public void Join_Expression()
        {
            Person2 person = null;
            IQuery  query  = sql.Query.Join(() => person);

            QueryResult result = engine.Compile(query);

            Assert.Equal("INNER JOIN \"dbo\".\"Person\" AS \"person\"", result.Sql);
        }
Esempio n. 25
0
        static void Main(string[] args)
        {
            foreach (Planet p in SolarSystem.PlanetsByDistanceFromSun)
            {
                Console.WriteLine("Planet = {0}", p);
            }

            SerializeToJSON();
            Person2 p2 = DeserializeJSONToObject("{\"name\": \"Bob\", \"age\": 19}");

            Console.WriteLine("name = {0}, age = {1}", p2.name, p2.age);

            //var graph = BuildHelloWorldGraph.BuildGraph();
            //string sourceFile = BuildHelloWorldGraph.GenerateCSharpCode(graph);
            //bool success = BuildHelloWorldGraph.CompileCSharpCode(sourceFile, @".\HelloWorld.exe");

            //TryFlags();

            //ch03();
            //optional(lastname: "Corbs", age: 40);

            //decimal total = 1234.56M;
            //Console.WriteLine(String.Format("{0:C}", total));
            //Console.WriteLine(total.ToString("c"));

            //Person alice = new Employee();
            //Person brett = new Manager();
            //Employee bob = new Person();
            //Manager cindy = new Employee();
            //Manager dan = (Manager)(new Employee());

            //Console.WriteLine(Convert.ChangeType(3.14F, TypeCode.Int32));

            //BitConverter.ToInt16()
            //Byte[] bytes = BitConverter.GetBytes(40);

            //Console.WriteLine(string.Join(" ", new List<string> { "James", "Ben", "Lockie" }));

            //Console.WriteLine(DateTime.Now.ToString("D"));
            //Console.WriteLine(DateTime.Now.ToString("d"));
            //Console.WriteLine(DateTime.Now.ToShortDateString());

            //Console.WriteLine(Calc.Add(50, 50));
            //Console.WriteLine(Calc.ShowNote("Hi"));
            //BackgroundWorker worker = new BackgroundWorker();
            //Monitor mon = new Monitor();
            //int value = 5, value2 = 5;
            //Console.Write(Interlocked.Add(ref value, value2));

            //GetRefAssemblies();
            //string hello = "hello world";
            //GetType(hello);

            Calc.TestChecked();

            Console.ReadKey();
        }
Esempio n. 26
0
        private static void SerializeDeserializeBinary()
        {
            object person = GetSimpleTypeInstance();

            IPerson structure = new Person2()
            {
                Age = 25, Surprise = Days.Monday
            };

            person = new PersonHolder()
            {
                A = structure, B = structure, C = structure
            };

            structure.IncreaseAge();

            //var stateMemberProvider = new BinaryStateMemberProvider(_stateMemberProvider);
            var stateMemberProvider = new BinaryStateMemberProvider(new PropertyStateMemberProvider());

            //var writeClimber = new SlowGraphClimber<BinaryWriterProcessor>(stateMemberProvider);
            //var readClimber = new SlowGraphClimber<BinaryReaderProcessor>(stateMemberProvider);

            var stream = new MemoryStream();
            var binaryWriterProcessor = new BinaryWriterProcessor(new LoggingWriter(new CompressingWriter(new BinaryWriterAdapter(new BinaryWriter(stream))), Console.Out));

            var writerGraphClimber = DefaultGraphClimber <BinaryWriterProcessor> .Create(stateMemberProvider);

            //ClimbDelegate<StrongBox<object>> climb2 =
            //    store2.GetClimb<StrongBox<object>>(typeof(StrongBox<object>));

            //climb2(binaryWriterProcessor,
            //    new StrongBox<object>(person));

            writerGraphClimber.Climb(new StrongBox <object>(person), binaryWriterProcessor);

            //writeClimber.Route(person, binaryWriterProcessor, false);

            stream.Position = 0;
            var binaryReaderProcessor = new BinaryReaderProcessor(new LoggingReader(new DecompressingReader(new BinaryReaderAdapter(new BinaryReader(stream))), Console.Out));

            var readerGraphClimber = DefaultGraphClimber <BinaryReaderProcessor> .Create(stateMemberProvider);

            var strongBox = new StrongBox <object>();

            readerGraphClimber.Climb(strongBox, binaryReaderProcessor);


            //ClimbStore store = new ClimbStore(binaryReaderProcessor.GetType(),
            //    new BinaryStateMemberProvider(new PropertyStateMemberProvider()),
            //    new MethodMapper(),
            //    new TrivialExpressionCompiler());

            //ClimbDelegate<StrongBox<object>> climb = store.GetClimb<StrongBox<object>>(typeof (StrongBox<object>));

            //climb(binaryReaderProcessor, strongBox);
        }
Esempio n. 27
0
        public void Builder_Expression_Nested_Deep()
        {
            Person2   person = null;
            IOperator op     = sql.IsNotNull(() => person.Address.City.Country.Name);

            QueryResult result = engine.Compile(op);

            Assert.Equal("\"person\".\"AddressCityCountryName\" IS NOT NULL", result.Sql);
            Assert.Equal(new Dictionary <string, object>(), result.Parameters);
        }
Esempio n. 28
0
        /* The type of an object contains all the fields of an object, along with all the metadata
         * describing the object. We can use methods and objects in the System.Reflection namespace
         * to work with Type objects. The code below extract information about all the fields in the
         * Person2 type. It prints all the members of the Person2.
         * Note that the Name property has been implemented by the compiler as a pair of get and set
         * methods (set_Name and get_Name), and the class contains all the methods that are exposed
         * by an object, including ToString and, of course, the GetType method. */
        private static void InvestingatingATypeExample()
        {
            Person2 p    = new Person2();
            Type    type = p.GetType();

            foreach (MemberInfo member in type.GetMembers())
            {
                Console.WriteLine(member.ToString());
            }
        }
Esempio n. 29
0
        public void Expression_ForeignKey()
        {
            Person2   person = null;
            IOperator op     = sql.Op(() => person.Department.Guid != null);

            QueryResult result = engine.Compile(op);

            Assert.Equal("\"person\".\"DepartmentGuid\" IS NOT NULL", result.Sql);
            Assert.Equal(new Dictionary <string, object>(), result.Parameters);
        }
Esempio n. 30
0
        public void Column_Nested_Deep()
        {
            Person2 person = null;
            IColumn column = (IColumn)sql.Val(() => person.Address.City.Country.Name);

            QueryResult result = engine.Compile(column);

            Assert.Equal("\"person\".\"AddressCityCountryName\"", result.Sql);
            Assert.Equal(new Dictionary <string, object>(), result.Parameters);
        }
Esempio n. 31
0
        private static void TestStructAsValField()
        {
            Console.WriteLine("\n�ṹ����Ϊֵ���ͳ�Ա");
            Person2 person = new Person2();
            person.name.last = "Huang";
            person.name.first = "Jizhou";
            person.name.displayName = string.Empty;
            person.age = 26;

            TestStructInStructByVal(ref person);
        }
        public void Validate_ComplexType_SuppressValidation()
        {
            // Arrange
            var validatorProvider = CreateValidatorProvider();
            var modelState = new ModelStateDictionary();
            var validationState = new ValidationStateDictionary();

            var validator = CreateValidator();

            var model = new Person2()
            {
                Name = "Billy",
                Address = new Address { Street = "GreaterThan5Characters" }
            };

            modelState.SetModelValue("person.Name", "Billy", "Billy");
            modelState.SetModelValue("person.Address.Street", "GreaterThan5Characters", "GreaterThan5Characters");
            validationState.Add(model, new ValidationStateEntry() { Key = "person" });
            validationState.Add(model.Address, new ValidationStateEntry()
            {
                Key = "person.Address",
                SuppressValidation = true
            });

            // Act
            validator.Validate(validatorProvider, modelState, validationState, "person", model);

            // Assert
            Assert.True(modelState.IsValid);
            AssertKeysEqual(modelState, "person.Name", "person.Address.Street");

            var entry = modelState["person.Name"];
            Assert.Equal(ModelValidationState.Valid, entry.ValidationState);
            Assert.Empty(entry.Errors);

            entry = modelState["person.Address.Street"];
            Assert.Equal(ModelValidationState.Skipped, entry.ValidationState);
            Assert.Empty(entry.Errors);
        }
Esempio n. 33
0
 private static extern void TestStructInStructByVal(ref Person2 person);
Esempio n. 34
0
        public void WhenColumnNameDiffersFromProperty_InsertQueryShouldUseColumnName()
        {
            // Arrange
            Person2 person = new Person2 { Name = "Bob", Age = 40, BirthDate = DateTime.Now };
            Dialect dialect = new SqlServerDialect();
            ColumnMapCollection mappings = MapRepository.Instance.GetColumns(typeof(Person2));
            var command = new System.Data.SqlClient.SqlCommand();
            var db = MockRepository.GenerateStub<IDataMapper>();
            db.Expect(d => d.Command).Return(command);
            var mappingHelper = new MappingHelper(db);
            mappingHelper.CreateParameters<Person2>(person, mappings, true);
            string targetTable = "PersonTable";
            InsertQuery query = new InsertQuery(dialect, mappings, command, targetTable);

            // Act
            string queryText = query.Generate();

            // Assert
            Assert.IsTrue(queryText.Contains("[PersonName]"), "Query should contain column name");
            Assert.IsTrue(queryText.Contains("[PersonAge]"), "Query should contain column name");
            Assert.IsTrue(queryText.Contains("[BirthDate]"), "Query should contain property name");
            Assert.IsTrue(queryText.Contains("[IsHappy]"), "Query should contain property name");
        }
        private void SimpleBinarySerializationExample()
        {
            Console.WriteLine("Binary Serialization example");
            Console.WriteLine("Non Serialized is valid only on field types not on properties");
            Person2 person2 = new Person2 { ID = 1, Name = "Mayank" };

            Console.WriteLine("Serialing using Binary Formatter into memory stream");
            IFormatter formatter = new BinaryFormatter();
            using (MemoryStream stream = new MemoryStream())
            {
                formatter.Serialize(stream, person2);
                stream.Position = 0;
                Person2 dp = (Person2)formatter.Deserialize(stream);
                Console.WriteLine("Deserialized Person details are Id:{0} with Name :{1}", dp.ID, dp.Name);
            }
        }