protected void cmbRemates_Select(object sender, DirectEventArgs e)
    {
      try
      {
        int id_remate = cmbRemates.SelectedItem.Value.ValidaEntero("Combo Remates");
        IList<co_rl_loteos> listLoteos = new bf_rl_loteos().GetData(new co_rl_loteos { id_remate = { id = id_remate } }).OrderBy(c => c.lo_numero).ToList();
        List<object> lista = new List<object>();
        if (listLoteos.Any())
        {
          foreach (co_rl_loteos lote in listLoteos)
          {
            lista.Add(new
            {
              id_loteo = lote.id_loteo,
              lo_numero = lote.lo_numero,
              lo_titulo = lote.lo_titulo,
              lo_descripcion = lote.lo_descripcion,
              fa_familia = lote.id_familia.descripcion,
              ca_categoria = lote.id_categoria.descripcion,
              subca_subcategoria = lote.id_subcategoria.descripcion,
              id_loteoestado = lote.id_loteoestado.descripcion
            });
          }
          btnCopiar.Disabled = false;
          strLotesRemate.RemoveAll();
          strLotesRemate.DataSource = lista;
          strLotesRemate.DataBind();

        }
      }
      catch (Exception ex)
      {
        Mensajes.Error(ex.Message);
      }
    }
    /// <summary>
    /// Metodo que me permite notificar al WebService de Tattersall Movil que se publicó un remate, 
    /// metodo solo para los Remate, NO para la Venta Directa
    /// </summary>
    /// <param name="remate">objeto remate que creó o publicó</param>
    public static void NotificarMovilRemate(co_re_remates remate)
    {
      try
      {
        getTransaccion();
        //1. valido si el remate a sido publicado
        if (remate.id_remateEstadoWeb.id == PUBLICADO)
        {
          //realizo la instancia del wsdl para la notificacion.
          WsNotificacion notificacion = new WsNotificacionClient();

          //obtengo todos los lotes del remate con la opcion de canal movil
          var lotes = new bf_rl_loteos().getLotesNotificacion(remate.id_remate, CANAL_MOVIL);
          if (!lotes.Any())
          {
            return;
          }
          string subcategoriasMovil = lotes.Aggregate(string.Empty, (current, lote) => current + lote.id_mosubcategoria + ",");
          if (subcategoriasMovil.Length > 0)
          {
            subcategoriasMovil = subcategoriasMovil.Substring(0, (subcategoriasMovil.Length - 1));
          }
          var usuariosWeb = new bf_ca_usuariosweb().getUsuariosSubcategoriasMovil(subcategoriasMovil);
          //verifico si hay usuario a los que notificar de lo contrario no hago nada
          if (usuariosWeb.Any())
          {
            string nombreCompleto = string.Empty;
            IList<Usuario> usuarios = new List<Usuario>();
            Publicacion publicacion = new Publicacion
            {
              esRemate = true,
              id = remate.id_remate,
              titulo = remate.rem_nombre
            };

            foreach (var usu in usuariosWeb)
            {
              int uuid = usu.id_usuarioWeb;
              nombreCompleto = usu.pe_nombrecompleto;
              usuarios.Add(new Usuario { uuid = uuid.ToString(), nombre = nombreCompleto });
            }
            publicacion.Usuarios = usuarios.ToArray();

            NotificarRequest notificarRequest = new NotificarRequest
            {
              DatosTransaccion = _transaccion,
              Publicacion = publicacion
            };

            NotificarResponse res = notificacion.Notificar(notificarRequest);
            GuardarResponseMovil(res, 0, remate.id_remate, publicacion);
          }
        }
      }
      catch (Exception)
      {
        //throw new Exception(ex.Message);
      }
    }
    public void ValidarExcel()
    {
      int id_remate = hid_idRemate.Text.ValidaEntero("id_remate");
      try {
        string nombreArchivo = Server.HtmlEncode(btnArchivo.FileName);
        string extension = System.IO.Path.GetExtension(nombreArchivo);
        string ruta = Request.PhysicalApplicationPath + FWPConfiguration.get_AppSettings("MatPathUpload").ToString() + Session.SessionID;

        if (extension.Equals(EXTENSION))
        {
          if (!System.IO.Directory.Exists(ruta))
          {
            System.IO.Directory.CreateDirectory(ruta);
          }
          ruta += "\\" + nombreArchivo;
          btnArchivo.PostedFile.SaveAs(ruta);
          IList<object> lista = new List<object>();
          RetornoMasiva datos = new bf_rl_loteos().ValidarExcelSAP(ruta,id_remate);
          if (!datos.EsValido)
          {
            foreach (ErrorMasiva rm in datos.listErrores)
            {
              lista.Add(new { tipo = rm.tipoError.ToString(), descripcion = rm.descripcion });
            }

            strErrores.DataSource = lista;
            strErrores.DataBind();
            btnCargarDatos.Disable();
          }
          else {
            if (datos.listLotesRepetidos.Count > 0) {
              strExcel.DataSource = datos.listLotesRepetidos;
              strExcel.DataBind();
            }
          }
        }
      }
      catch(Exception ex)
      {
        Mensajes.Error("Se produjo un Error al Validar el Excel", "wf_cargaMasivaLotesSAP.ValidarExcel[DirectMethod]",ex);
      }
    }
    private void CargarMasiva(HttpContext context)
    {
      string response = "";
      string idCarpeta = context.Request.Form["file-id_carpeta"];
      int idTabla = Constantes.TABLA_LOTES;

      List<int> numeroLotes = new List<int>();
      numeroLotes.AddRange(context.Request.Form["file-ids"].Split('*').Select(int.Parse).ToArray());

      foreach (int numero in numeroLotes)
      {
        co_rl_loteos lote = new co_rl_loteos();
        lote.lo_numero = numero;
        lote.id_remate.id = Convert.ToInt32(idCarpeta);
        IList<co_rl_loteos> lotes = new bf_rl_loteos().GetData(lote);

        if (lotes.Count == 1)
        {
          foreach (string key in context.Request.Files)
          {
            List<HttpPostedFile> imgs = new List<HttpPostedFile>();
            HttpPostedFile file = context.Request.Files[key] as HttpPostedFile;
            List<int> imgId = new List<int>();

            if (file != null && file.ContentLength == 0) continue;

            if (file != null && numero == NumeroLoteImagen(file.FileName))
            {
              int idOrigen = lotes.First().id;

              imgs.Add(file);
              imgId.Add(TipoImagen(file.FileName));
              string mensaje;
              response = !new bf_tg_imagenes().GuardaImagenesMasiva(idTabla, idOrigen, idCarpeta, imgId, imgs, out mensaje) ? mensaje : "ok";
            }
          }
        }
      }
      context.Response.Write(response);
    }
    protected void btnGuardar_Click(object sender, DirectEventArgs e)
    {
      try
      {
        string atributosParam = e.ExtraParams["atributos"];
        IList<JsonAtributos> atributos = JsonConvert.DeserializeObject<List<JsonAtributos>>(atributosParam);
        string atributosFamiliaParam = e.ExtraParams["atributosFamilia"];
        IList<JsonAtributos> atributosFamilia = JsonConvert.DeserializeObject<List<JsonAtributos>>(atributosFamiliaParam);
        string atributosCategoriaParam = e.ExtraParams["atributosCategoria"];
        IList<JsonAtributos> atributosCategoria = JsonConvert.DeserializeObject<List<JsonAtributos>>(atributosCategoriaParam);
        string atributosSubcategoriaParam = e.ExtraParams["atributosSubcategoria"];
        IList<JsonAtributos> atributosSubcategoria = JsonConvert.DeserializeObject<List<JsonAtributos>>(atributosSubcategoriaParam);
        co_rl_loteos lote = new co_rl_loteos();
        string detalle = e.ExtraParams["detalle"];
        string mensaje = ErrorText.REGISTRO_INGRESADO;

        int idLoteo = hid_id.Text.ValidaEntero("id_lote");
        if (idLoteo != 0)
        {
          lote = new bf_rl_loteos().GetData(idLoteo);
          mensaje = ErrorText.REGISTRO_MODIFICADO;
        }
        else
        {
          lote.id_remate.id = hid_idRemate.Text.ValidaEntero("id_remate");
        }

        lote.lo_codigo = txtCodigo.Text;
        lote.lo_numero = NumInt.Init(Numeros.QuitaPunteo(txtNroLote.Text));
        lote.lo_orden = NumInt.Init(Numeros.QuitaPunteo(txtNroLote.Text));
        lote.lo_cantidad = NumInt.Init(Numeros.QuitaPunteo(txtCantidad.Text));

        lote.lo_descripcion = txtDescripcion.Text.ToUpper();

        lote.lo_superficieConstruida = NumDec.Init(txtSuperficieConstruida.Text);
        lote.id_unidadConstruida.id =
          cmbUniMedSupConstruida.SelectedItem.Value.ValidaEntero(cmbUniMedSupConstruida.FieldLabel);
        lote.lo_superficieSitio = NumDec.Init(txtSuperficieSitio.Text);
        lote.id_unidadSitio.id = cmbUniMedSupSitio.SelectedItem.Value.ValidaEntero(cmbUniMedSupSitio.SelectedItem.Value);

        lote.lo_minimo = Numeros.QuitaPunteo(txtMinimo.Text).ValidaDecimal(txtMinimo.Text);
        lote.lo_iva = chkIva.Checked ? 1 : 0;
        lote.id_moneda.id = cmbMoneda.SelectedItem.Value.ValidaEntero(cmbMoneda.FieldLabel);
        lote.lo_unidad_medida = txtUnidadMedida.Text.ToUpper();
        lote.lo_comision = txtComision.Text;

        lote.lo_descripcionMonto = txtDescripcionMonto.Text.ToUpper();
        lote.lo_garantia = NumDec.Init(Numeros.QuitaPunteo(txtGarantia.Text));
        if (cmbMonedaGarantia.SelectedItem.Value != null)
        {
          lote.id_moneda_garantia.id = cmbMonedaGarantia.SelectedItem.Value.ValidaEntero(cmbMonedaGarantia.FieldLabel);
        }

        lote.id_loteoestado.id = cmbEstado.SelectedItem.Value.ValidaEntero(cmbEstado.FieldLabel);
        if (cmbMandantes.SelectedItem.Value != null)
        {
          lote.id_mandante.id = cmbMandantes.SelectedItem.Value.ValidaEntero(cmbMandantes.FieldLabel);
        }
        lote.id_familia.id = cmbFamilias.SelectedItem.Value.ValidaEntero(cmbFamilias.FieldLabel);
        lote.id_categoria.id = cmbCategoria.SelectedItem.Value.ValidaEntero(cmbCategoria.FieldLabel);
        lote.id_subcategoria.id = cmbSubCategoria.SelectedItem.Value.ValidaEntero(cmbSubCategoria.FieldLabel);

        lote.lo_direccion = txtDireccion.Text.ToUpper();
        lote.id_region.id = cmbRegion.SelectedItem.Value.ValidaEntero(cmbRegion.FieldLabel);
        lote.id_comuna.id = cmbComuna.SelectedItem.Value.ValidaEntero(cmbComuna.FieldLabel);
        lote.lo_latitud = txtLatitud.Text;
        lote.lo_longitud = txtLongitud.Text;

        lote.lo_lugar_exhibicion = txtLugarExhibicion.Text.ToUpper();
        lote.lo_exhibicion = txtExhibicion.Text.ToUpper();

        lote.lo_observacion = txtObservacion.Text.ToUpper();

        if (lote.id_remate_origen == 0)
        {
          lote.id_remate_origen = lote.id_remate.id;
        }

        if (lote.id_categoria.id == Constantes.CATEGORIA_VEHICULOS)
        {
          lote.lo_detalle = ConformarDetalle(atributosSubcategoria);
          lote.lo_titulo = ConformarNombre(atributosSubcategoria);
        }
        else
        {
          lote.lo_detalle = detalle;
          lote.lo_titulo = txtNombre.Text.ToUpper();
        }


        IList<co_rl_loteoscanales> canales = ObtenerCanales();
        IList<co_rl_incrementos> incrementos = ObtenerIncrementos();
        IList<co_tg_personaslote> contactos = ObtenerContactos();

        lote = new bf_rl_loteos().Save(lote, contactos, incrementos, canales);

        //VIMEO
        if (!string.IsNullOrWhiteSpace(txtVimeo.Text)) guardarUrlVimeo(lote.id_loteo);

        if (lote.id != 0)
        {
          if (atributos.Any())
          {
            GrabarAtributos(Constantes.TABLA_LOTES, lote.id_loteo, 0, atributos);
          }
          if (atributosFamilia.Any())
          {
            GrabarAtributos(Constantes.ATRIBUTOS_TABLA_FAMILIA, lote.id_loteo, lote.id_familia.id, atributosFamilia);
          }
          if (atributosCategoria.Any())
          {
            GrabarAtributos(Constantes.ATRIBUTOS_TABLA_CATEGORIA, lote.id_loteo, lote.id_categoria.id, atributosCategoria);
          }
          if (atributosSubcategoria.Any())
          {
            GrabarAtributos(Constantes.ATRIBUTOS_TABLA_SUBCATEGORIA, lote.id_loteo, lote.id_subcategoria.id, atributosSubcategoria);
          }
        }
        Mensajes.Show("Mensaje", mensaje, "CloseIframe();", MessageBox.Icon.INFO);
      }
      catch (Exception ex)
      {
        Mensajes.Error(ErrorText.ERROR_GUARDAR_REGISTRO + "<br />" + ex.Message);
      }
    }
    private void CompletarValores(int idLoteo)
    {
      try
      {
        co_rl_loteos lote = new bf_rl_loteos().GetData(idLoteo);

        txtNroLote.Text = lote.lo_numero.ToString();
        txtCantidad.Text = lote.lo_cantidad.ToString();
        txtNombre.Text = lote.lo_titulo;
        txtDescripcion.Text = lote.lo_descripcion;
        txtMinimo.Text = lote.lo_minimo.ToString("N0");
        chkIva.Checked = NumInt.Init(lote.lo_iva) != 0;
        cmbMoneda.SeleccionarOpcion(lote.id_moneda.id.ToString());
        txtUnidadMedida.Text = lote.lo_unidad_medida;
        txtComision.Text = lote.lo_comision;
        txtDescripcionMonto.Text = lote.lo_descripcionMonto;
        txtGarantia.Text = lote.lo_garantia.ToString("N0");
        cmbMonedaGarantia.SeleccionarOpcion(lote.id_moneda_garantia.id.ToString());

        cmbEstado.SeleccionarOpcion(lote.id_loteoestado.id.ToString());
        cmbMandantes.SeleccionarOpcion(lote.id_mandante.id.ToString());
        cmbFamilias.SetValueAndFireSelect(lote.id_familia.id);
        cmbCategoria.SetValueAndFireSelect(lote.id_categoria.id);
        cmbSubCategoria.SetValueAndFireSelect(lote.id_subcategoria.id);

        //**VIMEO**
        var urlVimeo = new bf_tg_urls().obtenerUrlLote(new co_tg_urls
        {
          id_origen = lote.id_loteo,
          id_tipourl = { id = Constantes.TIPO_URL_VIMEO }

        });
        txtVimeo.Text = urlVimeo == null ? "" : urlVimeo.url_recurso;

        if (!string.IsNullOrEmpty(lote.lo_direccion))
        {
          cmbTipoDireccion.SetValueAndFireSelect("DIR");
          txtDireccion.Text = lote.lo_direccion;
        }
        else
        {
          cmbTipoDireccion.SetValueAndFireSelect("COR");
        }
        cmbRegion.SetValueAndFireSelect(lote.id_region.id);
        cmbComuna.SetValueAndFireSelect(lote.id_comuna.id);
        txtLatitud.Text = lote.lo_latitud;
        txtLongitud.Text = lote.lo_longitud;

        txtObservacion.Text = lote.lo_observacion;
        //txtDetalle.Text = lote.lo_detalle;
        editor.InnerHtml = lote.lo_detalle;
        CargarIncrementos(lote.id_loteo);
        CargarCanales(lote.id_loteo);
        CargarContactos(lote.id_loteo);

        txtCodigo.Text = lote.lo_codigo;
        txtSuperficieConstruida.Text = lote.lo_superficieConstruida.ToString("N2");
        txtSuperficieSitio.Text = lote.lo_superficieSitio.ToString("N2");
        if (lote.id_unidadSitio.id != 0)
        {
          cmbUniMedSupSitio.SeleccionarOpcion(lote.id_unidadSitio.id.ToString());
        }
        if (lote.id_unidadConstruida.id != 0)
        {
          cmbUniMedSupConstruida.SeleccionarOpcion(lote.id_unidadConstruida.id.ToString());
        }
        txtLugarExhibicion.Text = lote.lo_lugar_exhibicion;
        txtExhibicion.Text = lote.lo_exhibicion;


      }
      catch (Exception ex)
      {
        Mensajes.Error(ErrorText.ERROR_CARGAR_LOTE, "wf_rl_loteos_adm.CompletarValores", ex);
      }
    }
    protected void StrLotesAgrupados_OnReadData(object sender, StoreReadDataEventArgs e)
    {
      try
      {
        
        co_rl_loteos Nomina = new co_rl_loteos();
        Nomina.id_familia.id = Constantes.FAMILIA_PROPIEDADES;
        Nomina.id_loteoestado.id = Constantes.ESTADO_LOTE_ACTIVO;
        if (hid_id_remate_base.Text != "")
        {
          Nomina.id_remate_base = Int32.Parse(hid_id_remate_base.Text);
        }

        IList<object> lista = new List<object>();

        IList<co_rl_loteos> data = new bf_rl_loteos().GetData(Nomina);
        
        foreach (co_rl_loteos n in data.OrderBy(c => c.lo_orden).ToList())
        {
          int posturas = new ConexionPlgOnline(ObtenerConexion(hid_id_remate_base.Text.ValidaEntero("id_remate"))).GetPosturasLote(n.id_loteo);
          lista.Add(
              new
              {
                id_loteo = n.id_loteo,
                lo_descripcion = n.lo_descripcion,
                lo_numero = n.lo_numero,
                id_remate = n.id_remate.id,
                rem_nombre = n.id_remate.descripcion,
                lo_minimo = n.lo_minimo,
                id_garantiatipo = n.id_garantiatipo,
                lo_garantia = n.lo_garantia,
                lo_montogarantia = n.lo_montogarantia,
                lo_montoadjudicacion = n.lo_montoadjudicacion,
                lo_fechaadjudicacion = n.lo_fechaadjudicacion.Fecha,
                lo_numparticipantes = n.lo_numparticipantes,
                id_persona = n.id_persona,
                lo_cantidad = n.lo_cantidad,
                id_loteoestado = n.id_loteoestado.id,
                le_loteoestado = n.id_loteoestado.descripcion,
                lo_especificaciones = n.lo_especificaciones,
                lo_orden = n.lo_orden,
                lo_titulo = n.lo_titulo,
                lo_detalle = n.lo_detalle,
                lo_iva = n.lo_iva,

                id_disponibilidad = n.id_disponibilidad,
                id_mandante = n.id_mandante,
                id_categoria = n.id_categoria.id,
                ca_categoria = n.id_categoria.descripcion,
                id_subcategoria = n.id_subcategoria.id,
                subca_subcategoria = n.id_subcategoria.descripcion,
                id_familia = n.id_familia.id,
                fa_familia = n.id_familia.descripcion,
                id_region = n.id_region.id,
                re_region = n.id_region.descripcion,
                id_comuna = n.id_comuna.id,
                co_comuna = n.id_comuna.descripcion,
                id_tipodestacado = n.id_tipodestacado,
                lo_exhibicion = n.lo_exhibicion,
                lo_latitud = n.lo_latitud,
                lo_longitud = n.lo_longitud,
                posturas =posturas
              });
        }

        strLotesAgrupados.DataSource = lista;
        PageProxy pageProxy = strLotesAgrupados.Proxy[0] as PageProxy;
        if (pageProxy != null) pageProxy.Total = lista.Count;
        strLotesAgrupados.DataBind();

      }
      catch (Exception ex)
      {
        Mensajes.Error(ErrorText.ERROR_CARGAR_LISTADO_LOTES, "wf_agrupador_lotes.StrLotesAgrupados_OnReadData", ex);
      }
    }
    protected void BtnGrabar_Click(object sender, DirectEventArgs e)
    {
      try
      {
        string data = e.ExtraParams["data"];
        IList<co_rl_loteos> lotesList = JsonConvert.DeserializeObject<IList<co_rl_loteos>>(data);
        int id_remate_base = Int32.Parse(hid_id_remate_base.Text);
        foreach (co_rl_loteos lo in lotesList)
        {
          co_rl_loteos loteos = new bf_rl_loteos().GetData(lo.id_loteo);

          if (loteos.id_loteo != 0)
          {
            if (loteos.lo_numero != lo.lo_numero || loteos.lo_orden != lo.lo_orden)
            {

              loteos.lo_numero = lo.lo_numero;
              loteos.lo_orden = lo.lo_orden;
              loteos = new bf_rl_loteos().Save(loteos);

              loteos.id_remate.id = id_remate_base;

              ConexionPlgOnline plg = new ConexionPlgOnline(this.ObtenerConexion(loteos.id_remate.id));
              plg.GrabaLotes(loteos);
            }
          }
        }
        Mensajes.Show("Mensaje",ErrorText.REGISTRO_MODIFICADO,Mensajes.Icon.INFO);
        strLotesAgrupados.CommitChanges();
      }
      catch (Exception ex)
      {
        Mensajes.Error(ex.Message);
      }
    }
    private Dictionary<int, string> ObtenerCategoriaPorRemateId(int id_remate)
    {
      string SQLText = "SELECT  dbo.re_categorias.id_categoria,dbo.re_categorias.ca_categoria ";
      SQLText += "FROM  dbo.re_remates INNER JOIN ";
      SQLText += " dbo.re_familias ON dbo.re_remates.id_familia = dbo.re_familias.id_familia INNER JOIN ";
      SQLText += "dbo.re_categorias ON dbo.re_familias.id_familia = dbo.re_categorias.id_familia ";
      SQLText += "WHERE  (dbo.re_remates.id_remate = " + id_remate + ")";

      Dictionary<int, string> ids = new Dictionary<int, string>();
      var idCategorias = new bf_rl_loteos().GetInforme(SQLText);

      if (idCategorias != null)
      {
        foreach (DataRow item in idCategorias.Tables[0].Rows)
        {
          ids.Add(item.Field<int>("id_categoria"), item.Field<string>("ca_categoria"));
        }
        return ids;
      }
      else
      {
        return null;
      }
    }
    private void Asocia(IEnumerable<Remate> list)
    {
      try
      {
        IList<co_rl_loteos> listLotesPLG = new List<co_rl_loteos>();
        IList<co_re_remates> listRemates = new List<co_re_remates>();
        int id_remate_base = 0;
        if (hid_id_remate.Text == "")
        {
          id_remate_base = Int32.Parse(cmbRemates.SelectedItem.Value);
        }
        else
        {
          id_remate_base = Int32.Parse(hid_id_remate.Text);
        }
        foreach (co_re_remates reRemates in list.Select(remate => new bf_re_remates().GetData(remate.id_remate)))
        {
          co_re_remates remate = new bf_re_remates().GetData(id_remate_base);
          if (!remate.rem_fecha.Fecha.ToShortDateString().Equals(reRemates.rem_fecha.Fecha.ToShortDateString()))
          {
            RematesDisponibles(id_remate_base);
            RematesAgrupados(id_remate_base);
            throw new Exception("Se produjo un error al tratar de agrupar el remate, para agrupar el remate deben tener la misma fecha");
          }
          reRemates.id_remate_base = id_remate_base;
          reRemates.id_usuario_agrupa = FWPConfiguration.get_ID_User(Session.SessionID);
          reRemates.rem_fechaagrupa.Fecha = DateTime.Now;
          listRemates.Add(reRemates);
          var lotes = new bf_rl_loteos().GetData(new co_rl_loteos { id_remate = { id = reRemates.id_remate } });
          foreach (co_rl_loteos lote in lotes)
          {
            lote.id_remate_origen = reRemates.id_remate;
            new bf_rl_loteos().Save(lote);
            lote.id_remate.id = id_remate_base;
            listLotesPLG.Add(lote);
          }
        }
        new bf_re_remates().Save(listRemates);


        ConexionPlgOnline plg = null;
        foreach (co_re_remates remate in listRemates)
        {

          string conexion = string.Empty;
          if (remate.id_familia == Constantes.FAMILIA_PROPIEDADES)
          {
            conexion = Constantes.CONEXION_PROPIEDADES;
          }
          else
          {
            conexion = Constantes.CONEXION_ONLINE;
          }
          plg = new ConexionPlgOnline(conexion);
          plg.GrabaRemate(remate);
        }
        plg.GrabaLotes(listLotesPLG);
        Mensajes.Show("Mensaje", ErrorText.REMATE_AGRUPADO_EXITOSAMENTE, Mensajes.Icon.INFO);
      }
      catch (Exception ex)
      {
        throw new Exception("Asocia: " + ex.Message);
      }
    }
    /// <summary>
    /// Metodo que Notifica al Usuario Movil acerca del Lote de acuerdo a sus preferencias
    /// </summary>
    /// <param name="idLote"></param>
    /// <param name="idRemate"></param>
    public static string NotificarTest(int idLote, int idRemate)
    {
      string mensaje = string.Empty;
      try
      {
        getTransaccion();
        co_rl_loteos lote = new bf_rl_loteos().GetData(idLote);
        co_re_remates remate = new bf_re_remates().GetData(idRemate);
        //valido que el remate no sea nulo
        if (remate != null)
        {
          //valido q el remate esta publicado
          if (remate.id_remateEstadoWeb.id == PUBLICADO)
          {
            //valido que el lote no sea nulo
            if (lote != null)
            {
              //valido q este marcado como activo
              if (lote.id_loteoestado.id == LOTE_ACTIVO)
              {
                //una vez validado los estados valido que este marcado como movil
                co_rl_loteoscanales canal = new bf_rl_loteoscanales().GetData(new co_rl_loteoscanales { id_loteo = { id = lote.id_loteo }, id_canal = { id = CANAL_MOVIL } }).FirstOrDefault();
                if (canal != null)
                {
                  getTransaccion();
                  //realizo la instancia del wsdl para la notificacion.
                  WsNotificacion notificacion = new WsNotificacionClient();

                  //obtengo todos los lotes del remate con la opcion de canal movil
                  var mvSubcategorias =
                    new bf_mv_mosubcategorias_subcategorias().GetData(new co_mv_mosubcategorias_subcategorias
                    {
                      id_subcategoria = lote.id_subcategoria
                    });
                  string subcategoriasMovil = mvSubcategorias.Aggregate(string.Empty,
                    (current, sb) => current + sb.id_mosubcategoria.id + ",");
                  if (subcategoriasMovil.Length > 0)
                  {
                    subcategoriasMovil = subcategoriasMovil.Substring(0, (subcategoriasMovil.Length - 1));
                  }else
                  {
                    subcategoriasMovil = @"0";
                  }

                  var usuariosWeb = new bf_ca_usuariosweb().getUsuariosSubcategoriasMovil(subcategoriasMovil);
                  //verifico si hay usuario a los que notificar de lo contrario no hago nada
                  if (usuariosWeb.Any())
                  {
                    Publicacion publicacion = new Publicacion
                    {
                      esRemate = EsRemate(remate),
                      id = lote.id_loteo,
                      titulo = lote.lo_titulo
                    };
                    IList<Usuario> usuarios = new List<Usuario>();
                    string nombreCompleto = string.Empty;
                    foreach (var usu in usuariosWeb)
                    {
                      int uuid = 1749;
                      nombreCompleto = usu.pe_nombrecompleto;
                      usuarios.Add(new Usuario { uuid = uuid.ToString(), nombre = nombreCompleto });
                    }
                    publicacion.Usuarios = usuarios.ToArray();

                    NotificarRequest notificarRequest = new NotificarRequest
                    {
                      DatosTransaccion = _transaccion,
                      Publicacion = publicacion
                    };

                    NotificarResponse response = notificacion.Notificar(notificarRequest);
                    //guardo la respuesta realizada por el WebService
                    GuardarResponseMovil(response, lote.id_loteo, remate.id_remate, publicacion);

                    mensaje = "Lote Notificado Exitosamente.";
                  }else
                  {
                    mensaje = "No hay usuarios al cual Notificar.";
                  }
                }
                else
                {
                  mensaje = "Debe Seleccionar Canal Movil para poder notificar";
                }
              }
              else
              {
                mensaje = "Lote debe estar con estado ACTIVO para poder notificar";
              }
            }
            else
            {
              mensaje = "Lote Nulo";
            }
          }
          else
          {
            mensaje = "Remate debe estar PUBLICADO para poder notificar.";
          }
        }
        else
        {
          mensaje = "Remate Nulo";
        }
      }
      catch (Exception ex)
      {
        return "Error al notificar <br>" + ex.Message;
      }
      return mensaje;
    }
    public string ValidarExcel()
    {
      JObject response = new JObject();
      try
      {
        int id_remate = hid_idRemate.Text.ValidaEntero("id_remate");
        if (fileExcel.HasFile)
        {
          string nombreArchivo = Server.HtmlEncode(fileExcel.FileName);
          string extension = System.IO.Path.GetExtension(nombreArchivo);
          string ruta = Request.PhysicalApplicationPath + FWPConfiguration.get_AppSettings("MatPathUpload").ToString() + Session.SessionID;

          if (extension == ".xls")
          {
            if (!System.IO.Directory.Exists(ruta))
            {
              System.IO.Directory.CreateDirectory(ruta);
            }

            ruta += "\\" + nombreArchivo;
            fileExcel.PostedFile.SaveAs(ruta);
            bool ret = true;
            string txt = "";

            DataTable dtCeldasMinimas = new bf_rl_loteos().ValidarExcel(ruta, id_remate, "CeldasMinimas")[0];

            string camposMinimos = "";
            foreach (DataRow rowCeldasMinimas in dtCeldasMinimas.AsEnumerable())
            {
              if (rowCeldasMinimas["Numero Lote"].ToString() != "") camposMinimos += rowCeldasMinimas["Numero Lote"].ToString() + "\n";
              if (rowCeldasMinimas["Comisión"].ToString() != "") camposMinimos += rowCeldasMinimas["Comisión"].ToString() + "\n";
              if (rowCeldasMinimas["Nombre Lote"].ToString() != "") camposMinimos += rowCeldasMinimas["Nombre Lote"].ToString() + "\n";
              if (rowCeldasMinimas["Descripción Lote"].ToString() != "") camposMinimos += rowCeldasMinimas["Descripción Lote"].ToString() + "\n";
              if (rowCeldasMinimas["Cantidad Bienes"].ToString() != "") camposMinimos += rowCeldasMinimas["Cantidad Bienes"].ToString() + "\n";
              if (rowCeldasMinimas["Dirección"].ToString() != "") camposMinimos += rowCeldasMinimas["Dirección"].ToString() + "\n";
              if (rowCeldasMinimas["Moneda"].ToString() != "") camposMinimos += rowCeldasMinimas["Moneda"].ToString() + "\n";
              if (rowCeldasMinimas["Categoría"].ToString() != "") camposMinimos += rowCeldasMinimas["Categoría"].ToString() + "\n";
              if (rowCeldasMinimas["Subcategoría"].ToString() != "") camposMinimos += rowCeldasMinimas["Subcategoría"].ToString() + "\n";
              if (rowCeldasMinimas["Agrupador"].ToString() != "") camposMinimos += rowCeldasMinimas["Agrupador"].ToString() + "\n";
              if (rowCeldasMinimas["Mandante"].ToString() != "") camposMinimos += rowCeldasMinimas["Mandante"].ToString() + "\n";
              if (rowCeldasMinimas["Comuna"].ToString() != "") camposMinimos += rowCeldasMinimas["Comuna"].ToString() + "\n";
              if (rowCeldasMinimas["IVA"].ToString() != "") camposMinimos += rowCeldasMinimas["IVA"].ToString() + "\n";
              if (rowCeldasMinimas["Incremento"].ToString() != "") camposMinimos += rowCeldasMinimas["Incremento"].ToString() + "\n";
              if (rowCeldasMinimas["Mínimo"].ToString() != "") camposMinimos += rowCeldasMinimas["Mínimo"].ToString() + "\n";
              if (rowCeldasMinimas["Detalle"].ToString() != "") camposMinimos += rowCeldasMinimas["Detalle"].ToString() + "\n";
              if (rowCeldasMinimas["Observación"].ToString() != "") camposMinimos += rowCeldasMinimas["Observación"].ToString() + "\n";
              if (rowCeldasMinimas["Exhibición Horario"].ToString() != "") camposMinimos += rowCeldasMinimas["Exhibición Horario"].ToString() + "\n";
              if (rowCeldasMinimas["Exhibición Lugar"].ToString() != "") camposMinimos += rowCeldasMinimas["Exhibición Lugar"].ToString() + "\n";
              if (rowCeldasMinimas["Póliza"].ToString() != "") camposMinimos += rowCeldasMinimas["Póliza"].ToString() + "\n";
              if (rowCeldasMinimas["Superficie Construida"].ToString() != "") camposMinimos += rowCeldasMinimas["Superficie Construida"].ToString() + "\n";
              if (rowCeldasMinimas["Superficie Sitio"].ToString() != "") camposMinimos += rowCeldasMinimas["Superficie Sitio"].ToString() + "\n";
              if (rowCeldasMinimas["Unidad Medida"].ToString() != "") camposMinimos += rowCeldasMinimas["Unidad Medida"].ToString() + "\n";
              if (rowCeldasMinimas["Unidad Medida Sitio"].ToString() != "") camposMinimos += rowCeldasMinimas["Unidad Medida Sitio"].ToString() + "\n";
              if (rowCeldasMinimas["Unidad Medida Construida"].ToString() != "") camposMinimos += rowCeldasMinimas["Unidad Medida Construida"].ToString() + "\n";
              if (rowCeldasMinimas["Moneda Garantia"].ToString() != "") camposMinimos += rowCeldasMinimas["Moneda Garantia"].ToString() + "\n";
            }

            if (camposMinimos != "")
            {
              if (camposMinimos.Split('\n').Length == 2)
              {
                txt = txt + "Verifique que la siguiente celda obligatoria exita en el excel : \n\n" + camposMinimos;
              }
              else
              {
                txt = txt + "Verifique que las siguientes celdas obligatorias exitan en el excel : \n\n" + camposMinimos;
              }
              ret = false;
            }

            if (ret)
            {
              DataTable dtCampos = new bf_rl_loteos().ValidarExcel(ruta, id_remate, "Obligatorios")[0];
              string camposObligatorios = "";
              foreach (DataRow rowObligatorios in dtCampos.AsEnumerable())
              {
                if (rowObligatorios["Cantidad Bienes"].ToString() != "") camposObligatorios += rowObligatorios["Cantidad Bienes"].ToString().ToString();
                if (rowObligatorios["Numero Lote"].ToString() != "") camposObligatorios += rowObligatorios["Numero Lote"].ToString().ToString();
                if (rowObligatorios["Nombre Lote"].ToString() != "") camposObligatorios += rowObligatorios["Nombre Lote"].ToString().ToString();
                if (rowObligatorios["Descripción Lote"].ToString() != "") camposObligatorios += rowObligatorios["Descripción Lote"].ToString().ToString();
                if (rowObligatorios["IVA"].ToString() != "") camposObligatorios += rowObligatorios["IVA"].ToString().ToString();
                if (rowObligatorios["Moneda"].ToString() != "") camposObligatorios += rowObligatorios["Moneda"].ToString().ToString();
                if (rowObligatorios["Comisión"].ToString() != "") camposObligatorios += rowObligatorios["Comisión"].ToString().ToString();
                if (rowObligatorios["Categoría"].ToString() != "") camposObligatorios += rowObligatorios["Categoría"].ToString().ToString();
                if (rowObligatorios["Subcategoría"].ToString() != "") camposObligatorios += rowObligatorios["Subcategoría"].ToString().ToString();
                if (rowObligatorios["Incremento"].ToString() != "") camposObligatorios += rowObligatorios["Incremento"].ToString().ToString();
                if (rowObligatorios["Mandante"].ToString() != "") camposObligatorios += rowObligatorios["Mandante"].ToString().ToString();
                if (rowObligatorios["Agrupador"].ToString() != "") camposObligatorios += rowObligatorios["Agrupador"].ToString().ToString();
                if (rowObligatorios["Dirección"].ToString() != "") camposObligatorios += rowObligatorios["Dirección"].ToString().ToString();
                if (rowObligatorios["Comuna"].ToString() != "") camposObligatorios += rowObligatorios["Comuna"].ToString().ToString();
                if (rowObligatorios["Unidad Medida"].ToString() != "") camposObligatorios += rowObligatorios["Unidad Medida"].ToString().ToString();
                if (rowObligatorios["Unidad Medida Sitio"].ToString() != "") camposObligatorios += rowObligatorios["Unidad Medida Sitio"].ToString().ToString();
                if (rowObligatorios["Unidad Medida Construida"].ToString() != "") camposObligatorios += rowObligatorios["Unidad Medida Construida"].ToString().ToString();
                if (rowObligatorios["Moneda Garantia"].ToString() != "") camposObligatorios += rowObligatorios["Moneda Garantia"].ToString().ToString();

              }

              if (camposObligatorios != "")
              {
                txt = txt + "Campos Obligatorios : \n\n" + camposObligatorios;
                ret = false;
              }
            }

            if (ret)
            {
              DataTable dtPropiedades = new bf_rl_loteos().ValidarExcel(ruta, id_remate, "Propiedades")[0];
              string camposPropiedades = "";
              foreach (DataRow rowPropiedades in dtPropiedades.AsEnumerable())
              {
                if (rowPropiedades["Numero Lote"].ToString() != "") camposPropiedades += rowPropiedades["Numero Lote"].ToString() + "\n";
                if (rowPropiedades["Comisión"].ToString() != "") camposPropiedades += rowPropiedades["Comisión"].ToString() + "\n";
                if (rowPropiedades["Nombre Lote"].ToString() != "") camposPropiedades += rowPropiedades["Nombre Lote"].ToString() + "\n";
                if (rowPropiedades["Descripción Lote"].ToString() != "") camposPropiedades += rowPropiedades["Descripción Lote"].ToString() + "\n";
                if (rowPropiedades["Cantidad Bienes"].ToString() != "") camposPropiedades += rowPropiedades["Cantidad Bienes"].ToString() + "\n";
                if (rowPropiedades["Dirección"].ToString() != "") camposPropiedades += rowPropiedades["Dirección"].ToString() + "\n";
                if (rowPropiedades["Moneda"].ToString() != "") camposPropiedades += rowPropiedades["Moneda"].ToString() + "\n";
                if (rowPropiedades["Categoría"].ToString() != "") camposPropiedades += rowPropiedades["Categoría"].ToString() + "\n";
                if (rowPropiedades["Subcategoría"].ToString() != "") camposPropiedades += rowPropiedades["Subcategoría"].ToString() + "\n";
                if (rowPropiedades["Agrupador"].ToString() != "") camposPropiedades += rowPropiedades["Agrupador"].ToString() + "\n";
                if (rowPropiedades["Mandante"].ToString() != "") camposPropiedades += rowPropiedades["Mandante"].ToString() + "\n";
                if (rowPropiedades["Comuna"].ToString() != "") camposPropiedades += rowPropiedades["Comuna"].ToString() + "\n";
                if (rowPropiedades["IVA"].ToString() != "") camposPropiedades += rowPropiedades["IVA"].ToString() + "\n";
                if (rowPropiedades["Incremento"].ToString() != "") camposPropiedades += rowPropiedades["Incremento"].ToString() + "\n";
                if (rowPropiedades["Mínimo"].ToString() != "") camposPropiedades += rowPropiedades["Mínimo"].ToString() + "\n";
                if (rowPropiedades["Detalle"].ToString() != "") camposPropiedades += rowPropiedades["Detalle"].ToString() + "\n";
                if (rowPropiedades["Observación"].ToString() != "") camposPropiedades += rowPropiedades["Observación"].ToString() + "\n";
                if (rowPropiedades["Exhibición Horario"].ToString() != "") camposPropiedades += rowPropiedades["Exhibición Horario"].ToString() + "\n";
                if (rowPropiedades["Exhibición Lugar"].ToString() != "") camposPropiedades += rowPropiedades["Exhibición Lugar"].ToString() + "\n";
                if (rowPropiedades["Póliza"].ToString() != "") camposPropiedades += rowPropiedades["Póliza"].ToString() + "\n";
                if (rowPropiedades["Superficie Construida"].ToString() != "") camposPropiedades += rowPropiedades["Superficie Construida"].ToString() + "\n";
                if (rowPropiedades["Superficie Sitio"].ToString() != "") camposPropiedades += rowPropiedades["Superficie Sitio"].ToString() + "\n";
                if (rowPropiedades["Unidad Medida"].ToString() != "") camposPropiedades += rowPropiedades["Unidad Medida"].ToString() + "\n";
                if (rowPropiedades["Unidad Medida Sitio"].ToString() != "") camposPropiedades += rowPropiedades["Unidad Medida Sitio"].ToString() + "\n";
                if (rowPropiedades["Unidad Medida Construida"].ToString() != "") camposPropiedades += rowPropiedades["Unidad Medida Construida"].ToString() + "\n";
                if (rowPropiedades["Moneda Garantia"].ToString() != "") camposPropiedades += rowPropiedades["Moneda Garantia"].ToString() + "\n";
              }

              if (camposPropiedades != "")
              {
                var espacio = "";
                //if (camposObligatorios != "") espacio = "\n";
                txt = txt + espacio + "Verifique la siguiente información : \n\n" + camposPropiedades;
                ret = false;
              }
            }
            if (ret)
            {
              DataTable dtDatos = new bf_rl_loteos().ValidarExcel(ruta, id_remate, "Datos")[0];

              var datosMalIngresado = "";
              foreach (DataRow rowDatos in dtDatos.AsEnumerable())
              {
                if (rowDatos["IVA"].ToString() != "") datosMalIngresado += String.Format("Fila {0}: {1} \n", rowDatos["Fila"].ToString(), rowDatos["IVA"].ToString());
                if (rowDatos["Moneda"].ToString() != "") datosMalIngresado += String.Format("Fila {0}: {1} \n", rowDatos["Fila"].ToString(), rowDatos["Moneda"].ToString());
                if (rowDatos["Categoría"].ToString() != "") datosMalIngresado += String.Format("Fila {0}: {1} \n", rowDatos["Fila"].ToString(), rowDatos["Categoría"].ToString());
                if (rowDatos["Subcategoría"].ToString() != "") datosMalIngresado += String.Format("Fila {0}: {1} \n", rowDatos["Fila"].ToString(), rowDatos["Subcategoría"].ToString());
                if (rowDatos["Mandante"].ToString() != "") datosMalIngresado += String.Format("Fila {0}: {1} \n", rowDatos["Fila"].ToString(), rowDatos["Mandante"].ToString());
                if (rowDatos["Comuna"].ToString() != "") datosMalIngresado += String.Format("Fila {0}: {1} \n", rowDatos["Fila"].ToString(), rowDatos["Comuna"].ToString());
                if (rowDatos["Numero Lote"].ToString() != "") datosMalIngresado += String.Format("Fila {0}: {1} \n", rowDatos["Fila"].ToString(), rowDatos["Numero Lote"].ToString());

                if (rowDatos["Unidad Medida Sitio"].ToString() != "") datosMalIngresado += String.Format("Fila {0}: {1} \n", rowDatos["Fila"].ToString(), rowDatos["Unidad Medida Sitio"].ToString());
                if (rowDatos["Unidad Medida Construida"].ToString() != "") datosMalIngresado += String.Format("Fila {0}: {1} \n", rowDatos["Fila"].ToString(), rowDatos["Unidad Medida Construida"].ToString());
                if (rowDatos["Moneda Garantia"].ToString() != "") datosMalIngresado += String.Format("Fila {0}: {1} \n", rowDatos["Fila"].ToString(), rowDatos["Moneda Garantia"].ToString());

              }
              if (datosMalIngresado != "")
              {
                var espacio = "";
                //if (camposObligatorios != "" || camposPropiedades != "") espacio = "\n";
                txt = txt + espacio + "Error en los siguientes Datos : \n\n" + datosMalIngresado;
                ret = false;
              }
            }


            if (ret)
            {

              DataTable dtRepetidos = new bf_rl_loteos().ValidarExcel(ruta, id_remate, "Repetidos")[0];

              var sobreescribir = (from item in dtRepetidos.AsEnumerable()
                                   where item.Field<bool>("Sobreescribir") == true
                                   orderby item.Field<Int32>("NumeroLote") ascending
                                   select new
                                   {
                                     NumeroLote = item.Field<Int32>("NumeroLote"),
                                     Sobreescribir = item.Field<bool>("Sobreescribir"),
                                     NombreLote = item.Field<string>("NombreLote")
                                   });
              var repetidos = (from item in dtRepetidos.AsEnumerable()
                               where item.Field<bool>("Repite") == true
                               select new
                               {
                                 NumeroLote = item.Field<Int32>("NumeroLote"),
                                 Repite = item.Field<bool>("Repite"),
                                 Fila = item.Field<Int32>("Fila")
                               });

              string camposRepetidos = "";

              int cuentaRepetidos = 0;
              foreach (var rowRepetidos in repetidos)
              {
                if (Convert.ToBoolean(rowRepetidos.Repite)) camposRepetidos = camposRepetidos + String.Format("Fila {0}: El numero lote {1} se encuentre mas de dos veces ingresado en el remate.\n", rowRepetidos.Fila, rowRepetidos.NumeroLote);
                cuentaRepetidos++;
              }

              if (camposRepetidos != "")
              {
                if (cuentaRepetidos == 1)
                {
                  txt = txt + "El siguiente lote se omitira su ingreso: \n\n" + camposRepetidos;
                }
                else
                {
                  txt = txt + "Los siguientes lotes se omitira su ingreso: \n\n" + camposRepetidos;
                }
              }

              int cuentaSobreescribir = 0;
              foreach (var rowSobreescribir in sobreescribir)
              {
                cuentaSobreescribir++;
              }

              if (cuentaSobreescribir > 0)
              {
                grdExcel.GetStore().DataSource = sobreescribir;
                grdExcel.GetStore().DataBind();
              }
            }

            response.Add(new JProperty("success", true));
            response.Add(new JProperty("mensaje", JsonConvert.SerializeObject(txt)));
            response.Add(new JProperty("respuesta", JsonConvert.SerializeObject(ret)));

          }
          else
          {
            response.Add(new JProperty("success", false));
            response.Add(new JProperty("mensaje", JsonConvert.SerializeObject("Archivo incompatible. Solo la extension.xls es permitida")));
            response.Add(new JProperty("respuesta", JsonConvert.SerializeObject(false)));

          }
        }
      }
      catch (Exception ex)
      {
        response.Add(new JProperty("success", false));
        response.Add(new JProperty("mensaje", JsonConvert.SerializeObject(ex.Message)));
        response.Add(new JProperty("respuesta", JsonConvert.SerializeObject(false)));
      }
      return response.ToString();
    }
    protected void btnCopiar_Click(object sender, DirectEventArgs e)
    {
      try
      {
        string mensaje = "Se Grabo con Exito.<br>";
        int id_remateAntiguo = cmbRemates.SelectedItem.Value.ValidaEntero("id_remate_antiguo");
        int id_remateNuevo = hid_id_remate.Text.ValidaEntero("id_remate_nuevo");
       
        RowSelectionModel model = grdLotes.SelectionModel.Primary as RowSelectionModel;
        IList<co_rl_loteos> lista = new List<co_rl_loteos>();
        if (model != null && model.SelectedRows.Any())
        {
          lista = new List<co_rl_loteos>();
          foreach (SelectedRow row in model.SelectedRows)
          {
            co_rl_loteos lote = new bf_rl_loteos().GetData(row.RecordID.ValidaEntero("id_lote"));
            lista.Add(lote);
          }
          
          mensaje += new bf_rl_loteos().CopiarLotes(lista, id_remateAntiguo, id_remateNuevo);
         
          Mensajes.Show("Mensaje", mensaje);

        }
        else
        {
          Mensajes.Error(ErrorText.ERROR_CHECK_LOTES);
        }
      }
      catch (Exception ex)
      {
        Mensajes.Error(ErrorText.ERROR_COPIAR_LOTES, "btnCopiar_Click", ex);
      }
    }
 protected void btnBorrar_Click(object sender, DirectEventArgs e)
 {
   try
   {
     Boolean lote = new bf_rl_loteos().DeleteLote(int.Parse(hid_id.Text));
     if (lote)
     {
       Mensajes.Show("Mensaje", ErrorText.REGISTRO_BORRADO, "CloseIframe();", MessageBox.Icon.INFO);
     }
     else
     {
       Mensajes.Error(ErrorText.ERROR_ELIMINAR_LOTE);
     }
   }
   catch (Exception ex)
   {
     Mensajes.Error(ErrorText.ERROR_BORRAR_REGISTRO, "wf_rl_loteos_adm.btnBorrar_Click", ex);
   }
 }
    private void Desasocia(IEnumerable<Remate> list)
    {
      try
      {
        IList<co_rl_loteos> lotes = new List<co_rl_loteos>();
        IList<co_rl_loteos> listLotesPLG = new List<co_rl_loteos>();
        IList<co_re_remates> listRemates = new List<co_re_remates>();
        foreach (co_re_remates reRemates in list.Select(remate => new bf_re_remates().GetData(remate.id_remate)))
        {
          reRemates.id_remate_base = 0;
          reRemates.id_usuario_agrupa = 0;
          reRemates.rem_fechaagrupa.Fecha = DateTime.MinValue;
          listRemates.Add(reRemates);
          lotes = new bf_rl_loteos().GetData(new co_rl_loteos { id_remate = { id = reRemates.id_remate } });
        }
        foreach (co_rl_loteos lote in lotes)
        {
          lote.id_remate_origen = lote.id_remate.id;
          listLotesPLG.Add(lote);
        }
        new bf_re_remates().Save(listRemates);
        new bf_rl_loteos().Save(listLotesPLG);

        ConexionPlgOnline plg = null;
        foreach (co_re_remates remate in listRemates)
        {
          string conexion = string.Empty;
          if (remate.id_familia == Constantes.FAMILIA_PROPIEDADES)
          {
            conexion = Constantes.CONEXION_PROPIEDADES;
          }
          else
          {
            conexion = Constantes.CONEXION_ONLINE;
          }
          plg = new ConexionPlgOnline(conexion);
          plg.GrabaRemate(remate);
        }
        plg.GrabaLotes(listLotesPLG);
        Mensajes.Show("Mensaje", ErrorText.REMATE_DESAGRUPADO_EXITOSAMENTE, Mensajes.Icon.INFO);
      }
      catch (Exception ex)
      {
        throw new Exception("Desasocia: " + ex.Message);
      }
    }
 private string ObtenerUrlCatalogo(string id)
 {
     try
     {
         bool esVehiculo = true;
         int id_remate = id.ValidaEntero("id_remate");
         IList<co_rl_loteos> loteos = new bf_rl_loteos().GetData(new co_rl_loteos { id_remate = { id = id_remate } });
         if (loteos.Any())
         {
             foreach (co_rl_loteos lote in loteos.Where(lote => lote.id_categoria.id != Constantes.CATEGORIA_VEHICULOS))
             {
                 esVehiculo = false;
             }
         }
         if (esVehiculo)
         {
             return Constantes.URL_PRINCIPAL_ADMIN + "Catalogo/wf_catalogo_remate.aspx?id_remate=" + id;
         }
         else
         {
             return Constantes.URL_PRINCIPAL_ADMIN + "Catalogo/wf_catalogo_remate_no_vehiculos.aspx?id_remate=" + id;
         }
     }
     catch (Exception ex)
     {
         Mensajes.Error(ex.Message);
     }
     return "";
 }
    protected void str_grilla_OnReadData(object sender, StoreReadDataEventArgs e)
    {
      try
      {
        int start = e.Start;
        int limit = NumInt.Init(e.Parameters.GetParameter("limit").Value);
        limit = limit == 0 ? e.Limit : limit;
        int page = (start / limit) + 1;
        int id_remate = hid_idRemate.Text.ValidaEntero("id_remate");

        co_rl_loteos_no Nomina = new co_rl_loteos_no();
        Nomina.Pagina = page;
        Nomina.RegistrosPorPaginas = e.Limit;
        Nomina.ColumnaOrden = e.Sort[0].Property;
        Nomina.OrdenColumna = (FwpServerControls.FwpDataGridDataBound.Orden)Enum.Parse(typeof(FwpServerControls.FwpDataGridDataBound.Orden), e.Sort[0].Direction.ToString(), true);
        Nomina.id_remate = id_remate;

        IList<object> lista = new List<object>();

        AgregarFiltros(ref Nomina);

        BotonesNominaLotes botones = new BotonesNominaLotes(Session);

        Nomina<co_rl_loteos_no> data = new bf_rl_loteos().GetNomina(Nomina);
        co_re_remates remate = new bf_re_remates().GetData(id_remate);
        if (remate.id_familia != Constantes.FAMILIA_BIENESMUEBLES) {
          MenuCargaMasivaSAP.Hidden = true;
        }
        string sUrlSitio = FamiliaPreview.ObtenerUrlVistaPreviaLotes(remate);

        foreach (co_rl_loteos_no n in data.DataSource)
        {
          //IList<co_tg_contadores> listaContadores = new bf_tg_contadores().GetData(new co_tg_contadores { id_origen = n.id_loteo, id_tipocontador = { id = remate.id_rematetipo.id==Constantes.REMATETIPO_REMATE?Constantes.TIPO_LOTES:remate.id_rematetipo.id} });
          IList<co_tg_contadores> listaContadores = new bf_tg_contadores().GetData(new co_tg_contadores { id_origen = n.id_loteo, id_tipocontador = { id = Constantes.TIPO_LOTES } });
          n.visitas = listaContadores.Count > 0 ? listaContadores[0].cont_cuenta : 0;
          bool esRemate = remate.id_rematetipo.id == Constantes.REMATETIPO_REMATE;
          bool esVentaDirecta = remate.id_tiporemate.id == Constantes.REMATETIPO_VENTA_DIRECTA;

          lista.Add(new
          {
            id_loteo = n.id_loteo,
            lo_numero = n.lo_numero,
            lo_titulo = n.lo_titulo,
            lo_descripcion = n.lo_descripcion,
            lo_minimo = n.mo_moneda + " " + n.lo_minimo.ToString("N0"),
            le_loteoestado = n.le_loteoestado,
            fa_familia = n.fa_familia,
            ca_categoria = n.ca_categoria,
            subca_subcategoria = n.subca_subcategoria,
            re_region = n.re_region,
            co_comuna = n.co_comuna,
            id_familia = n.id_familia,
            visitas = n.visitas,
            url = sUrlSitio+n.id_loteo,
            btnEliminarLote = botones.btnEliminarLote,
            notifica = (esRemate || esVentaDirecta) && NotificacionMovil.EsMovil(n.id_loteo)
          });
        }

        str_grilla.DataSource = lista;
        str_grilla.PageSize = limit;
        PageProxy pageProxy = str_grilla.Proxy[0] as PageProxy;
        if (pageProxy != null) pageProxy.Total = data.Registros;
        str_grilla.DataBind();

      }
      catch (Exception ex)
      {
        Mensajes.Error(ErrorText.ERROR_CARGAR_LISTADO_LOTES, "wf_pa_loteos_no.str_grilla_OnReadData", ex);
      }
    }