public void LimpaCallBack()
        {
            ConstruirEF cf = new ConstruirEF();
            NSAADMEntities n = (NSAADMEntities)cf.RecuperaEntity(Entities.MercadoLivre);

            List<CallBackML> x = (from p in n.CallBackMLs where p.topic == "questions" select p).ToList();

            foreach (CallBackML item in x)
            {
                try
                {
                    decimal cod;

                    cod = Convert.ToDecimal(item.resource.Replace("/questions/",""));

                    var b = (from p in n.ML_Question where p.id_question == cod select p ).First();

                    n.CallBackMLs.DeleteObject(item);

                }
                catch (Exception)
                {

                }

                n.SaveChanges();

            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ConstruirEF cf = new ConstruirEF();
                n = (NSAADMEntities)cf.RecuperaEntity(Entities.MercadoLivre);

                var um = (from ito in n.ML_ItemOrganizacao
                          join it in n.ML_Item on ito.id equals it.id_org
                          join ordit in n.ML_OrderItem on it.id equals ordit.id_item
                          join ord in n.ML_Order on ordit.id_order equals ord.id
                          join fd in n.ML_FeedbackSeller on ord.id equals fd.id_order
                         where fd.id_order == ord.id
                            && fd.rating == "positive"
                        select new { DescrItem = ito.Descricao, ValorOrdem = ord.total_amount });

                var dois = (from p in um group p by p.DescrItem into umg select new { ItemDesc = umg.Key, Qtd = umg.Count(), TotalBruto = umg.Sum(x => x.ValorOrdem), TotalLiquido = (umg.Sum(x1 => x1.ValorOrdem) * COMISSAO_ML) });

                GridView1.DataSource = dois;
                GridView1.DataBind();

                Label1.Text = String.Format("Total de valor recebido: {0}",dois.Sum(x => x.TotalLiquido));

            }
        }
        protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
        {
            ConstruirEF cf = new ConstruirEF();
            NSAADMEntities n = (NSAADMEntities)cf.RecuperaEntity(Entities.MercadoLivre);

            try
            {
                var u = (from p in n.UsuarioAdms where p.nome == Login1.UserName && p.senha == Login1.Password select p).First();

                e.Authenticated = true;
                FormsAuthentication.RedirectFromLoginPage(Login1.UserName, false);

            }
            catch (Exception ex)
            {

                throw new Exception("Erro no login: Login1_Authenticate", ex);
            }

            //if ((Login1.UserName == "admin") && (Login1.Password == "123"))
            //{
            //    e.Authenticated = true;
            //    FormsAuthentication.RedirectFromLoginPage(Login1.UserName, false);
            //}
            //else
            //{
            //    e.Authenticated = false;
            //}
        }
        public bool VerificaUser(JToken t)
        {
            NSAADMEntities n;

            ConstruirEF cf = new ConstruirEF();
            n = (NSAADMEntities)cf.RecuperaEntity(Entities.MercadoLivre);

            try
            {
                decimal d = (decimal)t["id"];
                ML_Usuario pa = (from p in n.ML_Usuario where p.id == d select p).First();

                return true;

            }
            catch (InvalidOperationException)
            {
                if (t["nickname"].ToString() == "")
                {
                    return true;
                }
                else
                {
                    return false;
                }

            }
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!Page.IsPostBack)
     {
         ConstruirEF cf = new ConstruirEF();
         n = (NSAADMEntities)cf.RecuperaEntity(Entities.MercadoLivre);
     }
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {

                Meli m;
                string pg;

                string codigo = Request.QueryString["code"];

                if ((string)Session["pagina"] != null)
                {
                    pg = (string)Session["pagina"];
                }
                else
                {
                    pg = "InicioML.aspx";
                }

                if (Session["M"] == null)
                {
                    //m = new Meli(5971480328026573, "HvQavElFhrbqlGCaTMWIrtQklsqnwlIM");
                    m = new Meli(AplicacaoML.RetornaIDAplicacaoML(), AplicacaoML.RetornaKeyAplicacaoML());
                }
                else
                {
                    m = (Meli)Session["M"];
                }

                string redirectUrl = AplicacaoML.RetornaURLLoginAplicacaoML();// ServidorWeb.Properties.Settings.Default.URL_Login;
                m.Authorize(codigo, redirectUrl);

                Session["M"] = m;

                NSAADMEntities n;
                ConstruirEF cf = new ConstruirEF();
                n = (NSAADMEntities)cf.RecuperaEntity(Entities.MercadoLivre);
                DadosML d;

                d = (from p in n.DadosMLs where p.id == "Meli" select p).First();

                d.ClientSecret = AplicacaoML.RetornaKeyAplicacaoML(); // m.ClientSecret;
                d.ClientId = m.ClientId.ToString();
                d.AccessToken = m.AccessToken;
                d.RefreshToken = m.RefreshToken;

                n.SaveChanges();

                Response.Redirect(pg, false);

            }
            catch (Exception ex)
            {

                throw new Exception ("Erro no load do login.aspx", ex) ;
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {

                int cont = 0;
                ConstruirEF cef = new ConstruirEF();
                NSAADMEntities n = (NSAADMEntities)cef.RecuperaEntity(Entities.MercadoLivre);
                ConverterObjetoMLparaEF cf = new ConverterObjetoMLparaEF();
                Usuario u = cm.RetornaUsuario();
                ConverterObjetoMLparaEF c = new ConverterObjetoMLparaEF();
                ListOrder o;
                ML_Order Ordem;

                ConverteVendas cv = new ConverteVendas();
                GerenciarVendas gv = new GerenciarVendas();
                NSAADM_HMLEntities ent = new NSAADM_HMLEntities();

                do
                {
                    o = cm.RetornarOrdens(u, cont);
                    cont = o.results.Count + cont;

                    foreach (Order or in o.results)
                    {
                        Ordem = (from p in n.ML_Order where p.id == or.id select p).FirstOrDefault();
                        if (Ordem == null)
                        {
                            Ordem = cf.ConverteOrdem(or, n);
                            n.ML_Order.AddObject(Ordem);

                            gv.IncluirVenda(cv.ConverteMLVendaEmVenda(Ordem, ent), ent);

                        }
                        else
                        {
                            cf.AtualizaOrdem(Ordem, or, n);

                            gv.IncluirVenda(cv.ConverteMLVendaEmVenda(Ordem, ent), ent);

                        }

                        n.SaveChanges();

                    }
                } while (o.results.Count == 50);

            }
            catch (Exception ex)
            {

                throw new Exception("Erro na rotina Button1_Click",ex);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            ConstruirEF cf = new ConstruirEF();
            n = (NSAADMEntities)cf.RecuperaEntity(Entities.MercadoLivre);

            Decimal codigo = Convert.ToDecimal(Request.QueryString["code"]);

            var x = (from p in n.MP_Payments where p.id == codigo select p);

            GridView1.DataSource = x;
            GridView1.DataBind();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            NSAADMEntities n;

            ConstruirEF cf = new ConstruirEF();
            n = (NSAADMEntities)cf.RecuperaEntity(Entities.MercadoLivre);

            //*****************************************
            Request.InputStream.Position = 0;
            System.IO.StreamReader str = new System.IO.StreamReader(Request.InputStream);

            CallBackTemp c = new CallBackTemp();
            c = JsonConvert.DeserializeObject<CallBackTemp>(str.ReadToEnd());
            //*****************************************

            try
            {
                CallBackML teste = (from p in n.CallBackMLs where p.resource == c.resource select p).First();

            }
            catch (Exception)
            {

                CallBackML call = new CallBackML();
                call.received = c.received;
                call.resource = c.resource;
                call.sent = c.sent;
                call.topic = c.topic;
                call.userID = c.user_id;

                n.CallBackMLs.AddObject(call);

                n.SaveChanges();

                if (c.topic == "questions")
                {
                    ControlaMeli cm = new ControlaMeli();

                    ControlaPerguntas cp = new ControlaPerguntas();

                    cp.GravaPergunta(cm.RetonarQuestion(c.resource), cm.n);
                }
                if (c.topic == "orders")
                {
                    ControlaMeli cm = new ControlaMeli();
                    ControlaOrdens co = new ControlaOrdens();
                    ConverterObjetoMLparaEF conv = new ConverterObjetoMLparaEF();
                    co.GravaOrdem(cm.RetornaOrder(c.resource),cm.n);

                }
            }
        }
 public ControlaMeli()
 {
     try
     {
         ConstruirEF cf = new ConstruirEF();
         n = (NSAADMEntities)cf.RecuperaEntity(Entities.MercadoLivre);
         d = (from p in n.DadosMLs where p.id == "Meli" select p).First();
         m = new Meli(Convert.ToInt64(d.ClientId), d.ClientSecret, d.AccessToken, d.RefreshToken);
     }
     catch (Exception ex)
     {
         throw new Exception(String.Format("Erro no New do ControlaMeli"), ex);
     }
 }
        public bool VerificaPay(JToken t)
        {
            NSAADMEntities n;

            ConstruirEF cf = new ConstruirEF();
            n = (NSAADMEntities)cf.RecuperaEntity(Entities.MercadoLivre);

            try
            {
                decimal d = (decimal)t["id"];
                MP_Payments pa = (from p in n.MP_Payments where p.id == d select p).First();
                return true;
            }
            catch (InvalidOperationException)
            {
                return false;

            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {

                ConstruirEF cf = new ConstruirEF();
                n = (NSAADMEntities)cf.RecuperaEntity(Entities.MercadoLivre);

                var x = (from p in n.ML_ItemOrganizacao select p);

                DropDownList1.Items.Clear();
                Label1.Text = "";
                Label2.Text = "";
                Label3.Text = "";

                DropDownList1.DataSource = x;
                DropDownList1.DataTextField = "descricao";
                DropDownList1.DataValueField = "id";

                DropDownList1.DataBind();

            }
        }
        private void InserirMOvimentos(JObject t)
        {
            NSAADMEntities n;

            ConstruirEF cf = new ConstruirEF();
            n = (NSAADMEntities)cf.RecuperaEntity(Entities.MercadoLivre);

            decimal temp;
            Nullable<DateTime> tempd;

            foreach (var item in t)
            {

                string a = item.ToString();

                JToken j = t["response"];

                JToken s = j["results"];

                foreach (var i in s)
                {
                    JToken b = i["collection"];

                    if (VerificaPay(b) == false)
                    {

                        MP_Payments p = new MP_Payments();

                        p.id = (decimal)b["id"];
                        p.last_modified = (DateTime)b["last_modified"];
                        p.marketplace = (string)b["marketplace"];

                        p.installments = b["installments"].ToString();

                        Decimal.TryParse(b["marketplace_fee"].ToString(), out temp);
                        p.marketplace_fee = temp;

                        Decimal.TryParse(b["mercadopago_fee"].ToString(), out temp);
                        p.mercadopago_fee = temp;

                        Decimal.TryParse(b["net_received_amount"].ToString(), out temp);
                        p.net_received_amount = temp;

                        Decimal.TryParse(b["collector_id"].ToString(), out temp);
                        p.collector_id = temp;

                        Decimal.TryParse(b["currency_id"].ToString(), out temp);
                        p.currency_id = temp;

                        Decimal.TryParse(b["external_reference"].ToString(), out temp);
                        p.external_reference = temp;

                        Decimal.TryParse(b["total_paid_amount"].ToString(), out temp);
                        p.total_paid_amount = temp;

                        Decimal.TryParse(b["transaction_amount"].ToString(), out temp);
                        p.transaction_amount = temp;

                        Decimal.TryParse(b["account_money_amount"].ToString(), out temp);
                        p.account_money_amount = temp;

                        Decimal.TryParse(b["shipping_cost"].ToString(), out temp);
                        p.shipping_cost = temp;

                        p.operation_type = (string)b["operation_type"];
                        p.payment_type = (string)b["payment_type"];
                        p.reason = (string)b["reason"];
                        p.released = (string)b["released"];

                        p.site_id = (string)b["site_id"];
                        p.sponsor_id = (string)b["sponsor_id"];
                        p.status = (string)b["status"];
                        p.status_code = (string)b["status_code"];
                        p.status_detail = (string)b["status_detail"];

                        tempd = (Nullable<DateTime>)b["date_approved"];
                        p.date_approved = tempd;
                        p.date_created = (DateTime)b["date_created"];

                        tempd = (Nullable<DateTime>)b["money_release_date"];
                        p.money_release_date = tempd;
                        //p.money_release_date = (DateTime)b["money_release_date"];

                        //USUARIO
                        JToken user = b["payer"];
                        if (VerificaUser(user) == false)
                        {
                            ML_Usuario u = new ML_Usuario();
                            Decimal.TryParse(user["id"].ToString(), out temp);
                            u.id = temp;
                            u.nickname = (string)user["nickname"];
                            u.first_name = (string)user["first_name"];
                            u.last_name = (string)user["last_name"];
                            u.email = (string)user["email"];

                            JToken phone = user["phone"];
                            ML_Phone phon = new ML_Phone();
                            phon.area_code = (string)phone["area_code"];
                            phon.number = (string)phone["number"];
                            phon.extension = (string)phone["extension"];

                            u.ML_Phone.Add(phon);

                            n.ML_Usuario.AddObject(u);
                        }

                        n.AddToMP_Payments(p);

                        n.SaveChanges();
                    }
                }

            }
        }