/// <summary>
        /// тесты для функции сервиса UpdateRelative
        /// </summary>
        public static void TestUpdateRelative()
        {
            dataFormat = "json";
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;

            string operationUrl = "http://localhost:8732/Design_Time_Addresses/RESTService/UpdateRelative";
            string passportNumber = "1111654321";
            string relPassportNumber = "1112654321";
            Person updatedRelative = new Person
            {
                Address = "",
                DateOfBirth = null,
                FirstName = "Vasily",
                PassportNumber = "",
                PersonID = 0,
                SecondName = "",
                Sex = "",
                ThirdName = ""
            };

            int i = 0;
            Stream stream = null;
            WebRequest req = null;
            WebResponse resp = null;
            StreamReader sr = null;
            while (i < 2)
            {
                if (i > 0) updatedRelative.FirstName = "Igor";

                #region Create params
                string updatedRelativeStr = "";
                updatedRelativeStr = "{\"updatedRelative\":" + JsonConvert.SerializeObject(updatedRelative, settings) + "}";
                Console.WriteLine(updatedRelativeStr);
                byte[] data = Encoding.GetEncoding(1251).GetBytes(updatedRelativeStr);
                #endregion

                #region Create Request
                req = WebRequest.Create(operationUrl + "?passportNumber=" + passportNumber + "&relPassportNumber=" + relPassportNumber);
                req.Method = "POST";
                req.Timeout = 12000;
                req.ContentType = "application/" + dataFormat;
                req.ContentLength = data.Length;
                #endregion

                #region Send Request
                Console.WriteLine("iter - " + i);
                stream = req.GetRequestStream();
                stream.Write(data, 0, data.Length);
                stream.Close();
                #endregion

                #region Get Response
                resp = req.GetResponse();
                stream = resp.GetResponseStream();
                sr = new StreamReader(stream);
                string s = sr.ReadToEnd();
                Console.WriteLine(s);
                #endregion

                Assert.IsTrue(s == "\"relative updated successfully\"");

                var sql = from p in persones.GetContent() where p.PassportNumber == relPassportNumber select p.FirstName;
                Console.WriteLine(sql.First());
                Console.WriteLine(updatedRelative.FirstName);
                Assert.IsTrue(sql.First() == updatedRelative.FirstName);

                i++;
            }
        }
        /// <summary>
        /// тесты для функции сервиса GetRelativesList
        /// </summary>
        public static void TestGetRelativesList()
        {
            //настройка сериализации типа DateTime в JSON
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
            //адресс функции сервиса
            string operationUrl = "http://localhost:8732/Design_Time_Addresses/RESTService/GetRelativesList";
            //параметры для функции
            string passportNumber = "1111654321";
            Person filter = new Person { Address = "", 
                                         DateOfBirth = new DateTime(), 
                                         FirstName = "Igor", 
                                         PassportNumber = "", 
                                         PersonID = 0, 
                                         SecondName = "", 
                                         Sex = "", 
                                         ThirdName = "" };

            //создание и отправка запроса сервису
            #region Send Request
            //описание Url запроса
            WebRequest req = WebRequest.Create(operationUrl + "?passportNumber=" + passportNumber);
            //описание метода запрса
            req.Method = "POST";
            req.Timeout = 12000;
            //описание формата обмена данными
            req.ContentType = "application/" + dataFormat;
            //конвертация параметров из С# в соответствующий формат
            #region Create params
            string filterStr = "";
            if (dataFormat == "json")
            {
                filterStr = "{\"filter\":"+ JsonConvert.SerializeObject(filter, settings) + "}";
            }
            else
            {
                filterStr = "<GetRelativesList>" + 
                            "<filter xmlns:a=\"http://Person\">" +
                            "<a:Address>" + filter.Address + "</a:Address>" +
                            "<a:DateOfBirth>" + filter.DateOfBirth.Value.ToString("o") + "</a:DateOfBirth>" +
                            "<a:FirstName>" + filter.FirstName + "</a:FirstName>" +
                            "<a:PassportNumber>" + filter.PassportNumber + "</a:PassportNumber>" +
                            "<a:PersonID>" + filter.PersonID + "</a:PersonID>" +
                            "<a:SecondName>" + filter.SecondName + "</a:SecondName>" +
                            "<a:Sex>" + filter.Sex + "</a:Sex>" +
                            "<a:ThirdName>" + filter.ThirdName + "</a:ThirdName>" +
                            "</filter>" +
                            "</GetRelativesList>";

                /*StringBuilder sb = new StringBuilder();
                StringWriter sw = new StringWriter(sb);
                XmlDocument doc = new XmlDocument();
                XmlElement operationEl = doc.CreateElement("GetRelativesList");
                XmlElement filterEl = doc.CreateElement("filter");
                filterEl.SetAttribute("xmlns:a", "http://Person");
                XmlElement AddresseEl = doc.CreateElement("a", "Addresse", "http://Person");
                AddresseEl.InnerText = filter.Addresse;
                XmlElement dobEl = doc.CreateElement("DateOfBirth");
                dobEl.InnerText = filter.DateOfBirth.ToUniversalTime().ToString();
                XmlElement firstNameEl = doc.CreateElement("a", "FirstName", "http://Person");
                firstNameEl.InnerText = filter.FirstName;
                XmlElement pasportNumberEl = doc.CreateElement("PasportNumber");
                pasportNumberEl.InnerText = filter.PasportNumber;
                XmlElement personIDEl = doc.CreateElement("PersonID");
                personIDEl.InnerText = filter.PersonID.ToString();
                XmlElement secondNameEl = doc.CreateElement("SecondName");
                secondNameEl.InnerText = filter.SecondName;
                XmlElement sexEl = doc.CreateElement("Sex");
                sexEl.InnerText = filter.Sex;
                XmlElement thirdNameEl = doc.CreateElement("ThirdName");
                thirdNameEl.InnerText = filter.ThirdName;
                filterEl.AppendChild(AddresseEl);
                filterEl.AppendChild(dobEl);
                filterEl.AppendChild(firstNameEl);
                filterEl.AppendChild(pasportNumberEl);
                filterEl.AppendChild(personIDEl);
                filterEl.AppendChild(secondNameEl);
                filterEl.AppendChild(sexEl);
                filterEl.AppendChild(thirdNameEl);
                operationEl.AppendChild(filterEl);
                XmlTextWriter xtw = new XmlTextWriter(sw);
                doc.AppendChild(operationEl);
                doc.WriteContentTo(xtw);
                xtw.Close();
                filterStr = sb.ToString();*/
            }
            Console.WriteLine(filterStr);
            #endregion
            byte[] data = Encoding.GetEncoding(1251).GetBytes(filterStr);
            req.ContentLength = data.Length;
            Stream sendStream = req.GetRequestStream();
            sendStream.Write(data, 0, data.Length);
            sendStream.Close();
            #endregion
            //получение и обработка ответа сервиса
            #region Get Response
            WebResponse resp = req.GetResponse();
            System.IO.Stream stream = resp.GetResponseStream();
            StreamReader sr = new System.IO.StreamReader(stream);
            List<Relative> result = new List<Relative>();
            //конвертация строки ответа в объект C# типа List<Relative>
            if (dataFormat == "json")
            {
                string s = sr.ReadToEnd();
                Console.WriteLine(s);
                result = JsonConvert.DeserializeObject<List<Relative>>(s, settings);
            }
            else
            {
                string s = sr.ReadToEnd();
                Console.WriteLine(s);
                StringReader strR = new StringReader(s);

                string root = "ArrayOfRelative";
                XmlRootAttribute xra = new XmlRootAttribute();
                xra.ElementName = root;
                xra.Namespace = "http://schemas.datacontract.org/2004/07/DomainModel.Entities";
                result = (List<Relative>)(new XmlSerializer(result.GetType(), xra).Deserialize(strR));
            }
            #endregion

            Assert.IsTrue(result.Count == 1);
            Assert.IsTrue(result.First().RelationshipState == "father");
        }
        /// <summary>
        /// тесты для функции сервиса AddRelative
        /// </summary>
        public static void TestAddRelative()
        {
            dataFormat = "json";
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;

            string operationUrl = "http://localhost:8732/Design_Time_Addresses/RESTService/AddRelative";
            string passportNumber = "1111654321";
            Person person = new Person
            {
                Address = "",
                DateOfBirth = null,
                FirstName = "Julia",
                PassportNumber = "1114654321",
                PersonID = 0,
                SecondName = "Glazacheva",
                Sex = "female",
                ThirdName = "Igorevna"
            };
            string state = "sister";
            Relative relative = new Relative(person, state);

            
            #region Create params
            string relativeStr = "";
            relativeStr = "{\"relative\":" + JsonConvert.SerializeObject(relative, settings) + "}";
            Console.WriteLine(relativeStr);
            byte[] data = Encoding.GetEncoding(1251).GetBytes(relativeStr);          
            #endregion

            int i = 0;
            int[] personesCount = new int[2];
            int[] relationshipCount = new int[2];
            Stream stream = null;
            WebRequest req = null;
            WebResponse resp = null;
            StreamReader sr = null;
            while (i < 2)
            {
                #region Create Request
                req = WebRequest.Create(operationUrl + "?passportNumber=" + passportNumber + "&mode=" + mode);
                req.Method = "POST";
                req.Timeout = 12000;
                req.ContentType = "application/" + dataFormat;
                req.ContentLength = data.Length;
                #endregion

                #region Send Request
                Console.WriteLine("iter - " + i);
                stream = req.GetRequestStream();
                stream.Write(data, 0, data.Length);
                stream.Close();
                #endregion

                #region Get Response
                resp = req.GetResponse();
                stream = resp.GetResponseStream();
                sr = new System.IO.StreamReader(stream);
                string s = sr.ReadToEnd();
                Console.WriteLine(s);
                //Console.WriteLine(s.Length);
                #endregion

                Assert.IsTrue(s == "\"relative added successfully\"");

                var sqlP = from p in persones.GetContent() select p.PersonID;
                var sqlR = from r in relationships.GetContent() select r.RelationshipID;
                personesCount[i] = sqlP.Count();
                relationshipCount[i] = sqlR.Count();
                i++;
            }

            Assert.IsTrue(personesCount[0] == personesCount[1]);
            Assert.IsTrue(relationshipCount[0] == relationshipCount[1]);
        }
        /// <summary>
        /// тесты для функции сервиса GetPersonInfo
        /// </summary>
        public static void TestGetPersonInfo()
        {
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;

            string operationUrl = "http://localhost:8732/Design_Time_Addresses/RESTService/GetPersonInfo";
            string passportNumber = "1111654321";

            #region Create Request
            WebRequest req = WebRequest.Create(operationUrl + "?passportNumber=" + passportNumber);
            req.ContentType = "application/" + dataFormat;
            #endregion

            #region Get Response
            WebResponse resp = req.GetResponse();
            Stream stream = resp.GetResponseStream();
            StreamReader sr = new StreamReader(stream);
            Person result = new Person();

            if (dataFormat == "json")
            {
                string s = sr.ReadToEnd();
                Console.WriteLine(s);
                result = JsonConvert.DeserializeObject<Person>(s, settings);
            }
            else
            {
                string s = sr.ReadToEnd();
                Console.WriteLine(s);
                StringReader strR = new StringReader(s);

                string root = "Person";
                XmlRootAttribute xra = new XmlRootAttribute();
                xra.ElementName = root;
                xra.Namespace = "http://Person";
                result = (Person)(new XmlSerializer(result.GetType(), xra).Deserialize(strR));
            }
            #endregion

            Assert.IsTrue(result.FirstName == "Konstantin");
        }
 public List<Relative> GetRelativesList(string passportNumber, Person filter) 
 {
     try
     {
         List<Relative> list = new List<Relative>();
         //производим запрос к базе
         var result = from p1 in Persones.GetContent()
                      from r in Relationships.GetContent()
                      from p2 in Persones.GetContent()
                      where ((p1.PassportNumber == passportNumber) && (((p1.PersonID == r.SecondPersonID) && (p2.PersonID == r.FirstPersonID)) || ((p1.PersonID == r.FirstPersonID) && (p2.PersonID == r.SecondPersonID))))
                      select new { r, p2 };
         //фильтруем результат
         if (filter != null)
         {
             if (filter.Address != "")
             {
                 result = result.Where(r => r.p2.Address == filter.Address);
             }
             if ((filter.DateOfBirth != null) && (filter.DateOfBirth.Value.Year >= 1900))
             {
                 result = result.Where(r => (r.p2.DateOfBirth.Value.Year == filter.DateOfBirth.Value.Year) &&
                                            (r.p2.DateOfBirth.Value.Month == filter.DateOfBirth.Value.Month) &&
                                            (r.p2.DateOfBirth.Value.Day == filter.DateOfBirth.Value.Day));
             }
             if (filter.FirstName != "")
             {
                 result = result.Where(r => r.p2.FirstName == filter.FirstName);
             }
             if (filter.PassportNumber != "")
             {
                 result = result.Where(r => r.p2.PassportNumber == filter.PassportNumber);
             }
             if (filter.SecondName != "")
             {
                 result = result.Where(r => r.p2.SecondName == filter.SecondName);
             }
             if (filter.Sex != "")
             {
                 result = result.Where(r => r.p2.Sex == filter.Sex);
             }
             if (filter.ThirdName != "")
             {
                 result = result.Where(r => r.p2.ThirdName == filter.ThirdName);
             }
         }
         //создаем список
         if (result.Count() > 0)
         {
             foreach (var r in result)
             {
                 string state = "";
                 //запись в таблице Relationships имеет вид
                 // <RelationshipID, FirstPersonID, SecondPersonID, State>
                 // читается как:
                 // первая персона приходится второй тем-то
                 //пример:
                 // 1 2 4 father
                 // персона2 приходится персоне4 отцом
                 //пользователь получает ответ вида:
                 //данный человек приходится мне тем-то
                 //т.е. по логике ответа родственник должен стоять на FirstPersonID, чтобы соответствовать
                 //типу родственного отношения
                 //т.о. если в БД он находится на SecondPersonID, то отношение необходимо инвертировать
                 //пример:
                 //запись БД: Вася Пете отец
                 //запрос исходит от Васи (т.е. родственник не на FirstPersonID)
                 //ответ сервиса:
                 //Петя мне сын
                 if (r.p2.PersonID == r.r.FirstPersonID)
                 {
                     list.Add(new Relative(r.p2, r.r.State));
                 }
                 else
                 {
                     //инвертировани родственного отношения
                     #region Relationship logic
                     if ((r.r.State == "son") || (r.r.State == "daughter"))
                     {
                         if (r.p2.Sex == "male") { state = "father"; } else { state = "mother"; }
                     }
                     else if ((r.r.State == "mother") || (r.r.State == "father"))
                     {
                         if (r.p2.Sex == "male") { state = "son"; } else { state = "daughter"; }
                     }
                     else if ((r.r.State == "sister") || (r.r.State == "brother"))
                     {
                         if (r.p2.Sex == "male") { state = "brother"; } else { state = "sister"; }
                     }
                     else if ((r.r.State == "wife") || (r.r.State == "husband"))
                     {
                         if (r.p2.Sex == "male") { state = "husband"; } else { state = "wife"; }
                     }
                     else if ((r.r.State == "grandson") || (r.r.State == "granddaughter"))
                     {
                         if (r.p2.Sex == "male") { state = "grandfather"; } else { state = "grandmother"; }
                     }
                     else if ((r.r.State == "grandfather") || (r.r.State == "grandmother"))
                     {
                         if (r.p2.Sex == "male") { state = "grandson"; } else { state = "granddaughter"; }
                     }
                     else if ((r.r.State == "aunt") || (r.r.State == "uncle"))
                     {
                         if (r.p2.Sex == "male") { state = "nephew"; } else { state = "niece"; }
                     }
                     else if ((r.r.State == "nephew") || (r.r.State == "niece"))
                     {
                         if (r.p2.Sex == "male") { state = "uncle"; } else { state = "aunt"; }
                     }
                     #endregion
                     list.Add(new Relative(r.p2, state));
                 }
             }
         }
         return list;
     }
     finally
     {
         if (ToDispose) Context.Dispose();
     }
 }
 public string UpdateRelative(string passportNumber, string relPassportNumber, Person updatedRelative)
 {
     try
     {
         string message = "relative updated successfully";
         try
         {
             //ищем родственника в БД
             var result = from r in Relationships.GetContent()
                          from p1 in Persones.GetContent()
                          from p2 in Persones.GetContent()
                          where ((p1.PassportNumber == passportNumber) &&
                                     (p2.PassportNumber == relPassportNumber) &&
                                     (((r.FirstPersonID == p2.PersonID) && (r.SecondPersonID == p1.PersonID)) ||
                                     ((r.FirstPersonID == p1.PersonID) && (r.SecondPersonID == p2.PersonID))))
                          select p2;
             //если нашли, обновляем
             if (result.Count() != 0)
             {
                 var r = result.First();
                 if (updatedRelative.Address != "") r.Address = updatedRelative.Address;
                 if ((updatedRelative.DateOfBirth != null) && (updatedRelative.DateOfBirth.Value.Year >= 1900)) r.DateOfBirth = updatedRelative.DateOfBirth;
                 if (updatedRelative.FirstName != "") r.FirstName = updatedRelative.FirstName;
                 if (updatedRelative.PassportNumber != "") r.PassportNumber = updatedRelative.PassportNumber;
                 if (updatedRelative.SecondName != "") r.SecondName = updatedRelative.SecondName;
                 if (updatedRelative.Sex != "") r.Sex = updatedRelative.Sex;
                 if (updatedRelative.ThirdName != "") r.ThirdName = updatedRelative.ThirdName;
                 Context.SubmitChanges();
             }
             else
             {
                 message = "relationship between " + passportNumber + " and " + relPassportNumber + " doesn't exist";
             }
         }
         catch (Exception e)
         {
             message = e.Message;
         }
         return message;
     }
     finally
     {
         if (ToDispose) Context.Dispose();
     }
 }
 public Relative(Person p, string rs)
 {
     Person = p;
     RelationshipState = rs;
 }