public static void CreateProperyStat(PropertyObject po, RealtyDb _db)
 {
     _db.PropertyStats.Add(new PropertyStat()
     {
         PropertyObject = po,
         day = DateTime.Today.Day,
         month = DateTime.Today.Month,
         year = DateTime.Today.Year
     });
     _db.SaveChanges();
 }
        public void ValidateAndFix(PropertyObject po)
        {
            if (po == null) return;
            string reason = string.Empty;
            bool markToDelete = false;
    
            if (po.PropertyType == null)
            {
                markToDelete = true;
                reason = "Не указан тип нобъекта";
            }



            if (string.IsNullOrEmpty(po.Title) || po.Title.Length < 10)
            {
                reason = "Заголовок для данного объявления не найден";
                markToDelete = true;
            }

            if (!string.IsNullOrEmpty(po.Title) && po.Title.Length >= 500)
            {
                po.Title = po.Title.Substring(0, 499);
            }

            if (string.IsNullOrEmpty(po.PropertyDescription) || po.PropertyDescription.Length < 50)
            {
                reason = "Текст объявления не найден";
                markToDelete = true;
            }

            if (string.IsNullOrEmpty(po.Phone1) || po.Phone1.Length < 5)
            {
                reason = "Телефон не найден";
                markToDelete = true;
            }

            if (!string.IsNullOrEmpty(po.Phone1) && po.Phone1.Length >= 20)
            {
                po.Phone1 = po.Phone1.Substring(0, 19);                
            }


            if (string.IsNullOrEmpty(po.ContactName))
                po.ContactName = "Агент";

            po.IsDeleted = (markToDelete ? 1 : 0);
            po.ReasonOfDelete = reason;
            if (markToDelete)
                po.DeletedDate = DateTime.Now;
        }
        private void AddLandSpecifics(PropertyObject po)
        {
            #region landCommunications

            // var _dbForInsert = new RealtyDb();
            var LandCommunicationToObjForAdding = new List<LandCommunicationToObj>();
            var landCommunications = from s in _db.LandCommunications
                                     select s;
            bool isChecked = false;
            foreach (var item in landCommunications)
            {
                if (Request.Form[item.guid.ToString()] != null &&
                    Request.Form[item.guid.ToString()].Contains(',') &&
                    Request.Form[item.guid.ToString()].Split(',').Count() == 2 &&
                    bool.TryParse(Request.Form[item.guid.ToString()].Split(',')[0].ToString(), out isChecked))
                {
                    if (isChecked)
                    {
                        isChecked = false;
                        var landCommunicationToObj = new LandCommunicationToObj()
                        {
                            LandCommunicationId = item,
                            PropertyObjectId = po
                        };
                        LandCommunicationToObjForAdding.Add(landCommunicationToObj);

                    }
                }
            }

            foreach (var item in LandCommunicationToObjForAdding)
            {
                if (_db.Entry(item).State == System.Data.EntityState.Detached)
                    _db.LandCommunicationToObjs.Attach(item);

                _db.LandCommunicationToObjs.Add(item);
                _db.Entry(item.PropertyObjectId).State = System.Data.EntityState.Unchanged;
                _db.Entry(item.LandCommunicationId).State = System.Data.EntityState.Unchanged;
                _db.SaveChanges();
            }
            #endregion

            #region landFunctions routine
            isChecked = false;
            var LandFunctionToObjForAdding = new List<LandFunctionToObj>();
            var landFunctions = from s in _db.LandFunctions
                                select s;

            foreach (var item in landFunctions)
            {
                if (Request.Form[item.guid.ToString()] != null &&
                    Request.Form[item.guid.ToString()].Contains(',') &&
                    Request.Form[item.guid.ToString()].Split(',').Count() == 2 &&
                    bool.TryParse(Request.Form[item.guid.ToString()].Split(',')[0].ToString(), out isChecked))
                {
                    if (isChecked)
                    {
                        isChecked = false;
                        var landFunctionToObj = new LandFunctionToObj()
                        {
                            LandFunctionId = item,
                            PropertyObjectId = po
                        };
                        LandFunctionToObjForAdding.Add(landFunctionToObj);
                        //_dbForInsert.LandFunctionToObjs.Add(landFunctionToObj);
                        //_dbForInsert.Entry(landFunctionToObj.PropertyObjectId).State = System.Data.EntityState.Unchanged;
                        //_dbForInsert.Entry(landFunctionToObj.LandFunctionId).State = System.Data.EntityState.Unchanged;
                        //_dbForInsert.SaveChanges();
                    }
                }
            }
            foreach (var item in LandFunctionToObjForAdding)
            {

                if (_db.Entry(item).State == System.Data.EntityState.Detached)
                    _db.LandFunctionToObjs.Attach(item);

                _db.LandFunctionToObjs.Add(item);
                _db.Entry(item.PropertyObjectId).State = System.Data.EntityState.Unchanged;
                _db.Entry(item.LandFunctionId).State = System.Data.EntityState.Unchanged;
                _db.SaveChanges();
            }
            #endregion


        }
        private void StoreEntity()
        {


            lock (dbLoaderLock)
            {
                Monitor.Wait(dbLoaderLock);
            }

            RealtyDb _db = new RealtyDb();
            bool stopLoop = false;
            Entity ent = null;
            int countStoredObjects = 0;

            var city = (from s in _db.Cities
                        select s).ToArray<City>();

            var district = (from s in _db.CityDistricts.Include("City")
                            select s).ToList<CityDisctict>();

            var propertyTypes = (from s in _db.PropertyTypes
                                 select s).ToList<PropertyType>();

            var propertyActions = (from s in _db.PropertyActions
                                   select s).ToList<PropertyAction>();

            var propertyObjects = (from s in _db.PropertyObjects
                                   select s).ToList<PropertyObject>();

            var periods = (from s in _db.Periods
                           select s).ToList<Periods>();

            var buildingTypes = (from s in _db.BuildingTypes
                                 select s).ToList<BuildingType>();

            var wcTypes = (from s in _db.WCTypes
                           select s).ToList<WCType>();

            var currencyTypes = (from s in _db.CurrencyTypes
                                 select s).ToList<CurrencyType>();

            var priceForTypes = (from s in _db.PriceForTypes
                                 select s).ToList<PriceForType>();

            var landCommunications = (from s in _db.LandCommunications
                                      select s).ToList<LandCommunication>();

            var landFunctions = (from s in _db.LandFunctions
                                 select s).ToList<LandFunction>();

            var commercialPropertyTypes = (from s in _db.CommercialPropertyTypes
                                           select s).ToList<CommercialPropertyType>();

            var serviceTypes = (from s in _db.ServiceTypes
                                select s).ToList<ServiceType>();


            _db.Dispose();
            _db = null;

            string connStr = "server=localhost; Port =3306; user id=root; password=mysqlPass; database=RealtyDb; pooling=true; CharSet=utf8; Connection Timeout=10000; Protocol=socket;";
            SqlObjectManipulation sql = new SqlObjectManipulation(connStr);
            WebRealty.Common.ImageProcessing imgHelper = new WebRealty.Common.ImageProcessing();

            DataValidator validate = new DataValidator();
            //int countInstructions = 0;
            //int countLinksToObject = 0;
            int countEntities = 0;
            int tmpInt = -1;
            do
            {
                lock (entitiesLocker)
                {
                    if (entities.Count > 0)
                        ent = entities.Dequeue();
                    countEntities = entities.Count;
                }

                //if (countEntities < minLimitList)
                //{
                //    lock (collectEntityLock)
                //    {
                //        Monitor.PulseAll(collectEntityLock);
                //    }
                //}



                //lock (instructionLocker)//получаем количество доступных инструкций
                //{
                //    countInstructions = instructions.Count();
                //}

                if (ent == null && t2.IsAlive)//засыпаем, пока нес не позовут
                {
                    eventLog.AddEventToLog("StoreEntity- сслыку на объект получить не удалось, поток собиратель объетов еще живой- засыпаем");
                    lock (dbLoaderLock)
                    {
                        Monitor.Wait(dbLoaderLock);
                    }
                    continue;
                }

                if (ent != null)
                {
                    var houseTypeObj = (from s in buildingTypes.AsEnumerable()
                                        where s.BuildingTypeName.ToLower() == ent.houseType.ToLower().Trim()
                                        select s).SingleOrDefault<BuildingType>();

                    var wcTypeObj = (from s in wcTypes.AsEnumerable()
                                     where s.WCTypeName.ToLower() == ent.wctype.ToLower().Trim()
                                     select s).SingleOrDefault<WCType>();

                    var currencyObj = (from s in currencyTypes
                                       where s.CurrencyTypeName.ToLower() == (ent.currency != null ? ent.currency.ToLower().Trim() : "у.е")
                                       select s).SingleOrDefault<CurrencyType>();

                    PriceForType priceForObj = null;
                    if (ent.priceFor != null)
                        priceForObj = (from s in priceForTypes
                                       where s.PriveForTypeName.ToLower().Replace(".", "") == ent.priceFor.ToLower().Trim().Replace(".", "")
                                       select s).FirstOrDefault<PriceForType>();

                    var cityObj = (from s in city
                                   where s.CityName.ToLower() == ent.City.ToLower().Trim()//"Киев".ToLower()//
                                   select s).SingleOrDefault<City>();

                    var districtObj = (from s in district
                                       where s.District.ToLower() == ent.District.ToLower().Trim()//"Голосеевский р-н.".ToLower()//
                                       && s.City.Id == cityObj.Id
                                       select s).SingleOrDefault<CityDisctict>();

                    var propertyTypeObj = (from s in propertyTypes
                                           where s.PropertyTypeName.ToLower() == ent.propertyType.ToLower().Trim()//"Квартиры".ToLower()//
                                           select s).SingleOrDefault<PropertyType>();

                    var propertyActionObj = (from s in propertyActions
                                             where s.PropertyActionName.ToLower() == ent.propertyAction.ToLower().Trim()//"Продажа".ToLower()//
                                             && s.PropertyType.Id == propertyTypeObj.Id
                                             select s).SingleOrDefault<PropertyAction>();

                    PropertyObject po = new PropertyObject()
                    {
                        BalconAvailable = ent.balconyAvailable,
                        BalconSpace = ent.balconySize,
                        BuildingTypeName = houseTypeObj,
                        City = cityObj,
                        CityDistrict = districtObj,
                        CommercialPropertyType = null,
                        ContactName = ent.contactName,
                        CountFloors = ent.countFloors, //???????
                        CountPhotos = (ent.photos != null ? ent.photos.Count() : 0),//ent.LinkToPhotos.Count(),
                        //CreatedDate=
                        Currency = currencyObj,
                        DistanceToCity = ent.distanceToCity,
                        Floor = ent.floor,
                        IsActive = true,
                        isBalconGlassed = ent.isBalconyGlassed,
                        IsNewBuilding = ent.isNewBuilding,
                        KitchenSpace = ent.kitchenSize,
                        LivingSpace = ent.livingSize,
                        NoCommission = ent.noComission,
                        //Periods=
                        Phone1 = ent.phone1,
                        Price = ent.price,
                        PriceForTypeName = priceForObj,
                        PropertyAction = propertyActionObj,
                        PropertyDescription = ent.description,
                        PropertyType = propertyTypeObj,
                        RoomCount = ent.roomsCount,
                        ServiceType = null,
                        Title = ent.title,
                        TotalSpace = ent.allSize,
                        WCType = wcTypeObj,
                        LinkOfObjectGrab = ent.linkToOriginalObject

                    };



                    if (po.CountFloors <= 0)
                        po.CountFloors = (int)ent.houseCountFloor;


                    if (po.LivingSpace <= 0)
                        po.LivingSpace = ent.houseGardenSize;

                    if (po.TotalSpace <= 0)
                        po.TotalSpace = ent.houseSize;

                    if (po.TotalSpace <= 0)
                        po.TotalSpace = ent.commercialObjectSize;




                    var datePart = ent.CreatedDate.Split('-');
                    if (datePart != null && datePart.Length > 1)
                    {
                        var dateSplitted = datePart[0].Split('.');
                        var timeSplitted = datePart[1].Split(':');
                        if (dateSplitted.Length == 3)
                        {
                            DateTime createdDate = new DateTime(Convert.ToInt32(dateSplitted[2]),
                                Convert.ToInt32(dateSplitted[1]),
                                Convert.ToInt32(dateSplitted[0]),
                                Convert.ToInt32(timeSplitted[0]),
                                Convert.ToInt32(timeSplitted[1]),
                                0, DateTimeKind.Local
                                );
                            po.CreatedDate = createdDate;
                        }
                    }

                    validate.ValidateAndFix(po);
                    try
                    {
                        int objectId = sql.AddPropertyObject(po);//uncomment it

                        for (int i = 0; i < ent.photos.Count(); i++)
                        {
                            if (ent.photos[i] != null && ent.photos[i].Length > 0)
                            {
                                //uncomment it
                                sql.Mysql_File_Save(objectId, 0, i.ToString() + ".jpg", "", 521, 521,
                                     ent.photos[i], imgHelper.ResizeImage(ent.photos[i], new System.Drawing.Size(120, 90)), false);
                            }
                        }
                        ent = null;
                        po = null;
                        Console.WriteLine("Stored objects : " + (++countStoredObjects).ToString());
                    }
                    catch (Exception ex)
                    {
                        eventLog.AddEventToLog("ОШИБКА сохранения объекта в БД: " + ex.Message.ToString() + " стэк ошибки: " + ex.StackTrace.ToString());
                    }
                }



                if (!t2.IsAlive && countEntities == 0)
                {
                    stopLoop = true;
                    linkLogger.TerminateLog();
                }

            } while (!stopLoop);

            Console.WriteLine("StoreEntity terminated");
            eventLog.AddEventToLog("StoreEntity завершает работу");
            return;

        }
        public int AddPropertyObject(PropertyObject po)
        {
            int result = -1;
            using (MySql.Data.MySqlClient.MySqlConnection oConn =
                new MySql.Data.MySqlClient.MySqlConnection(this.connStr))
            {
                oConn.Open();

                MySql.Data.MySqlClient.MySqlCommand cmd = oConn.CreateCommand();
                cmd.Connection = oConn;

                cmd.CommandText = @"INSERT INTO PropertyObjects (City_Id, CityDistrict_Id, PropertyType_Id, PropertyAction_Id,
Title,PropertyDescription,RoomCount,TotalSpace,LivingSpace,KitchenSpace,BuildingTypeName_Id,Floor,CountFloors,IsNewBuilding,BalconAvailable,
BalconSpace,isBalconGlassed,ContactName,Price,Currency_Id,PriceForTypeName_Id,NoCommission,Phone1,Phone2,Phone3,Periods_Id,CreatedDate,SourceUrl,
UserOwner_Id,DistanceToCity,WCType_Id,CountPhotos,CommercialPropertyType_Id,ServiceType_Id,IsActive,IsDeleted,DeletedDate,LinkOfObjectGrab) values (?City, ?CityDistrict, ?PropertyType, 
?PropertyAction,
?Title,?PropertyDescription,?RoomCount,?TotalSpace,?LivingSpace,?KitchenSpace,?BuildingTypeName,?Floor,?CountFloors,?IsNewBuilding,?BalconAvailable,
?BalconSpace,?isBalconGlassed,?ContactName,?Price,?Currency,?PriceForTypeName,?NoCommission,?Phone1,?Phone2,?Phone3,?Periods,?CreatedDate,?SourceUrl,
?UserOwner,?DistanceToCity,?WCType,?CountPhotos,?CommercialPropertyType,?ServiceType,?IsActive,?IsDeleted,?DeletedDate,?LinkOfObjectGrab);
select last_insert_id();";

                cmd.Parameters.Add("?City", (po.City != null ? po.City.Id.ToString() : null));

                cmd.Parameters.Add("?CityDistrict", (po.CityDistrict != null ? po.CityDistrict.Id.ToString() : null));

                cmd.Parameters.Add("?PropertyType", (po.PropertyType != null ? po.PropertyType.Id.ToString() : null));

                cmd.Parameters.Add("?PropertyAction", (po.PropertyAction != null ? po.PropertyAction.Id.ToString() : null));

                cmd.Parameters.Add("?Title", po.Title);

                cmd.Parameters.Add("?PropertyDescription", po.PropertyDescription);

                cmd.Parameters.Add("?RoomCount", po.RoomCount);

                cmd.Parameters.Add("?TotalSpace", po.TotalSpace);

                cmd.Parameters.Add("?LivingSpace", po.LivingSpace);

                cmd.Parameters.Add("?KitchenSpace", po.KitchenSpace);

                cmd.Parameters.Add("?BuildingTypeName", (po.BuildingTypeName != null ? po.BuildingTypeName.Id.ToString() : null));

                cmd.Parameters.Add("?Floor", po.Floor);

                cmd.Parameters.Add("?CountFloors", po.CountFloors);

                cmd.Parameters.Add("?IsNewBuilding", po.IsNewBuilding);

                cmd.Parameters.Add("?BalconAvailable", po.BalconAvailable);

                cmd.Parameters.Add("?BalconSpace", po.BalconSpace);

                cmd.Parameters.Add("?isBalconGlassed", po.isBalconGlassed);

                cmd.Parameters.Add("?ContactName", po.ContactName);

                cmd.Parameters.Add("?Price", po.Price);

                cmd.Parameters.Add("?Currency", (po.Currency != null ? po.Currency.Id.ToString() : null));

                cmd.Parameters.Add("?PriceForTypeName", (po.PriceForTypeName != null ? po.PriceForTypeName.Id.ToString() : null));

                cmd.Parameters.Add("?NoCommission", po.NoCommission);

                cmd.Parameters.Add("?Phone1", po.Phone1);
                cmd.Parameters.Add("?Phone2", po.Phone2);
                cmd.Parameters.Add("?Phone3", po.Phone3);

                cmd.Parameters.Add("?Periods", (po.Periods != null ? po.Periods.Id.ToString() : null));

                cmd.Parameters.Add("?CreatedDate", po.CreatedDate);

                cmd.Parameters.Add("?SourceUrl", po.SourceUrl);

                cmd.Parameters.Add("?UserOwner", (po.UserOwner != null ? po.UserOwner.Id.ToString() : null));

                cmd.Parameters.Add("?DistanceToCity", po.DistanceToCity);

                cmd.Parameters.Add("?WCType", (po.WCType!=null?po.WCType.Id.ToString():null));

                cmd.Parameters.Add("?CountPhotos", po.CountPhotos);

                cmd.Parameters.Add("?CommercialPropertyType", (po.CommercialPropertyType != null ? po.CommercialPropertyType.Id.ToString() : null));

                cmd.Parameters.Add("?ServiceType", (po.ServiceType != null ? po.ServiceType.Id.ToString() : null));

                cmd.Parameters.Add("?IsActive", po.IsActive);

                cmd.Parameters.Add("?IsDeleted", po.IsDeleted);

                cmd.Parameters.Add("?DeletedDate", po.DeletedDate);

                cmd.Parameters.Add("?LinkOfObjectGrab", po.LinkOfObjectGrab);


                result = Convert.ToInt32(cmd.ExecuteScalar());
                oConn.Close();

            }
            return result;
        }