// Сохранить результат в базе данных

        public bool Store(int k)
        {
            MyEntityContext ctx = Application.Context;

            PrepareClusters(k);

            ctx.ObjectClasss.ToList().ForEach(ctx.DeleteObject);
            ctx.SaveChanges();

            foreach (var cl in Cidx.Select((c, i) => new { c, i }))
            {
                IObjectClass c = ctx.ObjectClasss.Create();
                c.Cluster = cl.c;
                IObject ob = input[cl.i];
                c.Object = ob;
                Console.WriteLine("ob:" + ob.GUID + "->" + cl.c + "[" + cl.i + "]");
            }

            ctx.SaveChanges();

            ctx.ClassNames.ToList().ForEach(ctx.DeleteObject);

            for (int i = 0; i < k; i++) // Заготовки имен кластеров.
            {
                IClassName cn = ctx.ClassNames.Create();
                cn.Name    = i.ToString();
                cn.Cluster = i;
            }

            ctx.SaveChanges();

            return(true);
        }
Esempio n. 2
0
        protected void GetLocationData(IObject obj, XElement input, string tagName = "location")
        {
            MyEntityContext ctx      = Application.Context;
            XElement        locInput = GetFirstElement(input, tagName);

            string   coName = GetText(locInput, "country");
            ICountry co     = ctx.Countries.Where(x => x.Name.Equals(coName)).FirstOrDefault();

            if (co == null)
            {
                co      = ctx.Countries.Create();
                co.Name = coName;
                ctx.Add(co);
                ctx.SaveChanges();
            }

            string  regName = GetText(locInput, "region");
            IRegion reg     = ctx.Regions.Where(x => x.Name == regName &&
                                                x.Country.Name == coName).FirstOrDefault();

            if (reg == null)
            {
                reg         = ctx.Regions.Create();
                reg.Country = co;
                reg.Name    = regName;
                ctx.SaveChanges();
            }

            string locLN  = GetText(locInput, "locality-name");
            string locSLN = GetText(locInput, "sub-locality-name");

            ILocation loc = ctx.Locations.Where(x =>
                                                x.Region.Country.Name == coName &&
                                                x.Region.Name == regName &&
                                                x.LocalityName == locLN &&
                                                x.SubLocalityName == locSLN).FirstOrDefault();

            if (loc == null)
            {
                loc                 = ctx.Locations.Create();
                loc.Region          = reg;
                loc.LocalityName    = locLN;
                loc.SubLocalityName = locSLN;
            }
            obj.Location = loc;
            try {
                obj.Address = GetText(locInput, "address");
            } catch (InvalidOperationException) {
                obj.Address = null;
            }
        }
Esempio n. 3
0
        protected void GetSalesAgent(IOffer offer, XElement input, string tagName = "sales-agent")
        {
            XElement sa = GetFirstElement(input, tagName);

            RoleEnum saRole = GetRole(sa);
            string   name   = GetText(sa, "name");
            string   phone  = GetText(sa, "phone");

            MyEntityContext ctx   = Application.Context;
            IAgent          agent = ctx.Agents.Where(x => x.Name == name &&
                                                     x.Phone == phone).FirstOrDefault();

            if (agent == null)
            {
                agent       = ctx.Agents.Create();
                agent.GUID  = GetGUID();
                agent.Name  = name;
                agent.Phone = phone;
                agent.Role  = saRole;
                ctx.Add(agent);
                ctx.SaveChanges();
            }
            offer.Agent = agent;

            // FIXME: Implement
        }
Esempio n. 4
0
        protected void GetSalesAgent(IOffer offer, XElement input, string tagName = "sales-agent")
        {
            XElement sa = GetFirstElement(input, tagName);

            RoleEnum saRole = GetRole(sa);
            string   name   = GetText(sa, "name");
            string   phone  = GetText(sa, "phone");

            MyEntityContext ctx   = Application.Context;
            IAgent          agent = ctx.Agents.Where(x => x.Name == name &&
                                                     x.Phone == phone).FirstOrDefault();
            string op = "Got";

            if (agent == null)
            {
                agent       = ctx.Agents.Create();
                agent.GUID  = GetGUID();
                agent.Name  = name;
                agent.Phone = phone;
                agent.Role  = saRole;
                ctx.Add(agent);
                ctx.SaveChanges();
                op = "Added";
            }

            /*
             * Console.WriteLine(string.Format("{3} agent: {0}:{1}:{2}",
             *                              agent.Name, agent.Phone,
             *                              agent.Role,
             *                              op));
             */
            offer.Agent = agent;
        }
Esempio n. 5
0
        private IAgent createAnonymousAgent()
        {
            MyEntityContext ctx = Application.Context;

            if (GUID == null)
            {
                GUID = ImportFromAtlcomru.GetGUID();
            }
            else
            {
                // Try load from database
                IAgent agent = ctx.Agents.Where(x => x.GUID == GUID).FirstOrDefault();
                if (agent != null)
                {
                    Agent = agent;
                }
            }

            IAgent anonym = ctx.Agents.Create();

            anonym.GUID = GUID;
            anonym.Role = RoleEnum.Unknown;
            this.Agent  = anonym;
            ctx.Add(this.Agent);
            ctx.SaveChanges();

            return(this.Agent);
        }
Esempio n. 6
0
        public void Import(bool onlyLoad = false)
        {
            XDocument       doc = Document; // Загружает XML, еще необработанный, дерево.
            MyEntityContext ctx = Application.Context;

            if (!onlyLoad)
            {
                Console.WriteLine("Processing doc!");

                /*
                 * IEnumerable<XElement> proposals =
                 *  from p in doc.Elements()
                 *  select p;
                 */

                IEnumerable <XElement> proposals =
                    doc.Descendants(YName("offer"));


                string siteName = "Атлант-Недвижимость";
                string siteURL  = @"http://atlantnt.ru";
                ISite  site     = ctx.Sites.Where(x => x.URL.Equals(siteURL)).FirstOrDefault();

                if (site == null)
                {
                    site      = ctx.Sites.Create();
                    site.Name = siteName;
                    site.URL  = siteURL;
                    ctx.SaveChanges();
                }

                int count = proposals.Count(), number = 0;
                foreach (XElement p in proposals)
                {
                    if (number % 100 == 0)
                    {
                        Console.Write(String.Format("Rec {0} of {1}    \r", number, count));
                        Application.Context.SaveChanges();
                    }
                    ;
                    ProcessProposal(p, site);
                    number++;
                }
                ;

                Application.Context.SaveChanges();
            }
        }
Esempio n. 7
0
        protected void addLike(IAgent agent, IObject obj)
        {
            MyEntityContext ctx  = Application.Context;
            ILikes          like = ctx.Likess.Where(x => x.Agent.GUID == agent.GUID && x.Object.GUID == obj.GUID).FirstOrDefault();

            if (like == null)
            {
                like         = ctx.Likess.Create();
                like.Agent   = agent;
                like.Object  = obj;
                like.Value   = 0.0;
                like.Quality = OriginatingEnum.Measured;
                ctx.Add(like);
            }
            like.Value += 1;
            ctx.SaveChanges();
            Console.WriteLine(" Spying: Added like of agent " + like.Agent.GUID +
                              " to object " + like.Object.GUID + " and now it is " + like.Value);
        }
Esempio n. 8
0
        public bool Process()
        {
            MyEntityContext ctx = Application.Context;

            string nick  = request.Form.user;
            string phone = request.Form.phone;

            Console.WriteLine("---> FORM:" + nick);
            IAgent user     = ctx.Agents.Where(x => x.NickName == nick).FirstOrDefault();
            string register = request.Form["register"];

            MessageModel success = null;

            if (register != null && user != null)
            {
                return(UserBad("Пользователь уже зарегистрирован"));
            }
            else if (register == null && user == null)
            {
                return(UserBad("Пользователь не найден"));
            }
            else if (register != null && user == null)
            {
                // FIXME: Проверки правильности данных не сделаны.

                string password = request.Form.password;
                string repeat   = request.Form.repeat;

                if (password != repeat)
                {
                    return(UserBad("Пароли не совпадают"));
                }

                user              = ctx.Agents.Create();
                user.Name         = request.Form.firstname + " " + request.Form.surname + " " + request.Form.lastname;
                user.PasswordHash = BCryptHelper.HashPassword(password, SALT);
                user.Phone        = request.Form.phone;
                user.GUID         = ImportFromAtlcomru.GetGUID();
                if (request.Form.realtor == "checked")
                {
                    user.Role = RoleEnum.Agent;
                }
                else
                {
                    user.Role = RoleEnum.Buyer;
                }
                user.NickName = nick;
                user.Email    = request.Form.email;
                ctx.Add(user);
                ctx.SaveChanges();
                success = info("Теперь вы зарегистрированы в системе. Можно начинать бояться.",
                               msg: "Успешная регистрация");
            }
            else             // register == null && user != null
            {
                string password = request.Form.password;
                if (!BCryptHelper.CheckPassword(password, user.PasswordHash))
                {
                    return(UserBad("Неправильный пароль"));
                }
                success = info("Ну вот вы и вошли в систему.", msg: "Успешная идентикация");
            }
            // К этому моменту пользователь или аутентифицирован
            // или создан.
            // Установить сессию.

            // Сессии бывают двух типов
            // 1. На время одного сеанса
            // 2. Между сеансами.
            // Мы будем делать 2 из 1.
            // Т.е. в сессии типа 1 собирать (обновлять) данные
            //      зарегистрированного пользователя.

            Session          = new SessionModel(); //Создание новой сессии
            Session["valid"] = true;
            Session["user"]  = user;               // Объект пользователя в сессии
            Session.GUID     = user.GUID;          // Идентификатор сессии пользователя.

            Session["message"] = success;

            Console.WriteLine("Linux rulez!");

            // TODO: Еще надо сделать выход из сессии при разлогигивании. Но пока у нас нет такой команды.

            return(true);
        }
Esempio n. 9
0
        public bool Process()
        {
            MyEntityContext ctx = Application.Context;

            string nick  = request.Form.user;
            string phone = request.Form.phone;

            Console.WriteLine("---> FORM:" + nick);
            IAgent user     = ctx.Agents.Where(x => x.NickName == nick).FirstOrDefault();
            string register = request.Form["register"];

            MessageModel success = null;

            if (register != null && user != null)
            {
                return(UserBad("Пользователь уже зарегистрирован"));
            }
            else if (register == null && user == null)
            {
                return(UserBad("Пользователь не найден"));
            }
            else if (register != null && user == null)
            {
                // FIXME: Проверки правильности данных не сделаны.

                string password = request.Form.password;
                string repeat   = request.Form.repeat;

                if (password != repeat)
                {
                    return(UserBad("Пароли не совпадают"));
                }

                user = Session.Agent;

                if (Session.Valid)
                {
                    throw new InvalidSession("user must be invalid while registering");
                }
                // Теперь мы из анонимного пользователя делаем зарегистрированного.
                // При этом сохраняется все, что он насмотрел.
                user.Name         = request.Form.firstname + " " + request.Form.surname + " " + request.Form.lastname;
                user.PasswordHash = BCryptHelper.HashPassword(password, SALT);
                user.Phone        = request.Form.phone;
                if (request.Form.realtor == "checked")
                {
                    user.Role = RoleEnum.Agent;
                }
                else
                {
                    user.Role = RoleEnum.Buyer;
                }
                user.NickName = nick;
                user.Email    = request.Form.email;
                ctx.Add(user);
                ctx.SaveChanges();
                success = info("Теперь вы зарегистрированы в системе. Можно начинать бояться.",
                               msg: "Успешная регистрация");
            }
            else             // register == null && user != null
            {
                string password = request.Form.password;
                if (!BCryptHelper.CheckPassword(password, user.PasswordHash))
                {
                    return(UserBad("Неправильный пароль"));
                }
                success = info("Ну вот вы и вошли в систему.", msg: "Успешная идентикация");
            }

            // Session = new SessionModel(); //Создание новой сессии
            Session.Agent = user;               // Объект пользователя в сессии
            Session.GUID  = user.GUID;          // Идентификатор сессии пользователя.

            Session["message"] = success;

            return(true);
        }