Example #1
0
        public static void InsertBusiness()
        {
            using (var context = new BusinessContext())
            {
                var business = new Business
                {
                    Name          = "Corner Dry Cleaning",
                    LicenseNumber = "100x1"
                };
                context.Businesses.Add(business);

                var retail = new Retail
                {
                    Name          = "Shop and Save",
                    LicenseNumber = "200C",
                    Address       = "101 Main",
                    City          = "Anytown",
                    State         = "TX",
                    ZIPCode       = "76106"
                };
                context.Businesses.Add(retail);

                var web = new eCommerce
                {
                    Name          = "BuyNow.com",
                    LicenseNumber = "300AB",
                    URL           = "www.buynow.com"
                };
                context.Businesses.Add(web);

                context.SaveChanges();
            }
        }
Example #2
0
        private void saveRetail()
        {
            try
            {
                Retail retail = new Retail();
                retail.Name        = txtName.Text;
                retail.Address     = txtAddress.Text;
                retail.City        = new City(int.Parse(cmbCity.SelectedValue), string.Empty, string.Empty);
                retail.Phone       = txtPhone.Text;
                retail.MobilePhone = txtMobilePhone.Text;
                retail.Location    = txtLocation.Text;
                retail.IsActive    = chkIsActive.Checked;
                if (lblRetailID.Value != string.Empty)
                {
                    retail.RetailID = int.Parse(lblRetailID.Value);
                }
                ViewState.Add("lblRetailName", retail.Name);
                lblRetailName.Text = retail.Name;


                int status = retail.RetailID == 0 ? new RetailBL().Insert(retail) : new RetailBL().Update(retail);

                setMessage("Prodajno mesto uspešno sačuvano", System.Drawing.Color.Green, true, "success");
            }
            catch (Exception ex)
            {
                setMessage(ex.Message, System.Drawing.Color.Red, true, "danger");
            }
        }
Example #3
0
        public decimal GetNoMoney(ConsumeInfo consumeInfo, Retail retail)
        {
            //不找零的消费 积分+储值+抹除+优惠券+店铺活动优惠
            var holy = consumeInfo.Score + consumeInfo.CardMoney + consumeInfo.Erase + retail.CouponConsume + retail.StoreActivityDiscount;

            return(holy);
        }
Example #4
0
        private void btnCalculate_Click(object sender, EventArgs e)
        {
            // Text box one Retail price
            double wholeSale;
            // variable we will use to convert
            double percent;
            // Output variable
            double Retail;

            try
            {
                // Variable equal to the text box
                wholeSale = double.Parse(tbWholeSalePrice.Text);
                percent   = double.Parse(tbMarkupPercent.Text);
                // Variable is pulled from my class
                Retail = WholeSaleToRetail.CalculateRetail(wholeSale, percent);
                // Output to list box
                lbRetailPrice.Items.Add(Retail.ToString("c"));
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #5
0
 private static void alPatruleaScenariu()
 {
     using (var context = new BusinessContext())
     {
         var business = new Business
         {
             Name          = "Corner Dry Cleaning",
             LicenseNumber = "100x1"
         };
         context.Businesses.Add(business);
         var retail = new Retail
         {
             Name          = "Shop and Save",
             LicenseNumber =
                 "200C",
             Address = "101 Main",
             City    = "Anytown",
             State   = "TX",
             ZIPCode = "76106"
         };
         context.Businesses.Add(retail);
         var web = new eCommerce
         {
             Name          = "BuyNow.com",
             LicenseNumber =
                 "300AB",
             URL = "www.buynow.com"
         };
         context.Businesses.Add(web);
         context.SaveChanges();
     }
     using (var context = new BusinessContext())
     {
         Console.WriteLine("\n--- All Businesses ---");
         foreach (var b in context.Businesses)
         {
             Console.WriteLine("{0} (#{1})", b.Name, b.LicenseNumber);
         }
         Console.WriteLine("\n--- Retail Businesses ---");
         foreach (var r in context.Businesses.OfType <Retail>())
         {
             Console.WriteLine("{0} (#{1})", r.Name, r.LicenseNumber);
             Console.WriteLine("{0}", r.Address);
             Console.WriteLine("{0}, {1} {2}", r.City, r.State, r.ZIPCode);
         }
         Console.WriteLine("\n--- eCommerce Businesses ---");
         foreach (var e in context.Businesses.OfType <eCommerce>())
         {
             Console.WriteLine("{0} (#{1})", e.Name, e.LicenseNumber);
             Console.WriteLine("Online address is: {0}", e.URL);
         }
     }
     Console.ReadLine();
 }
    private IEnumerator LoadRetailJobLimits()
    {
        UnityWebRequest www = UnityWebRequest.Get("http://18.223.239.177/hello/getretail/" + DB.GameCode);

        yield return(www.SendWebRequest());

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            JsonData = www.downloadHandler.text;
            retail   = JsonUtility.FromJson <Retail>(JsonData);
            {
                int max = -1;
                if (retail.CEOMD > max)
                {
                    max = retail.CEOMD;
                }
                if (retail.brand.Associate > max)
                {
                    max = retail.brand.Associate;
                }
                if (retail.brand.Director > max)
                {
                    max = retail.brand.Director;
                }
                if (retail.brand.Manager > max)
                {
                    max = retail.brand.Manager;
                }
                if (retail.merchandise.MD > max)
                {
                    max = retail.merchandise.MD;
                }
                if (retail.merchandise.MM > max)
                {
                    max = retail.merchandise.MM;
                }
                if (retail.merchandise.VM > max)
                {
                    max = retail.merchandise.VM;
                }
                retail.total_upper = max;
                // sending data here...
                StartCoroutine(SendRetailJobLimits());
            }
        }
    }
Example #7
0
        public float GetScore(ConsumeInfo consumeInfo, Retail retail, ScoreRule scoreRule)
        {
            if (scoreRule == null || scoreRule.ConsumeUnit <= 0 || scoreRule.ScoreUnit <= 0)
            {
                return(0);
            }
            var payMoney = consumeInfo.ConsumeCoun - GetNoMoney(consumeInfo, retail);

            // 消费/积分比例
            float unitConsu = scoreRule.ConsumeUnit;
            float unitScore = scoreRule.ScoreUnit;
            var   score     = (float)Math.Round(payMoney) / unitConsu * unitScore;

            return(score);
        }
        private void dgRetail_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (dgRetail.SelectedItem != null)
            {
                cbComuna.ItemsSource = null;
                cbRegion.ItemsSource = null;
                Retail r = (Retail)dgRetail.SelectedItem;
                txtRut.Text         = r.RutRetail;
                txtNombre.Text      = r.NombreRetail;
                txtRazonSocial.Text = r.RazonSocial;
                txtTelefono.Text    = r.Telefono.ToString();
                txtEmail.Text       = r.Email;
                txtDireccion.Text   = r.Direccion;

                ServiceReference1.Service1Client proxy = new ServiceReference1.Service1Client();
                string            jsonS = proxy.ReadAllRegiones();
                RegionCollections reCol = new RegionCollections(jsonS);
                cbRegion.DisplayMemberPath = "Nombre";
                cbRegion.SelectedValuePath = "IdRegion";
                cbRegion.ItemsSource       = reCol.ToList();

                for (int i = 0; i < cbRegion.Items.Count; i++)
                {
                    Region re = (Region)cbRegion.Items[i];
                    if (re.IdRegion == r.IdRegion)
                    {
                        cbRegion.SelectedIndex = i;
                    }
                }


                string            json   = proxy.ReadAllComuna();
                ComunaCollections comCol = new ComunaCollections(json);
                cbComuna.DisplayMemberPath = "Nombre";
                cbComuna.SelectedValuePath = "IdComuna";
                cbComuna.ItemsSource       = comCol.ToList();

                for (int i = 0; i < cbComuna.Items.Count; i++)
                {
                    Comuna co = (Comuna)cbComuna.Items[i];
                    if (co.IdComuna == r.IdComuna)
                    {
                        cbComuna.SelectedIndex = i;
                    }
                }
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection  con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=E:\WindowsFormsApp1\WindowsFormsApp1\Database1.mdf;Integrated Security=True");
            SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From LoginDatabase where Username = '******' and Password = '******'", con);
            DataTable      dt  = new DataTable();

            sda.Fill(dt);
            if (dt.Rows[0][0].ToString() == "1")
            {
                this.Hide();
                Retail r = new Retail();
                r.Show();
            }
            else
            {
                MessageBox.Show("Please Check Your Username or Password!");
            }
        }
Example #10
0
        static void Main(string[] args)
        {
            // Scenario 1
            Console.WriteLine("Scenario 1");
            using (var context = new ModelSelfReference())
            {
                context.Database.ExecuteSqlCommand("DELETE FROM [SelfReferences]");
                context.SelfReferences.Add(new SelfReference
                {
                    Name = "Test"
                });
                context.SaveChanges();

                context.SelfReferences.Add(new SelfReference
                {
                    Name = "Test2",
                    ParentSelfReference = context.SelfReferences.FirstOrDefault()
                });
                context.SaveChanges();
            }

            using (var context = new ModelSelfReference())
            {
                foreach (var p in context.SelfReferences)
                {
                    Console.WriteLine("{0} {1} {2}", p.SelfReferenceId, p.Name, p.ParentSelfReferenceId);
                }
            }

            // Scenario 2
            Console.WriteLine("\nScenario 2");
            using (var context = new ModelSelfReference())
            {
                context.Database.ExecuteSqlCommand("DELETE FROM [BazaDeDate].[ProductWebInfo]");
                context.SaveChanges();
                context.Database.ExecuteSqlCommand("DELETE FROM [BazaDeDate].[Product]");

                var product = new Product
                {
                    SKU         = 147,
                    Description = "Expandable Hydration Pack",
                    Price       = 19.97M,
                    ImageURL    = "/pack147.jpg"
                };
                context.Products.Add(product);
                product = new Product
                {
                    SKU         = 178,
                    Description = "Rugged Ranger Duffel Bag",
                    Price       = 39.97M,
                    ImageURL    = "/pack178.jpg"
                };
                context.Products.Add(product);
                product = new Product
                {
                    SKU         = 186,
                    Description = "Range Field Pack",
                    Price       = 98.97M,
                    ImageURL    = "/noimage.jp"
                };
                context.Products.Add(product);
                product = new Product
                {
                    SKU         = 202,
                    Description = "Small Deployment Back Pack",
                    Price       = 29.97M,
                    ImageURL    = "/pack202.jpg"
                };
                context.Products.Add(product);
                context.SaveChanges();
            }

            using (var context = new ModelSelfReference())
            {
                foreach (var p in context.Products)
                {
                    Console.WriteLine("{0} {1} {2} {3}", p.SKU, p.Description,
                                      p.Price.ToString("C"), p.ImageURL);
                }
            }

            // scenario 3 example
            Console.WriteLine("\nScenario 3");
            byte[] thumbBits = new byte[100];
            byte[] fullBits  = new byte[2000];
            using (var context = new ModelSelfReference())
            {
                var photo = new Photograph
                {
                    Title         = "My Dog",
                    ThumbnailBits = thumbBits
                };
                var fullImage = new PhotographFullImage
                {
                    HighResolutionBits =
                        fullBits
                };
                photo.PhotographFullImage = fullImage;
                context.Photographs.Add(photo);
                context.SaveChanges();
            }

            using (var context = new ModelSelfReference())
            {
                foreach (var photo in context.Photographs)
                {
                    Console.WriteLine("Photo: {0}, ThumbnailSize {1} bytes",
                                      photo.Title, photo.ThumbnailBits.Length);
                    context.Entry(photo)
                    .Reference(p => p.PhotographFullImage).Load();
                    Console.WriteLine("Full Image Size: {0} bytes",
                                      photo.PhotographFullImage.HighResolutionBits.Length);
                }
            }

            // Scenario 4
            Console.WriteLine("\n Scenario 4");
            using (var context = new ModelSelfReference())
            {
                var business = new Business
                {
                    Name          = "Corner Dry Cleaning",
                    LicenseNumber = "100x1"
                };
                context.Businesses.Add(business);
                var retail = new Retail
                {
                    Name          = "Shop and Save",
                    LicenseNumber =
                        "200C",
                    Address = "101 Main",
                    City    = "Anytown",
                    State   = "TX",
                    ZIPCode = "76106"
                };
                context.Businesses.Add(retail);
                var web = new ECommerce
                {
                    Name          = "BuyNow.com",
                    LicenseNumber =
                        "300AB",
                    URL = "www.buynow.com"
                };
                context.Businesses.Add(web);
                context.SaveChanges();
            }

            using (var context = new ModelSelfReference())
            {
                Console.WriteLine("\n--- All Businesses ---");
                foreach (var b in context.Businesses)
                {
                    Console.WriteLine("{0} (#{1})", b.Name, b.LicenseNumber);
                }
                Console.WriteLine("\n--- Retail Businesses ---");
                foreach (var r in context.Businesses.OfType <Retail>())
                {
                    Console.WriteLine("{0} (#{1})", r.Name, r.LicenseNumber);
                    Console.WriteLine("{0}", r.Address);
                    Console.WriteLine("{0}, {1} {2}", r.City, r.State, r.ZIPCode);
                }
                Console.WriteLine("\n--- eCommerce Businesses ---");
                foreach (var e in context.Businesses.OfType <ECommerce>())
                {
                    Console.WriteLine("{0} (#{1})", e.Name, e.LicenseNumber);
                    Console.WriteLine("Online address is: {0}", e.URL);
                }
            }

            // Scenario 5
            Console.WriteLine("\nScenario 5");
            using (var context = new ModelSelfReference())
            {
                var fte = new FullTimeEmployee
                {
                    FirstName = "Jane",
                    LastName  =
                        "Doe",
                    Salary = 71500M
                };
                context.Employees.Add(fte);
                fte = new FullTimeEmployee
                {
                    FirstName = "John",
                    LastName  = "Smith",
                    Salary    = 62500M
                };
                context.Employees.Add(fte);
                var hourly = new HourlyEmployee
                {
                    FirstName = "Tom",
                    LastName  =
                        "Jones",
                    Wage = 8.75M
                };
                context.Employees.Add(hourly);
                context.SaveChanges();
            }
            using (var context = new ModelSelfReference())
            {
                Console.WriteLine("--- All Employees ---");
                foreach (var emp in context.Employees)
                {
                    bool fullTime = emp is HourlyEmployee ? false : true;
                    Console.WriteLine("{0} {1} ({2})", emp.FirstName, emp.LastName,
                                      fullTime ? "Full Time" : "Hourly");
                }
                Console.WriteLine("--- Full Time ---");
                foreach (var fte in context.Employees.OfType <FullTimeEmployee>())
                {
                    Console.WriteLine("{0} {1}", fte.FirstName, fte.LastName);
                }
                Console.WriteLine("--- Hourly ---");
                foreach (var hourly in context.Employees.OfType <HourlyEmployee>())
                {
                    Console.WriteLine("{0} {1}", hourly.FirstName,
                                      hourly.LastName);
                }
            }
        }
        public ActionResult List()
        {
            GridRequest gr = new GridRequest(Request);
            Expression <Func <RetailItem, bool> > predict = FilterHelper.GetExpression <RetailItem>(gr.FilterGroup);
            var retailsAll = _retailItemContract.RetailItems.Where(predict).Select(c => new
            {
                c.Id,
                //c.OutStorage.StorageName,
                c.OutStorageIds,
                c.CreatedTime,
                c.Product.ProductNumber,
                c.ProductRetailPrice,
                c.RetailCount,
                c.RetailId,
                c.Retail.RetailNumber,
                c.IsDeleted,
                c.IsEnabled
            }).GroupBy(x => x.RetailId).Select(x => new
            {
                CreateTime = x.Max(t => t.CreatedTime),
                x
            }).OrderByDescending(c => c.CreateTime);


            var           retails = retailsAll.Skip(gr.PageCondition.PageIndex).Take(gr.PageCondition.PageSize).ToList();
            List <object> li      = new List <object>();

            foreach (var reta in retails)
            {
                Retail reail = _retailContract.Retails.FirstOrDefault(c => c.Id == reta.x.Key);
                li.Add(new
                {
                    ParentId     = "",
                    StoreId      = "",
                    MemberNum    = reail.Consumer.UniquelyIdentifies,
                    Id           = "par" + reta.x.Key,
                    RetailNumber = reail.RetailNumber,
                    //reail.Operator.AdminName,
                    AdminName     = reail.OperatorId,
                    CreateTime    = reail.CreatedTime.ToString("yyyy-MM-dd hh:mm"),
                    RetailPrice   = "",
                    RetailCount   = "",
                    ProductNumber = "",
                    StorageName   = "",
                    reail.IsEnabled,
                    reail.IsDeleted
                });
                var child = reta.x.Select(c => new
                {
                    c.Id,
                    ParentId     = "par" + reta.x.Key,
                    MemberNum    = "",
                    RetailNumber = "",
                    AdminName    = "",
                    CreateTime   = "",
                    RetailPrice  = c.ProductRetailPrice,
                    RetailCount  = c.RetailCount,
                    c.ProductNumber,
                    StorageName = GetStorageNames(c.OutStorageIds),
                    c.IsDeleted,
                    c.IsEnabled
                });
                li.AddRange(child);
            }
            GridData <object> data = new GridData <object>(li, retailsAll.Count(), gr.RequestInfo);

            return(Json(data));
        }
Example #12
0
 public void AddToRetails(Retail retail)
 {
     base.AddObject("Retails", retail);
 }
Example #13
0
 public static Retail CreateRetail(string productId, string state, bool inStock, decimal price)
 {
     Retail retail = new Retail();
     retail.ProductId = productId;
     retail.State = state;
     retail.InStock = inStock;
     retail.Price = price;
     return retail;
 }
Example #14
0
    // Start is called before the first frame update
    void Start()
    {
        Dictionary <int, OSMObject>         elements;
        Dictionary <int, OSMObject>         townElements;
        Dictionary <string, Town>           towns       = new Dictionary <string, Town> ();
        Dictionary <string, List <Retail> > retailAreas = new Dictionary <string, List <Retail> > ();
        List <OSMObject> objects;
        List <OSMObject> townObjs;

        //List<Building> houses;
        maxlat  = minlat + height;
        maxlon  = minlon + width;
        unitlat = (maxlat - minlat) / 32;
        unitlon = (maxlon - minlon) / (32 * (width / height));

        //WebRequest request = WebRequest.Create ("https://overpass-api.de/api/interpreter?data=[out:json];node(41.77,-87.95,41.82,-87.9);out;");
        //HttpWebResponse response = (HttpWebResponse) request.GetResponse ();
        using (WebClient wc = new WebClient()) {
            //string query = String.Format ("https://overpass-api.de/api/interpreter?data=[out:json];node({0},{1},{2},{3});out;", minlat, minlon, maxlat, maxlon);
            string query     = String.Format("https://overpass-api.de/api/interpreter?data=[out:json];way[landuse=retail]({0},{1},{2},{3});(._;>;);out;", minlat, minlon, maxlat, maxlon);
            string townQuery = String.Format("https://overpass-api.de/api/interpreter?data=[out:json][bbox:{0}, {1}, {2}, {3}];relation[admin_level=8];>>;out;", minlat, minlon, maxlat, maxlon);
            string json      = wc.DownloadString(query);
            string townJson  = wc.DownloadString(townQuery);
            townJson = townJson.Replace("\"ref\"", "\"id\"");
            OSMelements data = JsonUtility.FromJson <OSMelements> (json);

            OSMelements townData = JsonUtility.FromJson <OSMelements> (townJson);
            print(query);
            objects      = data.elements;
            townObjs     = townData.elements;
            elements     = data.elements.ToDictionary(x => x.id, x => x);
            townElements = townData.elements.ToDictionary(x => x.id, x => x);
        }
        int misses  = 0;
        int queries = 0;
        List <OSMObject> toRemove = new List <OSMObject> ();

        //houses = new List<Building> ();
        foreach (OSMObject o in objects)
        {
            if (o.type != "way")
            {
                continue;
            }
            o.nodeRefs = new List <OSMObject> ();

            foreach (int i in o.nodes)
            {
                queries++;
                if (elements.ContainsKey(i))
                {
                    o.nodeRefs.Add(elements[i]);
                }
                else
                {
                    misses++;
                    toRemove.Add(o);
                    break;
                }
            }
        }
        objects.RemoveAll(x => toRemove.Contains(x));
        toRemove = new List <OSMObject> ();
        foreach (OSMObject o in townObjs)
        {
            if (o.type == "relation")
            {
                o.wayRefs = new List <OSMObject> ();
                print(o.members.Count);
                print(o.members[0].id);
                foreach (OSMObject i in o.members)
                {
                    queries++;
                    if (townElements.ContainsKey(i.id))
                    {
                        o.wayRefs.Add(townElements[i.id]);
                    }
                    else
                    {
                        print(String.Format("way {0} not here", i.id));
                        misses++;
                        toRemove.Add(o);
                        break;
                    }
                }
            }
            else if (o.type == "way")
            {
                o.nodeRefs = new List <OSMObject> ();

                foreach (int i in o.nodes)
                {
                    queries++;
                    if (townElements.ContainsKey(i))
                    {
                        o.nodeRefs.Add(townElements[i]);
                    }
                    else
                    {
                        print(String.Format("node {0} not here", i));
                        misses++;
                        toRemove.Add(o);
                        break;
                    }
                }
            }
        }
        townObjs.RemoveAll(x => toRemove.Contains(x));
        foreach (OSMObject t in townObjs)
        {
            //print(t.type);
            if (t.type != "relation")
            {
                continue;
            }
            print("RELATION");
            Town town;
            if (!towns.ContainsKey(t.tags.name))
            {
                towns[t.tags.name] = new Town(-1, -1, t.tags.name);
            }
            town = towns[t.tags.name];
            foreach (OSMObject o in t.wayRefs)
            {
                if (o.type != "way")
                {
                    print(o.type);
                    continue;
                }
                print("inner way has these many nodes:");
                print(o.nodeRefs.Count);
                print(o.nodes.Count);
                //print (String.Format ("instantiating at {0}, {1}", (o.nodeRefs[0].lat - minlat) / unitlat, (o.nodeRefs[0].lon - minlon) / unitlon));
                //Building h = new Building (o, latToY (o.nodeRefs[0].lat), lonToX (o.nodeRefs[0].lon));
                foreach (OSMObject n in o.nodeRefs)
                {
                    if (town.x1 == -1 || town.x1 > lonToX(n.lon))
                    {
                        town.x1 = lonToX(n.lon);
                        print(String.Format("{0} -> {1}", n.lon, lonToX(n.lon)));
                    }
                    if (town.x2 == -1 || town.x2 < lonToX(n.lon))
                    {
                        town.x2 = lonToX(n.lon);
                        print(String.Format("{0} -> {1}", n.lon, lonToX(n.lon)));
                    }
                    if (town.y1 == -1 || town.y1 > latToY(n.lat))
                    {
                        town.y1 = latToY(n.lat);
                        print(String.Format("{0} -> {1}", n.lat, latToY(n.lat)));
                    }
                    if (town.y2 == -1 || town.y2 < latToY(n.lat))
                    {
                        town.y2 = latToY(n.lat);
                        print(String.Format("{0} -> {1}", n.lat, latToY(n.lat)));
                    }
                }
            }
            print(String.Format("town: {0}, x1={1}, x2={2}, y1={3}, y2={4}", town.name, town.x1, town.x2, town.y1, town.y2));
            var vertices2 = new Vector2[] {
                new Vector2(town.x1, town.y1),
                new Vector2(town.x2, town.y1),
                new Vector2(town.x2, town.y2),
                new Vector2(town.x1, town.y2)
            };

            /*
             *          for (int i = 0; i < o.nodeRefs.Count - 1; i++) {
             *              OSMObject n = o.nodeRefs[i];
             *              vertices2[i] = new Vector2 (lonToX (n.lon), latToY (n.lat));
             *              OSMObject ni = o.nodeRefs[i + 1];
             *              Debug.DrawLine (new Vector3 (lonToX (n.lon), latToY (n.lat), 0), new Vector3 (lonToX (ni.lon), latToY (ni.lat)), w.tags.landuse == "commercial" || w.tags.landuse == "retail" ? Color.white :
             *                  w.tags.landuse == "grass" ? Color.green :
             *                  Color.cyan, 300, false);
             *          }*/
            var vertices3    = System.Array.ConvertAll <Vector2, Vector3> (vertices2, v => new Vector3(v.x, v.y, 12));
            var triangulator = new Triangulator(vertices2);
            var indices      = triangulator.Triangulate();
            var colors       = Enumerable.Range(0, vertices3.Length)
                               .Select(i => UnityEngine.Color.blue)
                               .ToArray();
            var mesh = new Mesh {
                vertices  = vertices3,
                triangles = indices,
                colors    = colors
            };
            mesh.RecalculateNormals();
            mesh.RecalculateBounds();
            var obj = Instantiate(TownGO, new Vector3(0, 0, 0), Quaternion.identity);
            obj.name = town.name;
            var meshRenderer = obj.AddComponent <MeshRenderer> ();
            meshRenderer.material = new Material(Shader.Find("Sprites/Default"));
            var filter = obj.AddComponent <MeshFilter> ();
            filter.mesh = mesh;
        }
        foreach (OSMObject o in objects)
        {
            if (o.type != "way")
            {
                continue;
            }
            var vertices2 = new Vector2[o.nodeRefs.Count - 1];

            for (int i = 0; i < o.nodeRefs.Count - 1; i++)
            {
                OSMObject n = o.nodeRefs[i];
                vertices2[i] = new Vector2(lonToX(n.lon), latToY(n.lat));
                OSMObject ni = o.nodeRefs[i + 1];

                /*Debug.DrawLine (new Vector3 (lonToX (n.lon), latToY (n.lat), 0), new Vector3 (lonToX (ni.lon), latToY (ni.lat)), o.tags.landuse == "commercial" || o.tags.landuse == "retail" ? Color.white :
                 *  o.tags.landuse == "grass" ? Color.green :
                 *  Color.cyan, 300, false);*/
            }
            var vertices3    = System.Array.ConvertAll <Vector2, Vector3> (vertices2, v => new Vector3(v.x, v.y, 0));
            var triangulator = new Triangulator(vertices2);
            var indices      = triangulator.Triangulate();
            var colors       = Enumerable.Range(0, vertices3.Length)
                               .Select(i => (o.tags.landuse == "retail" ? UnityEngine.Color.green : UnityEngine.Color.yellow))
                               .ToArray();
            var mesh = new Mesh {
                vertices  = vertices3,
                triangles = indices,
                colors    = colors
            };
            mesh.RecalculateNormals();
            mesh.RecalculateBounds();
            var     obj = Instantiate(TownGO, new Vector3(0, 0, 0), Quaternion.identity);
            Vector2 avg = averageVector(vertices2);
            Town    t   = closestTown(avg.x, avg.y, towns.Values.ToList());
            Retail  r   = new Retail(o, avg.x, avg.y, obj);
            if (!retailAreas.ContainsKey(t.name))
            {
                retailAreas[t.name] = new List <Retail> ();
            }
            retailAreas[t.name].Add(r);
            obj.name = String.Format("{0}-{1}-{2}", t.name, avg.x, avg.y);
            var meshRenderer = obj.AddComponent <MeshRenderer> ();
            meshRenderer.material = new Material(Shader.Find("Sprites/Default"));
            var filter = obj.AddComponent <MeshFilter> ();
            filter.mesh = mesh;
        }

        foreach (Town t in towns.Values.ToList())
        {
            if (!retailAreas.ContainsKey(t.name))
            {
                continue;
            }

            print(String.Format("{0} downtown:", t.name));
            List <Retail> downtown = removeOutliers(retailAreas[t.name]);
            print(String.Format("\t{0} areas", downtown.Count));
            foreach (Retail r in downtown)
            {
                var     filter = (MeshFilter)r.o.GetComponent("MeshFilter");
                var     mesh   = filter.mesh;
                Color[] colors = new Color[mesh.vertices.Length];
                for (int m = 0; m < colors.Length; m++)
                {
                    colors[m] = Color.white;
                }
                mesh.colors = colors;
            }
        }
        print(String.Format("{0} queries, {1} misses", queries, misses));
        print(String.Format("{0} objects", objects.Count));
    }
        private async void btnEjecutar_Click(object sender, RoutedEventArgs e)
        {
            lblNombre.Content      = validador.validarNombre(txtNombre.Text);
            lblEmail.Content       = validador.validarCorreo(txtEmail.Text);
            lblRazonSocial.Content = validador.validarRazonSocial(txtRazonSocial.Text);
            lblRut.Content         = validador.validarRut(txtRut.Text);

            Retail ret = new Retail();

            ServiceReference1.Service1Client proxy = new ServiceReference1.Service1Client();
            if (cbComuna.SelectedIndex.Equals(-1))
            {
                lblComuna.Content    = "Seleccione una opcion";
                lblComuna.Visibility = Visibility.Visible;
            }

            if (lblRut.Content.Equals("OK") && lblNombre.Content.Equals("OK") && lblRazonSocial.Content.Equals("OK") && lblEmail.Content.Equals("OK"))
            {
                lblEmail.Visibility = Visibility.Hidden;
                string json;
                switch (btnEjecutar.Content.ToString())
                {
                case "Agregar":

                    ret.RutRetail    = txtRut.Text;
                    ret.NombreRetail = txtNombre.Text;
                    ret.RazonSocial  = txtRazonSocial.Text;
                    int tele;
                    int.TryParse(txtTelefono.Text, out tele);
                    ret.Telefono  = tele;
                    ret.Email     = txtEmail.Text;
                    ret.Direccion = txtDireccion.Text;
                    ret.IdRegion  = (int)cbRegion.SelectedValue;
                    ret.IdComuna  = (int)cbComuna.SelectedValue;

                    json = ret.Serializar();
                    if (proxy.CrearRetail(json))
                    {
                        await this.ShowMessageAsync("Exito", "Retail creado");

                        LimpiarControles();
                    }
                    else
                    {
                        await this.ShowMessageAsync("Error", "No se a podido crear");

                        LimpiarControles();
                    }

                    break;

                case "Modificar":

                    ret.RutRetail    = txtRut.Text;
                    ret.NombreRetail = txtNombre.Text;
                    ret.RazonSocial  = txtRazonSocial.Text;
                    int tel;
                    int.TryParse(txtTelefono.Text, out tel);
                    ret.Telefono  = tel;
                    ret.Email     = txtEmail.Text;
                    ret.Direccion = txtDireccion.Text;
                    ret.IdRegion  = (int)cbRegion.SelectedValue;
                    ret.IdComuna  = (int)cbComuna.SelectedValue;
                    Retail id = (Retail)dgRetail.SelectedItem;
                    ret.IdRetail = id.IdRetail;
                    json         = ret.Serializar();
                    if (proxy.ActualizarRetail(json))
                    {
                        await this.ShowMessageAsync("Exito", "Retail actualizado");

                        LimpiarControles();
                    }
                    else
                    {
                        await this.ShowMessageAsync("Error", "No se a podido actualizar");

                        LimpiarControles();
                    }
                    break;

                case "Eliminar":

                    Retail r = (Retail)dgRetail.SelectedValue;
                    json = r.Serializar();
                    if (proxy.EliminarRetail(json))
                    {
                        await this.ShowMessageAsync("Exito", "Retail eliminado");

                        LimpiarControles();
                    }
                    else
                    {
                        await this.ShowMessageAsync("Error", "No se a podido eliminar");

                        LimpiarControles();
                    }

                    break;

                default:
                    break;
                }
            }
            else
            {
                if (lblEmail.Content.Equals("OK"))
                {
                    lblEmail.Visibility = Visibility.Hidden;
                }
                else
                {
                    lblEmail.Visibility = Visibility.Visible;
                }

                if (lblRazonSocial.Content.Equals("OK"))
                {
                    lblRazonSocial.Visibility = Visibility.Hidden;
                }
                else
                {
                    lblRazonSocial.Visibility = Visibility.Visible;
                }

                if (lblNombre.Content.Equals("OK"))
                {
                    lblNombre.Visibility = Visibility.Hidden;
                }
                else
                {
                    lblNombre.Visibility = Visibility.Visible;
                }

                if (lblRut.Content.Equals("OK"))
                {
                    lblRut.Visibility = Visibility.Hidden;
                }
                else
                {
                    lblRut.Visibility = Visibility.Visible;
                }
            }
        }