Пример #1
0
        public static USERINFO Login(string UserName, string Password)
        {
            //#if DEBUG
            //    Debugger.Launch();
            //#endif
            string condition = "";

            if (null != UserName && null != Password)
            {
                condition = "select*From userinfo where UserName='******'";
            }

            DbSqlQuery <USERINFO> result1 = db.USERINFO.SqlQuery(condition, UserName);

            if (null != result1 && result1.Count() > 0)
            {
                USERINFO user = result1.First <USERINFO>();

                if (null != user)
                {
                    if (user.PASSWORD == Utils.md5Unicodebase64(Password))
                    {
                        //if (user.PASSWORD == Password)
                        return(user);
                    }
                }
            }
            return(null);
        }
        public ActionResult ChooseDate([Bind(Include = "Settling,Eviction,ValueOfGuests,ValueOfKids,ClientId")] Booking booking)
        {
            if (ModelState.IsValid)
            {
                //return RedirectToAction("AvailableApartments", new { id = booking.ClientId, settling = booking.Settling, eviction = booking.Eviction, vog = booking.ValueOfGuests, vok = booking.ValueOfKids });
                ViewBag.BookingId     = booking.Id;
                ViewBag.Settling      = booking.Settling;
                ViewBag.Eviction      = booking.Eviction;
                ViewBag.ValueOfGuests = booking.ValueOfGuests;
                ViewBag.ValueOfKids   = booking.ValueOfKids;
                ViewBag.ClientId      = booking.ClientId;
                string settlingStr       = ConvertDateToString(booking.Settling);
                string evictionStr       = ConvertDateToString(booking.Eviction);
                var    requestResultTest = db.Apartments.SqlQuery($"SELECT * FROM Apartments b WHERE EXISTS (SELECT a.id FROM Apartments a WHERE b.id = a.id AND a.price > {0} AND a.price < {999999} AND (( EXISTS (SELECT apartmentsid FROM Livings WHERE eviction < '{settlingStr}' AND apartmentsid = a.id) AND NOT EXISTS(SELECT apartmentsid FROM Bookings WHERE EXISTS (SELECT apartmentsid FROM Bookings WHERE apartmentsid = a.id))) OR (EXISTS (SELECT apartmentsid FROM Bookings WHERE settling > '{evictionStr}' AND apartmentsid = a.id) OR ( EXISTS (SELECT apartmentsid FROM Bookings WHERE eviction < '{settlingStr}' AND apartmentsid = a.id))) AND NOT EXISTS(SELECT apartmentsid FROM Livings WHERE EXISTS (SELECT apartmentsid FROM Livings WHERE apartmentsid = a.id)) OR (( EXISTS (SELECT apartmentsid FROM Livings WHERE eviction<'{settlingStr}' AND apartmentsid = a.id)) AND ( EXISTS (SELECT apartmentsid FROM Bookings WHERE settling>'{evictionStr}' AND apartmentsid = a.id ) OR ( EXISTS (SELECT apartmentsid FROM Bookings WHERE eviction<'{settlingStr}' AND apartmentsid = a.id)))) OR ( NOT EXISTS (SELECT apartmentsid FROM Livings WHERE apartmentsid = a.id) AND NOT EXISTS (SELECT apartmentsid FROM Bookings WHERE apartmentsid = a.id))))");
                //var requestRT = db.Apartments.($"SELECT * FROM Apartments b WHERE EXISTS (SELECT a.id FROM Apartments a WHERE b.id = a.id AND a.price > {0} AND a.price < {999999} AND (( EXISTS (SELECT apartmentsid FROM Livings WHERE eviction < '{settlingStr}' AND apartmentsid = a.id) AND NOT EXISTS(SELECT apartmentsid FROM Bookings WHERE EXISTS (SELECT apartmentsid FROM Bookings WHERE apartmentsid = a.id))) OR (EXISTS (SELECT apartmentsid FROM Bookings WHERE settling > '{evictionStr}' AND apartmentsid = a.id) OR ( EXISTS (SELECT apartmentsid FROM Bookings WHERE eviction < '{settlingStr}' AND apartmentsid = a.id))) AND NOT EXISTS(SELECT apartmentsid FROM Livings WHERE EXISTS (SELECT apartmentsid FROM Livings WHERE apartmentsid = a.id)) OR (( EXISTS (SELECT apartmentsid FROM Livings WHERE eviction<'{settlingStr}' AND apartmentsid = a.id)) AND ( EXISTS (SELECT apartmentsid FROM Bookings WHERE settling>'{evictionStr}' AND apartmentsid = a.id ) OR ( EXISTS (SELECT apartmentsid FROM Bookings WHERE eviction<'{settlingStr}' AND apartmentsid = a.id)))) OR ( NOT EXISTS (SELECT apartmentsid FROM Livings WHERE apartmentsid = a.id) AND NOT EXISTS (SELECT apartmentsid FROM Bookings WHERE apartmentsid = a.id))))");
                //DbSqlQuery
                DbSqlQuery <Apartments> apartmentsQuery = db.Apartments.SqlQuery($"SELECT * FROM Apartments b WHERE EXISTS (SELECT a.id FROM Apartments a WHERE b.id = a.id AND a.price > {0} AND a.price < {999999} AND (( EXISTS (SELECT apartmentsid FROM Livings WHERE eviction < '{settlingStr}' AND apartmentsid = a.id) AND NOT EXISTS(SELECT apartmentsid FROM Bookings WHERE EXISTS (SELECT apartmentsid FROM Bookings WHERE apartmentsid = a.id))) OR (EXISTS (SELECT apartmentsid FROM Bookings WHERE settling > '{evictionStr}' AND apartmentsid = a.id) OR ( EXISTS (SELECT apartmentsid FROM Bookings WHERE eviction < '{settlingStr}' AND apartmentsid = a.id))) AND NOT EXISTS(SELECT apartmentsid FROM Livings WHERE EXISTS (SELECT apartmentsid FROM Livings WHERE apartmentsid = a.id)) OR (( EXISTS (SELECT apartmentsid FROM Livings WHERE eviction<'{settlingStr}' AND apartmentsid = a.id)) AND ( EXISTS (SELECT apartmentsid FROM Bookings WHERE settling>'{evictionStr}' AND apartmentsid = a.id ) OR ( EXISTS (SELECT apartmentsid FROM Bookings WHERE eviction<'{settlingStr}' AND apartmentsid = a.id)))) OR ( NOT EXISTS (SELECT apartmentsid FROM Livings WHERE apartmentsid = a.id) AND NOT EXISTS (SELECT apartmentsid FROM Bookings WHERE apartmentsid = a.id))))");
                List <Apartments>       apartments      = new List <Apartments>();
                foreach (Apartments apt in apartmentsQuery.ToList())
                {
                    apartments.Add(db.Apartments.Include(a => a.ApartmentType).ToList().Find(x => x.Id == apt.Id));
                }
                return(View("~/Views/RegisterNewBooking/BookingAvailableApartments.cshtml", apartments));
            }

            return(View("~/Views/RegisterNewBooking/BookingDateChooser.cshtml"));
        }
Пример #3
0
        public override int countSQL(string sql, object dbSet)
        {
            DbSqlQuery <publisher> DbPub = ((DbSet <publisher>)dbSet)
                                           .SqlQuery(sql);

            return(DbPub.Count());
        }
Пример #4
0
 public static DbSqlQuery <TEntity> ApplyTracking <TEntity>(this DbSqlQuery <TEntity> query, bool tracking)
     where TEntity : class
 {
     return(tracking
         ? query
         : query.AsNoTracking());
 }
Пример #5
0
        public DbSqlQuery <T> GetWhere(int from, int count, params object[] keys)
        {
            var sql = new DbSqlQuery <T>(this);

            _mapper.Where(sql, keys);
            sql.SelectAll();
            if (from != -1 && count != int.MaxValue)
            {
                sql.SetFirstResult(from);
                sql.SetMaxResults(count);
            }
            return(sql);
        }
Пример #6
0
        private static void DbSqlQuerySample()
        {
            using (Formula1Entities data = new Formula1Entities())
            {
                data.Database.Log = Console.Write;

                string country = "Brazil";
                // DbSqlQuery<Racer> racers = data.Racers.SqlQuery("SELECT * FROM Racers WHERE nationality = @country", new SqlParameter("country", country));
                DbSqlQuery <Racer> racers = data.Racers.SqlQuery("SELECT * FROM Racers WHERE nationality = @p0", country).AsNoTracking();

                foreach (var r in racers)
                {
                    Console.WriteLine("{0} {1}", r.FirstName, r.LastName);
                }
            }
        }
        //GET: Template code to serialize AG Grid's JSON object onGridReady
        public JsonResult GetTableLayoutJson(string currentGrid)
        {
            //get current user
            string currentUserId = User.Identity.GetUserId();

            //"Select[JsonLayoutInstructions], [CustomTableLayoutId], [AspNetUsersId], [GridName] from [CustomTableLayout] where [AspNetUsersId] = \'" + currentUserId + "\' AND [GridName] = \'" + currentGrid + "\'"
            DbSqlQuery <CustomTableLayout> customLayout = db.CustomTableLayouts.SqlQuery("Select[JsonLayoutInstructions], [CustomTableLayoutId], [AspNetUsersId], [GridName] from [CustomTableLayout] where [AspNetUsersId] = \'" + currentUserId + "\' AND [GridName] = \'" + currentGrid + "\'");

            var output = JsonConvert.SerializeObject(customLayout, Formatting.Indented,
                                                     new JsonSerializerSettings()
            {
                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
            }
                                                     );

            return(Json(output, JsonRequestBehavior.AllowGet));
        }
Пример #8
0
        // GET: Home/Login
        public ActionResult Login(string username, string password)
        {
            Session.RemoveAll();
            DatabaseContext   userDbContext = new DatabaseContext();
            DbSqlQuery <User> result        = userDbContext.Users.SqlQuery("Select * from Users where username = @p0", username);

            if (!result.Any())
            {
                return(Redirect("Index"));
            }
            if (result.First().Password != password)
            {
                return(Redirect("Index"));
            }
            Session.Add("userInfo", result.First());
            return(Redirect("Info"));
        }
Пример #9
0
        /// <summary>
        ///     Return the result of the <paramref name="query" /> from the cache. If the query is not cached yet, the query
        ///     is materialized and cached before being returned.
        /// </summary>
        /// <typeparam name="T">The generic type of the query.</typeparam>
        /// <param name="query">The query to cache the result.</param>
        /// <param name="policy">The eviction details for the cached result.</param>
        /// <param name="tags">(Optional) The tag list that can be used to expire cached result.</param>
        /// <returns>The result of the query.</returns>
        public static IEnumerable <T> FromCache <T>(this DbSqlQuery <T> query, CacheItemPolicy policy, params string[] tags) where T : class
        {
            if (!QueryCacheManager.IsEnabled)
            {
                return(query.AsNoTracking().ToList());
            }
            var key = QueryCacheManager.GetCacheKey(query, tags);

            var item = QueryCacheManager.Get <List <T> >(key);

            if (item == null)
            {
                item = query.AsNoTracking().ToList();
                item = QueryCacheManager.AddOrGetExisting(key, item, policy) ?? item;
                QueryCacheManager.AddCacheTag(key, tags);
            }

            return((IEnumerable <T>)item);
        }
Пример #10
0
        // GET: api/SASSensors
        public IQueryable <SASSensor> GetSASSensor([FromUri] string till = "0", string during = "1")
        {
            var      reqUri          = this.Request.RequestUri;
            var      paq             = reqUri.PathAndQuery;
            DateTime specStartTime   = DateTime.Now;
            DateTime specEndTime     = DateTime.Now;
            int      paramStartIndex = paq.LastIndexOf("?");

            if (paramStartIndex > 0)
            {
                paq = paq.Split('?').First();
                double tempt, tempd;
                if (!double.TryParse(till, out tempt) || !double.TryParse(during, out tempd))
                {
                    throw new ArgumentOutOfRangeException("parameters should be real value!");
                }
            }
            var st = double.Parse(till);
            var sd = double.Parse(during);

            specEndTime   = specEndTime.Subtract(TimeSpan.FromDays(st));
            specStartTime = specEndTime.Subtract(TimeSpan.FromDays(sd));

            string                 sql       = "select * from SASSensor where time >= @starttime AND time <= @endtime";
            SqlParameter           startTime = new SqlParameter("starttime", specStartTime);
            SqlParameter           endTime   = new SqlParameter("endtime", specEndTime);
            DbSqlQuery <SASSensor> result    = null;

            if (paq.Split('/').Last().ToLower() == "sassensors")
            {
                result = db.SASSensor.SqlQuery(sql, startTime, endTime);
            }
            else
            {
                SqlParameter targetId = new SqlParameter("targetId", paq.Split('/').Last());
                sql   += " AND CONVERT(nvarchar(20),deviceId) = @targetId";
                result = db.SASSensor.SqlQuery(sql, startTime, endTime, targetId);
            }
            return(result.AsQueryable());
            //          return db.SASSensor;
        }
Пример #11
0
        private async Task RunAsync(CancellationToken cancellationToken)
        {
            CheckInContext db = new CheckInContext();

            while (!cancellationToken.IsCancellationRequested)
            {
                Trace.TraceInformation("Working");

                DbSqlQuery <UserCheckIn> query = db.UserCheckIns.SqlQuery("SELECT * FROM dbo.UserCheckIns WHERE returnTime <= @p0", DateTime.UtcNow);

                List <UserCheckIn> expiredCheckIns = query.ToList();

                foreach (UserCheckIn checkIn in expiredCheckIns)
                {
                    sendMissingEmail(checkIn);
                    db.UserCheckIns.Remove(checkIn);
                    db.SaveChanges();
                }

                await Task.Delay(checkEvery * 1000);
            }
        }
Пример #12
0
        // GET api/Product
        public IEnumerable <Product> Get(String orderby = null, string dir = "ASC")
        {
            if (orderby == null)
            {
                return(entities.Products.ToList());
            }
            else
            //return entities.Products.OrderBy(p => p.ProductName).ToList();
            {
                //using(EntityConnection connection = new EntityConnection("Name= NorthwindEntities"))
                //{
                //string sql = "select VALUE Product from entities.Products as Product" +
                //             "order by Product." + orderby + " " + dir; //ESQL -> Entity SQL
                //ObjectContext oc = new ObjectContext(connection);
                //ObjectQuery<Product> query = new ObjectQuery<Product>(sql, oc);

                //return query.ToList(); ;
                //}
                DbSqlQuery <Product> sq = entities.Products.SqlQuery
                                              ("select * from Products order by " + orderby + " " + dir);//TSQL
                return(sq.ToList());
            }
        }
Пример #13
0
        /// <summary>
        ///     Return the result of the <paramref name="query" /> from the cache. If the query is not cached yet, the query
        ///     is materialized and cached before being returned.
        /// </summary>
        /// <typeparam name="T">The generic type of the query.</typeparam>
        /// <param name="query">The query to cache the result.</param>
        /// <param name="policy">The eviction details for the cached result.</param>
        /// <param name="tags">(Optional) The tag list that can be used to expire cached result.</param>
        /// <returns>The result of the query.</returns>
        public static IEnumerable <T> FromCache <T>(this DbSqlQuery <T> query, CacheItemPolicy policy, params string[] tags) where T : class
        {
            if (!QueryCacheManager.IsEnabled)
            {
                return(query.AsNoTracking().ToList());
            }
            var key = QueryCacheManager.GetCacheKey(query, tags);

            var item = QueryCacheManager.Get <List <T> >(key);

            if (item == null)
            {
                using (var handler = new QueryCacheItemTracker().Initialize(query))
                {
                    item = query.AsNoTracking().ToList();
                    item = QueryCacheManager.AddOrGetExisting(key, item, policy) ?? item;
                    QueryCacheManager.AddCacheTag(handler, key, tags);
                    QueryCacheManager.AddCacheTag(key, typeof(T).Name + QueryCacheManager.CacheTypeSuffix);
                }
            }

            return((IEnumerable <T>)item);
        }
Пример #14
0
        /// <summary>
        ///     Return the result of the <paramref name="query" /> from the cache. If the query is not cached yet, the query
        ///     is materialized and cached before being returned.
        /// </summary>
        /// <typeparam name="T">The generic type of the query.</typeparam>
        /// <param name="query">The query to cache the result.</param>
        /// <param name="absoluteExpiration">The fixed date and time at which the cache entry will expire.</param>
        /// <param name="tags">(Optional) The tag list that can be used to expire cached result.</param>
        /// <returns>The result of the query.</returns>
        public static IEnumerable <T> FromCache <T>(this DbSqlQuery <T> query, DateTimeOffset absoluteExpiration, params string[] tags) where T : class
        {
            if (!QueryCacheManager.IsEnabled)
            {
                return(query.AsNoTracking().ToList());
            }

            var key = QueryCacheManager.GetCacheKey(query, tags);

            var item = QueryCacheManager.Get <List <T> >(key);

            if (item == null)
            {
                using (var handler = new QueryCacheItemTracker().Initialize(query))
                {
                    item = query.AsNoTracking().ToList();
                    item = QueryCacheManager.AddOrGetExisting(key, item, absoluteExpiration) ?? item;
                    QueryCacheManager.AddCacheTag(handler, key, tags);
                }
            }

            return((IEnumerable <T>)item);
        }
Пример #15
0
        public static string GetCacheKey <T>(DbSqlQuery <T> query, string[] tags) where T : class
        {
            var sb = new StringBuilder();

            var queryCacheUniqueKeyMethod = query.GetType().GetMethod("GetQueryCacheUniqueKey", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

            if (queryCacheUniqueKeyMethod != null)
            {
                var queryCacheUniqueKey = (string)queryCacheUniqueKeyMethod.Invoke(query, new object[] { tags });

                if (!string.IsNullOrEmpty(queryCacheUniqueKey))
                {
                    return(queryCacheUniqueKey);
                }
            }

            if (IsCommandInfoOptionalForCacheKey && !UseFirstTagAsCacheKey && !UseTagsAsCacheKey)
            {
                throw new Exception(ExceptionMessage.QueryCache_IsCommandInfoOptionalForCacheKey_Invalid);
            }

            sb.AppendLine(CachePrefix);
            sb.AppendLine(query.GetType().Name + ";");

            var internalQueryProperty = query.GetType().BaseType.GetProperty("InternalQuery", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            var internalQuery         = internalQueryProperty.GetValue(query, null);

            var sqlProperty        = internalQuery.GetType().GetProperty("Sql", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            var parametersProperty = internalQuery.GetType().GetProperty("Parameters", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

            var sql        = (string)sqlProperty.GetValue(internalQuery, null);
            var parameters = (object[])parametersProperty.GetValue(internalQuery, null);

            sb.Append(sql);
            foreach (DbParameter parameter in parameters)
            {
                sb.Append(parameter.ParameterName);
                sb.Append(";");
                sb.Append(parameter.Value);
                sb.AppendLine(";");
            }

            //var objectQuery = IsCommandInfoOptionalForCacheKey ? query.GetObjectQuerySafe() : query.GetObjectQuery();

            //if (IncludeConnectionInCacheKey && objectQuery != null)
            //{
            //    sb.AppendLine(GetConnectionStringForCacheKey(query));
            //}

            if (UseFirstTagAsCacheKey)
            {
                if (tags == null || tags.Length == 0 || string.IsNullOrEmpty(tags[0]))
                {
                    throw new Exception(ExceptionMessage.QueryCache_FirstTagNullOrEmpty);
                }

                sb.AppendLine(tags[0]);
                return(sb.ToString());
            }

            if (UseTagsAsCacheKey)
            {
                if (tags == null || tags.Length == 0 || tags.Any(string.IsNullOrEmpty))
                {
                    throw new Exception(ExceptionMessage.QueryCache_UseTagsNullOrEmpty);
                }

                sb.AppendLine(string.Join(";", tags));
                return(sb.ToString());
            }

            sb.AppendLine(string.Join(";", tags));

            return(sb.ToString());
        }
Пример #16
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            Type objectType = validationContext.ObjectType;

            if (objectType.BaseType != typeof(object))
            {
                objectType = objectType.BaseType;
            }
            Console.Write(objectType.Name);
            string objectName = objectType.Name;

            if (!string.IsNullOrEmpty(validationContext.MemberName))
            {
                PropertyInfo currentProperty = objectType.GetProperty(validationContext.MemberName);

                if (currentProperty != null && currentProperty.GetGetMethod().IsVirtual)
                {
                    return(null);
                }
            }

            Context context = new Context();

            DbSet  set        = context.Set(objectType);
            string schemaName = "dbo";

            if (objectType.GetCustomAttributes(typeof(TableAttribute), true).Length > 0)
            {
                TableAttribute tableAttribute = objectType.GetCustomAttributes(typeof(TableAttribute), true)[0] as TableAttribute;
                schemaName = tableAttribute.Schema;
            }

            StringBuilder queryBuilder = new StringBuilder("SELECT ");

            PropertyInfo[] propertyInfos      = validationContext.ObjectType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            bool           hasAddedFirstField = false;

            for (int i = 0; i < propertyInfos.Length; i++)
            {
                if (propertyInfos[i].GetGetMethod().IsVirtual)
                {
                    continue;
                }

                if (hasAddedFirstField)
                {
                    queryBuilder.Append(", ");
                }

                hasAddedFirstField = true;

                queryBuilder.Append($"[{propertyInfos[i].Name}]");
            }

            queryBuilder.Append($" FROM [{schemaName}].[{objectName}] WHERE ");

            List <object> parameters = new List <object>();

            for (int i = 0; i < UniqueFields.Length; i++)
            {
                if (i != 0)
                {
                    queryBuilder.Append(" AND ");
                }

                object propertyValue = validationContext.ObjectType.GetProperty(UniqueFields[i]).GetValue(validationContext.ObjectInstance);

                if (propertyValue != null)
                {
                    queryBuilder.Append(string.Format("[{0}]=@{1}", UniqueFields[i], parameters.Count));
                    parameters.Add(new SqlParameter(string.Format("@{0}", parameters.Count), propertyValue));
                }
                else
                {
                    queryBuilder.Append(string.Format("[{0}] IS NULL", UniqueFields[i]));
                }
            }

            object primaryKey = validationContext.ObjectType.GetProperty($"{objectName}ID").GetValue(validationContext.ObjectInstance);

            if (primaryKey != null)
            {
                queryBuilder.Append($" AND {objectName}ID != @{parameters.Count}");
                parameters.Add(new SqlParameter($"@{parameters.Count}", primaryKey));
            }

            DbSqlQuery dbRawSqlQuery = set.SqlQuery(queryBuilder.ToString(), parameters.ToArray());
            bool       isUnique      = true;

            foreach (var item in dbRawSqlQuery.AsNoTracking())
            {
                isUnique = false;
                break;
            }

            if (!isUnique)
            {
                StringBuilder errorBuilder = new StringBuilder();
                for (int i = 0; i < UniqueFields.Length; i++)
                {
                    if (i != 0)
                    {
                        errorBuilder.Append(", ");
                    }

                    errorBuilder.Append(UniqueFields[i]);
                }

                errorBuilder.Append(" must be unique");

                return(new ValidationResult(errorBuilder.ToString(), UniqueFields));
            }

            return(null);
        }
Пример #17
0
        public JsonResult llenaGrid(int lineaNegocio, int start, int limit, string NombrePantalla, string ColumnaModificada, string Valor_Nuevo, string Valor_Anterior,
                                    string Fecha, string Direccion_IP, string Accion, string Usuario)
        {
            List <object> listaParametros = new List <object>();
            object        respuesta       = null;
            int           total;
            Consultas     aux      = new Consultas();
            StringBuilder consulta = new StringBuilder();
            Dictionary <string, string> auxFechas = new Dictionary <string, string>();


            try
            {
                StringBuilder consultaAnterior = new StringBuilder();
                consultaAnterior = (StringBuilder)Session["consulta"];
                LogActualizaciones tmp = new LogActualizaciones();
                tmp.NombrePantalla    = NombrePantalla;
                tmp.ColumnaModificada = ColumnaModificada;
                tmp.Valor_Nuevo       = Valor_Nuevo;
                tmp.Valor_Anterior    = Valor_Anterior;
                tmp.Direccion_IP      = Direccion_IP;
                tmp.Accion            = Accion;
                tmp.Usuario           = Usuario;
                auxFechas.Add("Fecha", Fecha);
                string consultaInicial = string.Empty;
                consulta = aux.consultaFinal(tmp, "WHERE Activo=@p0", auxFechas, out consultaInicial);

                if (consultaAnterior == null) // primera consulta
                {
                    Session["consulta"] = consulta;
                }
                else if (start != 0 && consultaAnterior.Equals(consulta)) // cuando se le da al paginar
                {
                    consulta = consultaAnterior;
                }
                else if (!consulta.Equals(consultaAnterior) && !consultaInicial.Equals(consulta.ToString()) && start == 0)
                {
                    Session["consulta"] = consulta;
                }
                else if (consulta.Length > consultaAnterior.Length)
                {
                    Session["consulta"] = consulta;
                }
                else if (!consulta.Equals(consultaAnterior) && !consulta.ToString().Equals(consultaInicial))
                {
                    Session["consulta"] = consulta;
                }
                else if (consulta.ToString().Equals(consultaInicial) && NombrePantalla != null)
                {
                    Session["consulta"] = consulta;
                }
                else
                {
                    consulta            = consultaAnterior;
                    Session["consulta"] = consulta;
                }

                DbSqlQuery <LogActualizaciones> catParametros = db.LogActualizaciones.SqlQuery(consulta.ToString(), 1);

                string lDia     = string.Empty;
                string lMes     = string.Empty;
                string lHora    = string.Empty;
                string lMinuto  = string.Empty;
                string lSegundo = string.Empty;

                foreach (var elemento in catParametros)
                {
                    int dia     = Convert.ToDateTime(elemento.Fecha).Day;
                    int mes     = Convert.ToDateTime(elemento.Fecha).Month;
                    int hora    = Convert.ToDateTime(elemento.Fecha).Hour;
                    int minuto  = Convert.ToDateTime(elemento.Fecha).Minute;
                    int segundo = Convert.ToDateTime(elemento.Fecha).Second;

                    lDia     = (dia >= 0 && dia < 9) ? ("0" + dia).ToString() : dia.ToString();
                    lMes     = (mes >= 0 && mes < 9) ? ("0" + mes).ToString() : mes.ToString();
                    lHora    = (hora >= 0 && hora < 9) ? ("0" + hora).ToString() : hora.ToString();
                    lMinuto  = (minuto >= 0 && minuto < 9) ? ("0" + minuto).ToString() : minuto.ToString();
                    lSegundo = (segundo >= 0 && segundo < 9) ? ("0" + segundo).ToString() : segundo.ToString();

                    listaParametros.Add(new
                    {
                        Id                = elemento.Id,
                        NombrePantalla    = elemento.NombrePantalla,
                        ColumnaModificada = elemento.ColumnaModificada,
                        Valor_Nuevo       = elemento.Valor_Nuevo,
                        Valor_Anterior    = elemento.Valor_Anterior,
                        Fecha             = lDia + "-" + lMes + "-" + Convert.ToDateTime(elemento.Fecha).Year + " " + lHora + ":" + lMinuto + ":" + lSegundo,
                        Direccion_IP      = elemento.Direccion_IP,
                        Accion            = elemento.Accion,
                        Usuario           = elemento.Usuario,
                        Activo            = elemento.Activo
                    });
                }
                total           = listaParametros.Count();
                listaParametros = listaParametros.Skip(start).Take(limit).ToList();
                respuesta       = new { success = true, results = listaParametros, total = total };
            }
            catch (Exception ex)
            {
                respuesta = new { success = false, results = ex.Message.ToString() };
            }

            return(Json(respuesta, JsonRequestBehavior.AllowGet));
        }
Пример #18
0
 /// <summary>
 ///     Return the result of the <paramref name="query" /> from the cache. If the query is not cached yet, the query
 ///     is materialized and cached before being returned.
 /// </summary>
 /// <typeparam name="T">The generic type of the query.</typeparam>
 /// <param name="query">The query to cache the result.</param>
 /// <param name="tags">The tag list that can be used to expire cached result.</param>
 /// <returns>The result of the query.</returns>
 public static IEnumerable <T> FromCache <T>(this DbSqlQuery <T> query, params string[] tags) where T : class
 {
     return(query.FromCache(QueryCacheManager.DefaultCacheItemPolicy, tags));
 }
 public  virtual IQueryable<T> GetAll()
 {
     DbSqlQuery<T> queryTest = _entities.Set<T>().SqlQuery(sqlstr);