Exemple #1
0
        public string PrintExpenseList(KendoFilterRequestDto Request)
        {
            using (EAharaDB context = new EAharaDB())
            {
                ReportDocument rd = new ReportDocument();

                var expenses = context.CompanyExpenses.Where(x => x.IsActive && (DbFunctions.TruncateTime(x.Date)) >= (DbFunctions.TruncateTime(Request.FromDate)) &&
                                                             (DbFunctions.TruncateTime(x.Date)) <= (DbFunctions.TruncateTime(Request.ToDate)));

                long[] items = expenses.Select(x => x.Id).ToArray();

                Guid   id1        = Guid.NewGuid();
                var    pdfName    = "ExpenseList" + id1 + ".pdf";
                string strRptPath = System.Web.HttpContext.Current.Server.MapPath("~/") + "Reports\\" + "ExpenseList" + ".rpt";
                string strPdfPath = System.Web.HttpContext.Current.Server.MapPath("~/") + "Reports\\" + pdfName;

                rd.Load(strRptPath);
                rd.Refresh();

                string connectionString =
                    ConfigurationManager.ConnectionStrings["EAharaDB"].ConnectionString;

                SqlConnectionStringBuilder SConn = new SqlConnectionStringBuilder(connectionString);

                rd.DataSourceConnections[0].SetConnection(
                    SConn.DataSource, SConn.InitialCatalog, SConn.UserID, SConn.Password);

                foreach (ReportDocument srd in rd.Subreports)
                {
                    srd.DataSourceConnections[0].SetConnection(SConn.DataSource, SConn.InitialCatalog, SConn.UserID, SConn.Password);
                }
                rd.SetParameterValue(0, items);
                System.IO.File.Delete(strPdfPath);
                //rd.PrintOptions.PaperSize = PaperSize.PaperA4;
                rd.ExportToDisk(ExportFormatType.PortableDocFormat, strPdfPath);

                return(pdfName);
            }
        }
Exemple #2
0
 public List <Usuario> ObterUsuariosCadastraosHa(int dias)
 {
     return(contexto.Usuarios
            .Where(u => DbFunctions.DiffDays(u.DataCadastro, DateTime.Now) >= dias)
            .ToList());
 }
Exemple #3
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute(IJobExecutionContext context)
        {
            // Check Api connection first.
            if (!Zoom.ZoomAuthCheck())
            {
                context.Result = "Zoom API authentication error. Check API settings for Zoom Room plugin or try again later.";
                throw new Exception("Authentication failed for Zoom API. Please verify the API settings configured in the Zoom Room plugin are valid and correct.");
            }

            using (var rockContext = new RockContext())
            {
                #region Setup Variables

                int      jobId                  = context.JobDetail.Description.AsInteger();
                var      job                    = new ServiceJobService(rockContext).GetNoTracking(jobId);
                var      JobStartDateTime       = RockDateTime.Now;
                DateTime?lastSuccessRunDateTime = null;
                if (job != null && job.Guid != Rock.SystemGuid.ServiceJob.JOB_PULSE.AsGuid())
                {
                    lastSuccessRunDateTime = job.LastSuccessfulRunDateTime;
                }

                // get the last run date or yesterday
                var beginDateTime = lastSuccessRunDateTime ?? JobStartDateTime.AddDays(-1);

                var dataMap = context.JobDetail.JobDataMap;
                var daysOut = dataMap.GetIntegerFromString(AttributeKey.SyncDaysOut);
                webhookBaseUrl = Settings.GetWebhookUrl();
                var importMeetings = dataMap.GetBooleanFromString(AttributeKey.ImportMeetings);
                verboseLogging = dataMap.GetBooleanFromString(AttributeKey.VerboseLogging);
                var zrOccurrencesCancel = new List <RoomOccurrence>();
                reservationLocationEntityTypeId = new EntityTypeService(rockContext).GetNoTracking(com.bemaservices.RoomManagement.SystemGuid.EntityType.RESERVATION_LOCATION.AsGuid()).Id;

                var zoom            = Zoom.Api();
                var locationService = new LocationService(rockContext);
                var zrLocations     = locationService.Queryable()
                                      .AsNoTracking()
                                      .WhereAttributeValue(rockContext, a => a.Attribute.Key == "rocks.kfs.ZoomRoom" && a.Value != null && a.Value != "")
                                      .ToList();
                var zrLocationIds           = zrLocations.Select(l => l.Id).ToList();
                var linkedZoomRoomLocations = new Dictionary <int, string>();
                foreach (var loc in zrLocations)
                {
                    loc.LoadAttributes();
                    var zoomRoomDV = DefinedValueCache.Get(loc.GetAttributeValue("rocks.kfs.ZoomRoom").AsGuid());
                    linkedZoomRoomLocations.Add(loc.Id, zoomRoomDV.Value);
                }

                #endregion Setup Variables

                #region Mark Completed Occurrences

                var zrOccurrenceService  = new RoomOccurrenceService(rockContext);
                var completedOccurrences = zrOccurrenceService.Queryable()
                                           .Where(ro => ro.IsCompleted == false &&
                                                  DbFunctions.AddMinutes(ro.StartTime, ro.Duration) < beginDateTime);
                foreach (var occ in completedOccurrences)
                {
                    occ.IsCompleted = true;
                }
                rockContext.SaveChanges();

                #endregion Mark Completed Occurrences

                #region Cleanup

                var reservationLocationService = new ReservationLocationService(rockContext);
                var reservationLocationIds     = reservationLocationService.Queryable().AsNoTracking().Select(rl => rl.Id);

                // Delete any orphaned RoomOccurrences ( tied to invalid/deleted ReservationId )
                zrOccurrenceService = new RoomOccurrenceService(rockContext);
                var orphanedOccs = zrOccurrenceService.Queryable()
                                   .Where(ro => ro.EntityTypeId == reservationLocationEntityTypeId &&
                                          !reservationLocationIds.Any(id => id == ro.EntityId));
                if (orphanedOccs.Count() > 0)
                {
                    if (verboseLogging)
                    {
                        LogEvent(rockContext, "Zoom Room Reservation Sync", string.Format("Preparing to delete {0} orphaned RoomOccurrence(s)."));
                    }
                    zrOccurrenceService.DeleteRange(orphanedOccs);
                    var errors = new List <string>();
                    LogEvent(null, "Zoom Room Reservation Sync", string.Format("{0} orphaned RoomOccurrence(s) deleted.", orphanedOccs.Count()));
                    if (verboseLogging)
                    {
                        LogEvent(null, "Zoom Room Reservation Sync", "Deleting related Zoom Meetings.");
                    }
                    DeleteOccurrenceZoomMeetings(orphanedOccs, zoom);
                    rockContext.SaveChanges();
                }

                // Delete any active Room Occurrences tied to Zoom Meetings that no longer exist.
                var linkedOccurrences = zrOccurrenceService
                                        .Queryable()
                                        .AsNoTracking()
                                        .Where(ro => ro.EntityTypeId == reservationLocationEntityTypeId &&
                                               ro.ZoomMeetingId > 0 &&
                                               !ro.IsCompleted &&
                                               ro.StartTime >= beginDateTime);
                var zoomMeetings = new List <Meeting>();
                foreach (var zrl in linkedZoomRoomLocations)
                {
                    zoomMeetings.AddRange(zoom.GetZoomMeetings(zrl.Value, MeetingListType.Upcoming));
                }
                var zoomMeetingIds      = zoomMeetings.Select(m => m.Id).ToList();
                var orphanedOccurrences = linkedOccurrences.Where(ro => !zoomMeetingIds.Any(mid => mid == ro.ZoomMeetingId));
                if (orphanedOccurrences.Count() > 0)
                {
                    zrOccurrenceService.DeleteRange(orphanedOccurrences);
                    rockContext.SaveChanges();
                }

                // Attempt to create Zoom Room Meeting for any Room Occurrences that may have had previous issues.
                var unlinkedOccurrences = zrOccurrenceService
                                          .Queryable()
                                          .Where(ro => ro.EntityTypeId == reservationLocationEntityTypeId &&
                                                 (!ro.ZoomMeetingId.HasValue || ro.ZoomMeetingId <= 0) &&
                                                 !ro.IsCompleted &&
                                                 ro.StartTime >= beginDateTime &&
                                                 (ro.ZoomMeetingRequestStatus == ZoomMeetingRequestStatus.Failed || ro.ZoomMeetingRequestStatus == ZoomMeetingRequestStatus.ZoomRoomOffline));

                foreach (var rOcc in unlinkedOccurrences)
                {
                    var rLoc = reservationLocationService.Queryable("Location").FirstOrDefault(rl => rl.Id == rOcc.EntityId);
                    rLoc.Location.LoadAttributes();
                    rOcc.ZoomMeetingRequestStatus = ZoomMeetingRequestStatus.Requested;
                    var zoomRoomDV = DefinedValueCache.Get(rLoc.Location.GetAttributeValue("rocks.kfs.ZoomRoom").AsGuid());
                    CreateOccurrenceZoomMeeting(rOcc, zoomRoomDV, zoom);
                }
                if (unlinkedOccurrences.Count() > 0)
                {
                    rockContext.SaveChanges();
                }

                #endregion Cleanup

                #region External Zoom Meetings

                var scheduleService           = new ScheduleService(rockContext);
                var reservationService        = new ReservationService(rockContext);
                var reservationTypeService    = new ReservationTypeService(rockContext);
                var zoomImportReservationType = reservationTypeService.Get(RoomReservationType.ZOOMROOMIMPORT.AsGuid());

                // Create RoomOccurrences for any Zoom Room meetings created outside of Rock
                if (importMeetings && linkedZoomRoomLocations.Count > 0)
                {
                    var linkedMeetings   = linkedOccurrences.Select(ro => ro.ZoomMeetingId).ToList();
                    var zoomRoomMeetings = zoomMeetings.Where(m => m.Start_Time > beginDateTime);
                    var missingMeetings  = zoomRoomMeetings.Where(m => !linkedMeetings.Any(mid => mid == m.Id));
                    if (missingMeetings.Count() > 0)
                    {
                        foreach (var zrl in linkedZoomRoomLocations)
                        {
                            foreach (var meeting in missingMeetings.Where(m => m.Host_Id == zrl.Value))
                            {
                                // Build the iCal string as it is a required property on the Schedule for Room Reservation block to display the Reservation
                                var meetingLocalTime = meeting.Start_Time.UtcDateTime.ToLocalTime();
                                var calendarEvent    = new Event
                                {
                                    DtStart = new CalDateTime(meetingLocalTime),
                                    DtEnd   = new CalDateTime(meetingLocalTime.AddMinutes(meeting.Duration)),
                                    DtStamp = new CalDateTime(meetingLocalTime.Year, meetingLocalTime.Month, meetingLocalTime.Day)
                                };
                                var calendar = new Calendar();
                                calendar.Events.Add(calendarEvent);
                                var serializer = new CalendarSerializer(calendar);

                                var schedule = new Schedule
                                {
                                    Guid = Guid.NewGuid(),
                                    EffectiveStartDate = meetingLocalTime,
                                    EffectiveEndDate   = meetingLocalTime.AddMinutes(meeting.Duration),
                                    IsActive           = true,
                                    iCalendarContent   = serializer.SerializeToString()
                                };
                                scheduleService.Add(schedule);

                                var location       = locationService.Get(zrl.Key);
                                var newReservation = new Reservation
                                {
                                    Name = location.Name.Left(50),    // NOTE: Reservation.Name is limited to 50 chars but Location.Name is up to 100 chars.
                                    ReservationTypeId = zoomImportReservationType.Id,
                                    Guid            = Guid.NewGuid(),
                                    Schedule        = schedule,
                                    NumberAttending = 0,
                                    Note            = string.Format("Created from import of \"{0}\" meeting ({1}) from Zoom Room \"{2}\".", meeting.Topic, meeting.Id, zrl.Value),
                                    ApprovalState   = ReservationApprovalState.Approved
                                };
                                reservationService.Add(newReservation);

                                var reservationLocation = new ReservationLocation
                                {
                                    Reservation   = newReservation,
                                    Location      = location,
                                    ApprovalState = ReservationLocationApprovalState.Approved
                                };
                                reservationLocationService.Add(reservationLocation);
                                rockContext.SaveChanges();

                                var occurrence = new RoomOccurrence
                                {
                                    ZoomMeetingId = meeting.Id,
                                    EntityTypeId  = reservationLocationEntityTypeId,
                                    EntityId      = reservationLocation.Id,
                                    Schedule      = schedule,
                                    LocationId    = reservationLocation.LocationId,
                                    Topic         = meeting.Topic,
                                    StartTime     = meetingLocalTime,
                                    Password      = meeting.Password,
                                    Duration      = meeting.Duration,
                                    TimeZone      = meeting.Timezone
                                };
                                zrOccurrenceService.Add(occurrence);
                                rockContext.SaveChanges();
                            }
                        }
                    }
                }

                #endregion External Zoom Meetings

                #region Process Reservations

                var reservations = reservationService.Queryable("Schedule,ReservationLocations,ReservationType")
                                   .AsNoTracking()
                                   .Where(r => r.ModifiedDateTime >= beginDateTime &&
                                          r.ReservationTypeId != zoomImportReservationType.Id &&
                                          (r.ApprovalState == ReservationApprovalState.Approved ||
                                           (!r.ReservationType.IsReservationBookedOnApproval && r.ApprovalState != ReservationApprovalState.Cancelled && r.ApprovalState != ReservationApprovalState.Denied && r.ApprovalState != ReservationApprovalState.Draft)) &&
                                          r.ReservationLocations.Any(rl => zrLocationIds.Contains(rl.LocationId)) &&
                                          r.Schedule != null &&
                                          ((r.Schedule.EffectiveEndDate != null && r.Schedule.EffectiveEndDate > DbFunctions.AddDays(RockDateTime.Today, -1)) ||
                                           (r.Schedule.EffectiveEndDate == null && r.Schedule.EffectiveStartDate != null && r.Schedule.EffectiveStartDate > DbFunctions.AddDays(RockDateTime.Today, -1))))
                                   .ToList();
                var resLocationIdsToProcess = new List <int>();
                var zrOccurrencesAdded      = 0;
                if (verboseLogging)
                {
                    LogEvent(rockContext, "Zoom Room Reservation Sync", string.Format("{0} Room Reservation(s) to be processed", reservations.Count()));
                }
                foreach (var res in reservations)
                {
                    foreach (var rl in res.ReservationLocations.Where(rl => zrLocationIds.Contains(rl.LocationId)).ToList())
                    {
                        rl.Location.LoadAttributes();
                        var zoomRoomDV = DefinedValueCache.Get(rl.Location.AttributeValues.FirstOrDefault(v => v.Key == "rocks.kfs.ZoomRoom").Value.Value.AsGuid());
                        var zrPassword = zoomRoomDV.GetAttributeValue("rocks.kfs.ZoomMeetingPassword");
                        resLocationIdsToProcess.Add(rl.Id);
                        var resLocOccurrences = zrOccurrenceService.Queryable().Where(ro => ro.EntityTypeId == reservationLocationEntityTypeId && ro.EntityId == rl.Id);

                        // One-Time Schedule
                        if (res.Schedule.EffectiveEndDate is null || res.Schedule.EffectiveStartDate.Value == res.Schedule.EffectiveEndDate.Value)
                        {
                            var occurrence = new RoomOccurrence();
                            if (resLocOccurrences.Count() == 0)
                            {
                                occurrence = new RoomOccurrence
                                {
                                    Id                       = 0,
                                    EntityTypeId             = reservationLocationEntityTypeId,
                                    EntityId                 = rl.Id,
                                    ScheduleId               = res.ScheduleId,
                                    LocationId               = rl.LocationId,
                                    Topic                    = res.Name,
                                    StartTime                = res.Schedule.FirstStartDateTime.Value,
                                    Password                 = zrPassword,
                                    Duration                 = res.Schedule.DurationInMinutes,
                                    IsCompleted              = false,
                                    ZoomMeetingRequestStatus = ZoomMeetingRequestStatus.Requested
                                };
                                zrOccurrenceService.Add(occurrence);
                                rockContext.SaveChanges();
                                zrOccurrencesAdded++;

                                if (CreateOccurrenceZoomMeeting(occurrence, zoomRoomDV, zoom))
                                {
                                    rockContext.SaveChanges();
                                }
                            }
                            else
                            {
                                Meeting connectedMeeting = null;
                                var     updateMeeting    = false;
                                occurrence = resLocOccurrences.FirstOrDefault();
                                if (occurrence.ZoomMeetingId.HasValue && occurrence.ZoomMeetingId.Value > 0)
                                {
                                    connectedMeeting = zoomMeetings.FirstOrDefault(m => m.Id == occurrence.ZoomMeetingId.Value);
                                    if (connectedMeeting == null)
                                    {
                                        occurrence.ZoomMeetingId = null;
                                    }
                                }
                                if (occurrence.IsCompleted)
                                {
                                    occurrence.IsCompleted = false;
                                }
                                if (occurrence.ScheduleId != res.ScheduleId)
                                {
                                    occurrence.ScheduleId = res.ScheduleId;
                                }
                                if (occurrence.StartTime != res.Schedule.FirstStartDateTime.Value)
                                {
                                    occurrence.StartTime = res.Schedule.FirstStartDateTime.Value;
                                }
                                if (connectedMeeting != null && connectedMeeting.Start_Time != occurrence.StartTime.ToRockDateTimeOffset())
                                {
                                    connectedMeeting.Start_Time = occurrence.StartTime.ToRockDateTimeOffset();
                                    updateMeeting = true;
                                }
                                if (occurrence.Duration != res.Schedule.DurationInMinutes)
                                {
                                    occurrence.Duration = res.Schedule.DurationInMinutes;
                                    if (connectedMeeting != null)
                                    {
                                        connectedMeeting.Duration = res.Schedule.DurationInMinutes;
                                        updateMeeting             = true;
                                    }
                                }
                                if (occurrence.Topic != res.Name)
                                {
                                    occurrence.Topic = res.Name;
                                    if (connectedMeeting != null)
                                    {
                                        connectedMeeting.Topic = res.Name;
                                        updateMeeting          = true;
                                    }
                                }
                                if (updateMeeting)
                                {
                                    zoom.UpdateMeeting(connectedMeeting);
                                }
                            }
                        }
Exemple #4
0
        public List <Afspraak> AfsprakenVandaag()
        {
            DateTime dt    = DateTime.Now;
            var      query = (from a in context.Afspraak.Include(k => k.Klant).Include(m => m.Masseur).Include(ms => ms.SoortAfspraak).Include(k => k.Klant.Adres).Include(k => k.Klant.Adres.Gemeente).Include(a => a.Arrangement)
                              where a.Geannuleerd == false && a.Archief == false && SqlFunctions.DateDiff("DAY", dt.Date, DbFunctions.TruncateTime(a.DatumTijdstip)) == 0
                              orderby a.DatumTijdstip ascending
                              select a);

            return(query.ToList <Afspraak>());
        }
Exemple #5
0
        public List <Afspraak> VanafAfspraken(DateTime vanaf)
        {
            var query = (from a in context.Afspraak.Include(k => k.Klant).Include(m => m.Masseur).Include(ms => ms.SoortAfspraak).Include(k => k.Klant.Adres).Include(k => k.Klant.Adres.Gemeente).Include(a => a.Arrangement).Include(e => e.Extra)
                         where a.Geannuleerd == false && a.Archief == false && SqlFunctions.DateDiff("DAY", vanaf.Date, DbFunctions.TruncateTime(a.DatumTijdstip)) >= 0
                         orderby a.DatumTijdstip ascending
                         select a);

            return(query.ToList <Afspraak>());
        }
        public static void DbFunctions_ISNULL()
        {
            DbFunctionTools tools = new DbFunctionTools();
            Random          rnd   = new Random();

            {
                Console.WriteLine("Testing DbFunctions.ISNULL(char(n))...");

                {
                    mstring s1 = Utils.GenString(rnd.Next(1, 200));

                    List <DbValue> args = new List <DbValue>();
                    args.Add(tools.AllocValue(s1));
                    DbFunctionArguments fargs = new DbFunctionArguments(args);

                    DbValue   valOutput = DbFunctions.ISNULL(tools, fargs);
                    ByteSlice bs        = valOutput.Eval();
                    bool      output    = tools.GetInt(bs) != 0;

                    bool expected = false;

                    if (expected != output)
                    {
                        throw new Exception("DbFunctions.ISNULL(char(n)='" + s1.ToString() + "') has failed.  Expected result: " + expected.ToString() + ", but received: " + output.ToString());
                    }
                    else
                    {
                        Console.WriteLine("Expected results received.");
                    }
                }

                {
                    List <DbValue> args = new List <DbValue>();
                    args.Add(tools.AllocValue(ByteSlice.Prepare(new byte[] { 1 }), DbTypeID.CHARS));
                    DbFunctionArguments fargs = new DbFunctionArguments(args);

                    DbValue   valOutput = DbFunctions.ISNULL(tools, fargs);
                    ByteSlice bs        = valOutput.Eval();
                    bool      output    = tools.GetInt(bs) != 0;

                    bool expected = true;

                    if (expected != output)
                    {
                        throw new Exception("DbFunctions.ISNULL(char(n)=NULL) has failed.  Expected result: " + expected.ToString() + ", but received: " + output.ToString());
                    }
                    else
                    {
                        Console.WriteLine("Expected results received.");
                    }
                }
            }

            {
                Console.WriteLine("Testing DbFunctions.ISNULL(Int32)...");

                {
                    int x = rnd.Next(Int32.MinValue, Int32.MaxValue);

                    List <DbValue> args = new List <DbValue>();
                    args.Add(tools.AllocValue(x));
                    DbFunctionArguments fargs = new DbFunctionArguments(args);

                    DbValue   valOutput = DbFunctions.ISNULL(tools, fargs);
                    ByteSlice bs        = valOutput.Eval();
                    bool      output    = tools.GetInt(bs) != 0;

                    bool expected = false;

                    if (expected != output)
                    {
                        throw new Exception("DbFunctions.ISNULL(Int32=" + x.ToString() + ") has failed.  Expected result: " + expected.ToString() + ", but received: " + output.ToString());
                    }
                    else
                    {
                        Console.WriteLine("Expected results received.");
                    }
                }

                {
                    List <DbValue> args = new List <DbValue>();
                    args.Add(tools.AllocValue(ByteSlice.Prepare(new byte[] { 1 }), DbTypeID.INT));
                    DbFunctionArguments fargs = new DbFunctionArguments(args);

                    DbValue   valOutput = DbFunctions.ISNULL(tools, fargs);
                    ByteSlice bs        = valOutput.Eval();
                    bool      output    = tools.GetInt(bs) != 0;

                    bool expected = true;

                    if (expected != output)
                    {
                        throw new Exception("DbFunctions.ISNULL(Int32=NULL) has failed.  Expected result: " + expected.ToString() + ", but received: " + output.ToString());
                    }
                    else
                    {
                        Console.WriteLine("Expected results received.");
                    }
                }
            }

            {
                Console.WriteLine("Testing DbFunctions.ISNULL(Double)...");

                {
                    double x = rnd.NextDouble();

                    List <DbValue> args = new List <DbValue>();
                    args.Add(tools.AllocValue(x));
                    DbFunctionArguments fargs = new DbFunctionArguments(args);

                    DbValue   valOutput = DbFunctions.ISNULL(tools, fargs);
                    ByteSlice bs        = valOutput.Eval();
                    bool      output    = tools.GetInt(bs) != 0;

                    bool expected = false;

                    if (expected != output)
                    {
                        throw new Exception("DbFunctions.ISNULL(Double=" + x.ToString() + ") has failed.  Expected result: " + expected.ToString() + ", but received: " + output.ToString());
                    }
                    else
                    {
                        Console.WriteLine("Expected results received.");
                    }
                }

                {
                    List <DbValue> args = new List <DbValue>();
                    args.Add(tools.AllocValue(ByteSlice.Prepare(new byte[] { 1 }), DbTypeID.DOUBLE));
                    DbFunctionArguments fargs = new DbFunctionArguments(args);

                    DbValue   valOutput = DbFunctions.ISNULL(tools, fargs);
                    ByteSlice bs        = valOutput.Eval();
                    bool      output    = tools.GetInt(bs) != 0;

                    bool expected = true;

                    if (expected != output)
                    {
                        throw new Exception("DbFunctions.ISNULL(Double=NULL) has failed.  Expected result: " + expected.ToString() + ", but received: " + output.ToString());
                    }
                    else
                    {
                        Console.WriteLine("Expected results received.");
                    }
                }
            }

            {
                Console.WriteLine("Testing DbFunctions.ISNULL(Long)...");

                {
                    long x = DateTime.Now.Ticks;

                    List <DbValue> args = new List <DbValue>();
                    args.Add(tools.AllocValue(x));
                    DbFunctionArguments fargs = new DbFunctionArguments(args);

                    DbValue   valOutput = DbFunctions.ISNULL(tools, fargs);
                    ByteSlice bs        = valOutput.Eval();
                    bool      output    = tools.GetInt(bs) != 0;

                    bool expected = false;

                    if (expected != output)
                    {
                        throw new Exception("DbFunctions.ISNULL(Long=" + x.ToString() + ") has failed.  Expected result: " + expected.ToString() + ", but received: " + output.ToString());
                    }
                    else
                    {
                        Console.WriteLine("Expected results received.");
                    }
                }

                {
                    List <DbValue> args = new List <DbValue>();
                    args.Add(tools.AllocValue(ByteSlice.Prepare(new byte[] { 1 }), DbTypeID.LONG));
                    DbFunctionArguments fargs = new DbFunctionArguments(args);

                    DbValue   valOutput = DbFunctions.ISNULL(tools, fargs);
                    ByteSlice bs        = valOutput.Eval();
                    bool      output    = tools.GetInt(bs) != 0;

                    bool expected = true;

                    if (expected != output)
                    {
                        throw new Exception("DbFunctions.ISNULL(Long=NULL) has failed.  Expected result: " + expected.ToString() + ", but received: " + output.ToString());
                    }
                    else
                    {
                        Console.WriteLine("Expected results received.");
                    }
                }
            }
        }
Exemple #7
0
        public JsonResult Save(WorkShopGoldViewModel model)
        {
            var      currentUser = GetAuthenticatedUser();
            var      dateTime    = DateUtility.GetDateTime(model.date);
            Response response;

            using (var db = new KiaGalleryContext())
            {
                var boughtGold   = db.GoldBalance.Where(x => x.TradeType == TradeType.Buy && DbFunctions.TruncateTime(x.Date) == dateTime).Select(x => x.Weight).ToList().Sum();
                var soldGold     = db.GoldBalance.Where(x => x.TradeType == TradeType.Sell && DbFunctions.TruncateTime(x.Date) == dateTime).Select(x => x.Weight).ToList().Sum();
                var workshopGold = db.WorkShopGold.Where(x => DbFunctions.TruncateTime(x.Date) == dateTime).Select(x => x.Weight).ToList().Sum();
                var sum          = boughtGold - soldGold - workshopGold;
                if (model.weight <= sum)
                {
                    var entity = new WorkShopGold()
                    {
                        RemittanceType  = model.remittanceType,
                        WorkshopId      = model.workshopId,
                        BoughtGoldPrice = model.workShopBoughtGoldPrice,
                        GoldRate        = model.workShopGoldRate,
                        Weight          = model.weight,
                        CreateUserId    = currentUser.Id,
                        ModifyUserId    = currentUser.Id,
                        CreateDate      = DateTime.Now,
                        ModifyDate      = DateTime.Now,
                        Date            = dateTime
                    };
                    db.WorkShopGold.Add(entity);
                    db.SaveChanges();
                    response = new Response()
                    {
                        status  = 200,
                        message = "حواله طلا با موفقیت انجام شد."
                    };
                    return(Json(response, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    response = new Response()
                    {
                        status  = 500,
                        message = "مقدار طلای وارد شده بیشتر از موجودی طلا میباشد."
                    };
                }
            }
            return(Json(response, JsonRequestBehavior.AllowGet));
        }
Exemple #8
0
        public static List <AllRuns> GetCompletedTestRuns(DateTime?toDate, DateTime?fromDate, bool isAdmin)
        {
            List <AllRuns> configTestRuns = null;

            using (PnPTestAutomationEntities dc = new PnPTestAutomationEntities())
            {
                var configDetails = from configset in dc.TestConfigurationSets
                                    select new
                {
                    configset.Id,
                    configset.Name,
                    configset.Type,
                    configset.AnonymousAccess,
                    configset.TestCategory_Id,
                    configset.TestAuthentication_Id,
                    configset.Branch
                };

                if (!isAdmin)
                {
                    configDetails = configDetails.Where(c => c.AnonymousAccess == true);
                }

                var testResults = (from configset in configDetails
                                   join categorySet in dc.TestCategorySets on configset.TestCategory_Id equals categorySet.Id
                                   join authenticationset in dc.TestAuthenticationSets on configset.TestAuthentication_Id equals authenticationset.Id
                                   join testrunsets in dc.TestRunSets on configset.Id equals testrunsets.TestConfigurationId
                                   //where testrunsets.TestDate >= fromDate && testrunsets.Status >= 2
                                   where DbFunctions.AddMilliseconds(testrunsets.TestDate, (DbFunctions.DiffMilliseconds(TimeSpan.Zero, testrunsets.TestTime) ?? 0)) >= fromDate &&
                                   DbFunctions.AddMilliseconds(testrunsets.TestDate, (DbFunctions.DiffMilliseconds(TimeSpan.Zero, testrunsets.TestTime) ?? 0)) < toDate &&
                                   testrunsets.Status >= 2
                                   select new
                {
                    Status = testrunsets.Status,
                    Testdate = testrunsets.TestDate,
                    TestDuration = testrunsets.TestTime,
                    Passed = testrunsets.TestsPassed,
                    Skipped = testrunsets.TestsSkipped,
                    Failed = testrunsets.TestsFailed,
                    Log = (testrunsets.MSBuildLog != null ? true : false),
                    TestRunSetId = testrunsets.Id,
                    CId = testrunsets.TestConfigurationId,
                    cName = configset.Name,
                    CategoryName = categorySet.Name,
                    appOnly = authenticationset.AppOnly,
                    cType = configset.Type,
                    GithubBranch = configset.Branch
                }).OrderByDescending(t => t.Testdate).ToList();

                configTestRuns = (from testrunsets in testResults
                                  select new AllRuns
                {
                    Status = testrunsets.Status,
                    ConfiguratioName = testrunsets.cName,
                    GithubBranch = testrunsets.GithubBranch,
                    CategoryName = testrunsets.CategoryName,
                    AppOnly = Enum.GetName(typeof(AppOnly), testrunsets.appOnly),
                    Environment = Enum.GetName(typeof(EnvironmentType), testrunsets.cType),
                    Testdate = testrunsets.Testdate,
                    TestDuration = Convert.ToString(testrunsets.TestDuration),
                    Passed = (testrunsets.Passed != null ? testrunsets.Passed : 0),
                    Skipped = (testrunsets.Skipped != null ? testrunsets.Skipped : 0),
                    Failed = (testrunsets.Failed != null ? testrunsets.Failed : 0),
                    Log = testrunsets.Log,
                    TestRunSetId = testrunsets.TestRunSetId,
                    Tests = ((testrunsets.Passed != null ? testrunsets.Passed : 0)
                             + (testrunsets.Skipped != null ? testrunsets.Skipped : 0)
                             + (testrunsets.Failed != null ? testrunsets.Failed : 0))
                }).OrderByDescending(d => d.Testdate.Date).ThenByDescending(t => t.Testdate.TimeOfDay).ToList();
            }

            return(configTestRuns);
        }
Exemple #9
0
        //随访过期列表
        public ActionResult ListExpire()
        {
            string type = CommonFunc.SafeGetStringFromObj(Request.QueryString["type"]);

            ViewBag.type = type;
            Comm_Platform_Worker workerModel = Session["worker"] as Comm_Platform_Worker;
            string region_code    = CommonFunc.SafeGetStringFromObj(workerModel.region_code);
            string dell_user_name = CommonFunc.SafeGetStringFromObj(workerModel.user_name);

            int pageIndex  = CommonFunc.SafeGetIntFromObj(this.Request["pageIndex"], 1);
            int pageSize   = this.Request["pageSize"] == null ? PageSize.GetPageSize : int.Parse(Request["pageSize"]);
            int totalCount = 0;
            var list       = mT_BC_FollowupService.LoadPageEntities(pageSize, pageIndex, out totalCount, t => t.community_code.Contains(region_code), t => t.followup_date, false);

            if (type == "乳腺癌")
            {
                list = mT_BC_FollowupService.LoadPageEntities(pageSize, pageIndex, out totalCount, t => t.community_code.Contains(region_code) && DbFunctions.DiffDays(t.next_time, DateTime.Now) >= 0, t => t.followup_date, false);
            }
            int PageCount = Convert.ToInt32(Math.Ceiling((double)totalCount / pageSize));

            List <MT_BC_Followup> result = new List <MT_BC_Followup>();

            result.AddRange(list);
            PagerInfo pager = new PagerInfo();

            pager.PageIndex  = pageIndex;
            pager.PageSize   = pageSize;
            pager.TotalCount = totalCount;
            PagerQuery <PagerInfo, List <MT_BC_Followup> > query = new PagerQuery <PagerInfo, List <MT_BC_Followup> >(pager, result);

            ViewData.Model         = query;
            ViewBag.dell_user_name = dell_user_name;
            ViewBag.PageIndex      = pageIndex;
            ViewBag.PageSize       = pageSize;
            return(View());
        }
Exemple #10
0
        public HttpResponseMessage GetNutritionInfo(long date)
        {
            // Получаем смещение времени пользователя
            int timezoneOffset = RequestHelper.GetTimezoneOffset(Request);
            var zonedDateTime  = TimeHelper.ConvertFromUtc(TimeHelper.FromUnixMsToDateTime(date), timezoneOffset);
            var zonedDate      = zonedDateTime.Date;

            var foodDiaryEntries = unitOfWork.FoodDiaryEntryRepository.Get(
                f => (f.CreateUserId == currentUserId &&
                      DbFunctions.DiffDays(
                          // Выбрасываем время, оставляем только дату
                          DbFunctions.TruncateTime(
                              // Добавляем смещение временной зоны пользователя, получаем время из БД в часовом формате пользователя
                              DbFunctions.AddMinutes(f.Date, timezoneOffset)
                              ),
                          zonedDate) == 0),
                null,
                iF => iF.Food,
                iS => iS.Food.Servings
                );

            var consumedNInfo      = new NutritionInfoDTO();
            var plannedNInfo       = new NutritionInfoDTO();
            int plannedMealsCount  = 0;
            int consumedMealsCount = 0;

            if (foodDiaryEntries != null &&
                foodDiaryEntries.Count() > 0)
            {
                foreach (var entry in foodDiaryEntries)
                {
                    var serving = entry.Food.Servings.Where(s =>
                                                            (s.ServingId == entry.FtSelectedServingId && entry.FsSelectedServingId == 0) ||
                                                            (s.FSServingId == entry.FsSelectedServingId && entry.FtSelectedServingId == 0) ||
                                                            (s.ServingId == entry.FtSelectedServingId && entry.FsSelectedServingId != 0 && entry.FtSelectedServingId != 0)
                                                            ).SingleOrDefault();
                    if (serving != null)
                    {
                        if (entry.IsCompleted == true)
                        {
                            // Суммируем значения энергетической ценности уже потребленной еды.
                            consumedNInfo.Sum(serving, entry.FoodQty);
                            consumedMealsCount++;
                        }
                        else
                        {
                            // Суммируем значения энергетической ценности запланированной к потреблению еды.
                            plannedNInfo.Sum(serving, entry.FoodQty);
                            plannedMealsCount++;
                        }
                    }
                }

                #region __Округляем значения__
                // Consumed info.
                consumedNInfo.Round(2);
                // Planned info.
                plannedNInfo.Round(2);
                #endregion
            }

            return(Request.CreateResponse(
                       HttpStatusCode.OK,
                       new {
                consumedNInfo = consumedNInfo,
                plannedNInfo = plannedNInfo,
                plannedMealsCount = plannedMealsCount,
                consumedMealsCount = consumedMealsCount
            }));
        }
Exemple #11
0
        public static void Main(string[] args)
        {
            MyMoneyManagerEntities context = new MyMoneyManagerEntities();

            #region Calcolo report IPASE
            //var calcolo = context.Movimenti.Where(q => q.IDCategoriaIphase != null).GroupBy(q => q.IDCategoriaIphase).Sum(q => new { q. }q.Sum(e => e.Importo)).;
            //var calcoloipase = context.Movimenti.Where(q => q.IDCategoriaIphase != null).GroupBy(x => new { x.IDCategoriaIphase, DbFunctions.CreateDateTime(x.DataValuta.Value.Year, x.DataValuta.Value.Month, x.DataValuta.Value.Day, 0, 0, 0).Value.Year, DbFunctions.CreateDateTime(x.DataValuta.Value.Year, x.DataValuta.Value.Month, x.DataValuta.Value.Day, 0, 0, 0).Value.Month }).SelectMany(rr => rr.Select(r => new { IDCategoria = rr.Key.IDCategoriaIphase, Anno = rr.Key.Year, Mese = rr.Key.Month, Totale = rr.Sum(t => t.Importo) }));
            //foreach (var item in calcoloipase)
            //{
            //    tReportCategorieMeseIpase rep = new tReportCategorieMeseIpase();
            //    rep.IDCategoria = item.IDCategoria;
            //    rep.Anno = item.Anno;
            //    rep.Mese = item.Mese;
            //    rep.Importo = item.Totale;
            //    context.tReportCategorieMeseIpase.Add(rep);
            //}
            var collection = context.vReportCategorieUbi;
            foreach (var item in collection)
            {
                tReportCategorieMeseUbi rep = new tReportCategorieMeseUbi();
                rep.IDCategoria = item.IDCategoria;
                rep.Anno        = item.Anno;
                rep.Mese        = item.Mese;
                rep.Importo     = item.Totale;
                context.tReportCategorieMeseUbi.Add(rep);
            }
            context.SaveChanges();

            var collection2 = context.v_ReportCategorieIpase;
            foreach (var item in collection2)
            {
                tReportCategorieMeseIpase rep1 = new tReportCategorieMeseIpase();
                rep1.IDCategoria = item.IDCategoriaIphase;
                rep1.Anno        = item.Anno;
                rep1.Mese        = item.Mese;
                rep1.Importo     = item.Totale;
                context.tReportCategorieMeseIpase.Add(rep1);
            }
            context.SaveChanges();
            #endregion


            #region Calcolo report UBI
            //var calcolo = context.Movimenti.Where(q => q.IDCategoriaIphase != null).GroupBy(q => q.IDCategoriaIphase).Sum(q => new { q. }q.Sum(e => e.Importo)).;
            var calcoloubi = context.Movimenti.Where(q => q.IDCategoria != null).GroupBy(x => new { x.IDCategoria, DbFunctions.CreateDateTime(x.DataContabile.Value.Year, x.DataContabile.Value.Month, x.DataContabile.Value.Day, 0, 0, 0).Value.Year, DbFunctions.CreateDateTime(x.DataContabile.Value.Year, x.DataContabile.Value.Month, x.DataContabile.Value.Day, 0, 0, 0).Value.Month }).SelectMany(rr => rr.Select(r => new { IDCategoria = rr.Key.IDCategoria, Anno = rr.Key.Year, Mese = rr.Key.Month, Totale = rr.Sum(t => t.Importo) }));
            foreach (var item in calcoloubi)
            {
                tReportCategorieMeseUbi rep = new tReportCategorieMeseUbi();
                rep.IDCategoria = item.IDCategoria;
                rep.Anno        = item.Anno;
                rep.Mese        = item.Mese;
                rep.Importo     = item.Totale;
                context.tReportCategorieMeseUbi.Add(rep);
            }
            context.SaveChanges();
            #endregion
        }
Exemple #12
0
        public List <DOCUMENTO> ExecuteFilter(Int32?classe, Int32?idCat, Int32?idUsuario, String nome, DateTime?data, Int32?idFormato, String descricao, String ocr, Int32 idAss)
        {
            List <DOCUMENTO>       lista = new List <DOCUMENTO>();
            IQueryable <DOCUMENTO> query = Db.DOCUMENTO;

            if (classe != null)
            {
                query = query.Where(p => p.CLAS_CD_ID == classe);
            }
            if (idCat != null)
            {
                query = query.Where(p => p.CADO_CD_ID == idCat);
            }
            if (idUsuario != null)
            {
                query = query.Where(p => p.USUA_CD_ID == idUsuario);
            }
            if (!String.IsNullOrEmpty(nome))
            {
                query = query.Where(p => p.DOCU_NM_NOME.Contains(nome));
            }
            if (data != null)
            {
                query = query.Where(p => DbFunctions.TruncateTime(p.DOCU_DT_CADASTRO) == DbFunctions.TruncateTime(data));
            }
            if (idFormato != null)
            {
                query = query.Where(p => p.DOCU_IN_FORMATO == idUsuario);
            }
            if (!String.IsNullOrEmpty(descricao))
            {
                query = query.Where(p => p.DOCU_DS_DESCRICAO.Contains(descricao));
            }
            if (!String.IsNullOrEmpty(ocr))
            {
                query = query.Where(p => p.DOCU_TX_OCR.Contains(ocr));
            }
            if (query != null)
            {
                query = query.Where(p => p.ASSI_CD_ID == idAss);
                query = query.OrderBy(a => a.DOCU_NM_NOME);
                lista = query.ToList <DOCUMENTO>();
            }
            return(lista);
        }
 public static DbBool Average(this DbFunctions dbFunctions, DbBool value)
 {
     return(new DbBoolFunctionValue("avg", new[] { value }));
 }
 public static DbString Average(this DbFunctions dbFunctions, DbString value)
 {
     return(new DbStringFunctionValue("avg", new[] { value }));
 }
 public static DbInt Sum(this DbFunctions dbFunctions, DbInt value)
 {
     return(new DbIntFunctionValue("sum", new[] { value }));
 }
Exemple #16
0
        protected MonthRanking GetMonthRankingInner(int year, int month)
        {
            var thisMonth = new DateTime(year, month, 1);
            var monthEndDate = thisMonth.AddMonths(1).AddDays(-1);
            var model = new MonthRanking();
            var currentMonthData = _db.HistoryRankings.Where(h => DbFunctions.DiffMonths(h.RankDate, thisMonth) == 0 && DbFunctions.DiffYears(h.RankDate, thisMonth) == 0)
                .Select(h => new { HistoryRanking = h, PostCount = _db.Posts.Count(p => p.ItemId == h.BlogID && p.IdType == ItemType.Blog), Deleted = !_db.Blogs.Any(b => b.BlogID == h.BlogID) })
                .ToList();
            var name2nick = _blogUtil.GetNickNames(currentMonthData.Select(r => r.HistoryRanking.Author));
            var currentMonthRankingData = currentMonthData.Select(h => new RankingDisplay
            {
                Author = name2nick[h.HistoryRanking.Author],
                BlogDate = h.HistoryRanking.BlogDate,
                BlogID = h.HistoryRanking.BlogID,
                BlogThumb = h.HistoryRanking.BlogThumb,
                BlogTitle = h.HistoryRanking.BlogTitle,
                BlogVisit = h.HistoryRanking.BlogVisit,
                BlogUrl = Url.Action("Details", "Blog", new { id = h.HistoryRanking.BlogID }),
                RankDate = h.HistoryRanking.RankDate,
                Rating = h.HistoryRanking.Rating,
                PostCount = h.PostCount,
                RankType = h.HistoryRanking.RankType,
                Deleted = h.Deleted,
            });

            var dailyRanking = currentMonthRankingData.Where(d => d.RankType == HistoryRanking.Type.RankDaily).ToList();
            if (year == DateTime.Today.Year && month == DateTime.Today.Month)
            {
                var dayFromMonday = DateTime.Now.DayOfWeek - DayOfWeek.Monday;
                if (dayFromMonday < 0)
                    dayFromMonday += 7;
                monthEndDate = DateTime.Today.AddDays(-dayFromMonday);
                // If don't have today's ranking, read from 24h
                if (!dailyRanking.Any(h => h.RankDate.Date == DateTime.Today))
                {
                    dailyRanking.AddRange(currentMonthRankingData.Where(d => d.RankType == HistoryRanking.Type.Rank24h));
                }
            }
            model.MonthlyRankings = currentMonthRankingData.Where(d => d.RankType == HistoryRanking.Type.RankMonthly).ToList();
            model.DailyRankings = dailyRanking;
            model.WeeklyRankings = currentMonthRankingData.Where(d => d.RankType == HistoryRanking.Type.RankWeekly && d.RankDate < monthEndDate).ToList();
            return model;
        }
        private void SendMailAfterEnd(DateTime today, VsmartsellDBContext db)
        {
            var khs = from p in db.DSKhachHang
                      where p.Archive == false && (DbFunctions.TruncateTime(p.NgayHetHan) < DbFunctions.TruncateTime(today))
                      select p;

            khs = khs.Where(a => (DbFunctions.DiffDays(a.NgayHetHan, DbFunctions.AddDays(today, -1)) % 7) == 0);
            var    size = khs.Count();
            string msg  = "";

            if (size != 0)
            {
                foreach (var kh in khs)
                {
                    msg += "Khách hàng: " + kh.TenKH.ToUpper() + "  ---  Ngày hết hạn: " + kh.NgayHetHan.ToString("dd/MM/yyyy") +
                           "  ---  http://localhost:3469/vsmartsell/details/" + kh.MaKH + " \n";
                }
                var mails = from m in db.DSNoticeMail
                            where m.MailType == "afterend"
                            select m;
                var size2 = mails.Count();
                if (size2 > 0)
                {
                    string      Mail_from = "*****@*****.**";
                    string      password  = "******";
                    MailMessage MM        = new MailMessage();
                    MM.From = new MailAddress(Mail_from);
                    foreach (var mail in mails)
                    {
                        MM.To.Add(mail.Email);
                    }
                    string Mail_subject = "Nhắc nhở về những khách hàng đã hết hạn (" + today.ToLongDateString() + ")";
                    string Mail_body    = msg + "\nDanh sách trên là những khách hàng đã hết hạn sử dụng.\nThư này để nhắc nhở việc hỏi thăm những khách hàng trên có nhu cầu muốn tiếp tục sử dụng nữa không.\nThân.";
                    MM.Subject = Mail_subject;
                    MM.Body    = Mail_body;
                    SmtpClient SC = new SmtpClient();
                    SC.Host        = "Smtp.gmail.com";
                    SC.Port        = 587;
                    SC.Credentials = new System.Net.NetworkCredential(Mail_from, password);
                    SC.EnableSsl   = true;
                    SC.Send(MM);
                }
            }
        }
Exemple #18
0
        private SMSResult checkContentFarmer(SMSContent paser)
        {
            var result = new SMSResult()
            {
                status = 1
            };

            try
            {
                // so

                var cInfo = db.CInfoCommons.Where(p => p.Phone == paser.phone).FirstOrDefault();

                if (cInfo == null)
                {
                    return new SMSResult {
                               status = 1, message = "So dien thoai Quy Khach vua nhan tin chua dang ky tham gia Chuong trinh nhan tin cung voi Cong ty HAI. Chi tiet lien he NVTT hoac 1800577768"
                    }
                }
                ;

                if (cInfo.CType != "FARMER")
                {
                    return new SMSResult {
                               status = 1, message = "So dien thoai Quy Khach vua nhan tin chua dang ky tham gia Chuong trinh nhan tin cung voi Cong ty HAI. Chi tiet lien he NVTT hoac 1800577768"
                    }
                }
                ;


                // lay danh sach sự kiện phù hợp với user (theo khu vực)
                List <EventInfo> listEventUser = new List <EventInfo>();

                //var eventArea = db.EventAreaFarmers.Where(p => p.AreaId == cInfo.AreaId && p.EventInfo.ESTT == 1).ToList();
                var dateNow   = DateTime.Now;
                var eventArea = (from log in db.EventAreaFarmers
                                 where log.AreaId == cInfo.AreaId && log.EventInfo.ESTT == 1 && (DbFunctions.TruncateTime(log.EventInfo.BeginTime)
                                                                                                 <= DbFunctions.TruncateTime(dateNow) && DbFunctions.TruncateTime(log.EventInfo.EndTime)
                                                                                                 >= DbFunctions.TruncateTime(dateNow))
                                 select log).ToList();

                foreach (var item in eventArea)
                {
                    var cusJoin = db.EventCustomerFarmers.Where(p => p.EventId == item.EventId && p.CInfoCommon.AreaId == item.AreaId).ToList();

                    if (cusJoin.Count() > 0)
                    {
                        var cJoin = cusJoin.Where(p => p.CInfoId == cInfo.Id).FirstOrDefault();
                        if (cJoin != null)
                        {
                            listEventUser.Add(item.EventInfo);
                        }
                    }
                    else
                    {
                        listEventUser.Add(item.EventInfo);
                    }
                }



                if (listEventUser.Count() == 0)
                {
                    return new SMSResult {
                               status = 4, message = "Quy khach dang dung hang chinh hang. Cam on Quy khach da tin dung & ung ho hang cua cong ty CPND HAI"
                    }
                }
                ;

                // kiem tra ma dung, ma sau
                List <ProductSeri> righCode = new List <ProductSeri>();

                foreach (var item in paser.products)
                {
                    // lây mã seri // eventCode or seri
                    var productSeri = db.ProductSeris.Where(p => p.Code == item && p.IsUse == 0 && p.SeriType == 2).FirstOrDefault();


                    if (productSeri == null)
                    {
                        return(new SMSResult {
                            status = 4, message = "Ma " + item + " khong dung. Vui long kiem tra lai ma so nhan tin. Xin cam on"
                        });
                    }
                    else if (productSeri.IsUse == 1)
                    {
                        return(new SMSResult {
                            status = 4, message = "Ma " + item + " da duoc su dung vao (" + productSeri.ModifyTime + "), Vui long kiem tra lai ma so nhan tin. Xin cam on"
                        });
                    }
                    else
                    {
                        righCode.Add(productSeri);
                    }
                }

                Hashtable map = new Hashtable();

                List <string> productAttend = new List <string>();

                result.status = 5;

                foreach (var item in righCode)
                {
                    try
                    {
                        // cap nhat lịch su
                        var hEvent = new MSGPoint()
                        {
                            Id         = Guid.NewGuid().ToString(),
                            AcceptTime = DateTime.Now,
                            CInfoId    = cInfo.Id,
                            UserLogin  = paser.code,
                            ProductId  = item.ProductId,
                            Barcode    = item.Code,
                            MSGType    = "SMS"
                        };

                        List <MSGPointEvent> listPointEvent = new List <MSGPointEvent>();

                        foreach (var userEvent in listEventUser)
                        {
                            // kiem tra san pham co trong su kien nay ko
                            var productEvent = userEvent.EventProducts.Where(p => p.ProductId == item.ProductId).FirstOrDefault();
                            if (productEvent != null)
                            {
                                var pointEvemt = new MSGPointEvent()
                                {
                                    EventId    = userEvent.Id,
                                    MSGPointId = hEvent.Id,
                                    Point      = productEvent.Point
                                };
                                listPointEvent.Add(pointEvemt);
                            }
                        }
                        //

                        if (listPointEvent.Count() > 0)
                        {
                            if (!productAttend.Contains(item.ProductId))
                            {
                                productAttend.Add(item.ProductId);
                            }

                            item.IsUse           = 1;
                            item.ModifyTime      = DateTime.Now;
                            db.Entry(item).State = System.Data.Entity.EntityState.Modified;

                            db.MSGPoints.Add(hEvent);

                            db.SaveChanges();

                            foreach (var pevent in listPointEvent)
                            {
                                if (map.ContainsKey(pevent.EventId))
                                {
                                    var oldPoint = Convert.ToInt32(map[pevent.EventId]);
                                    map[pevent.EventId] = oldPoint + pevent.Point;
                                }
                                else
                                {
                                    map.Add(pevent.EventId, Convert.ToInt32(pevent.Point));
                                }

                                db.MSGPointEvents.Add(pevent);



                                // luu diem cho khach hang
                                var agencyPoint = db.AgencySavePoints.Where(p => p.EventId == pevent.EventId && p.CInfoId == cInfo.Id).FirstOrDefault();

                                if (agencyPoint == null)
                                {
                                    var newAgencyPoint = new AgencySavePoint()
                                    {
                                        EventId    = pevent.EventId,
                                        CInfoId    = cInfo.Id,
                                        PointSave  = pevent.Point,
                                        CreateTime = DateTime.Now
                                    };
                                    db.AgencySavePoints.Add(newAgencyPoint);
                                }
                                else
                                {
                                    var newPoint = agencyPoint.PointSave + pevent.Point;
                                    agencyPoint.PointSave       = newPoint;
                                    agencyPoint.ModifyTime      = DateTime.Now;
                                    db.Entry(agencyPoint).State = System.Data.Entity.EntityState.Modified;
                                }

                                db.SaveChanges();
                            }
                        }
                    }
                    catch
                    {
                    }
                }
                //

                // phan qua
                string pointEvent = "";
                int    countPoint = 0;
                foreach (var item in map.Keys)
                {
                    var eventInfo = db.EventInfoes.Find(item);

                    var savePoint = eventInfo.AgencySavePoints.Where(p => p.CInfoCommon.CCode == paser.code).FirstOrDefault();
                    int?point     = 0;
                    if (savePoint != null)
                    {
                        point = savePoint.PointSave;
                    }

                    string aWard     = "";
                    var    listAward = eventInfo.AwardInfoes.OrderByDescending(p => p.Point).ToList();
                    foreach (var aWardItem in listAward)
                    {
                        if (aWardItem.Point <= point)
                        {
                            aWard = ConvertToUnsign3(aWardItem.Name);
                            break;
                        }
                    }

                    var nameEvent = ConvertToUnsign3(eventInfo.Name);

                    if (!String.IsNullOrEmpty(aWard))
                    {
                        pointEvent = " , " + aWard + " tu " + nameEvent;
                    }


                    countPoint += Convert.ToInt32(map[item]);
                }


                //
                string msgReturn = "Chuc mung Quy khach vua tich luy " + countPoint + " diem tu ";
                foreach (string item in productAttend)
                {
                    var productCheck = db.ProductInfoes.Find(item);
                    if (productCheck != null)
                    {
                        msgReturn += ConvertToUnsign3(productCheck.PName) + " ,";
                    }
                }

                msgReturn = msgReturn.Remove(msgReturn.Count() - 1, 1);

                msgReturn += ". Cam on Quy khach da tin dung & ung ho hang cua cong ty CPND HAI. ";


                if (!String.IsNullOrEmpty(pointEvent))
                {
                    pointEvent = pointEvent.Remove(0, 2);
                    msgReturn += "Chuc mung Quy khach nhan duoc " + pointEvent + ". Cam on Quy khach da tin dung & ung ho hang cua cong ty CPND HAI.";
                }

                result.message = msgReturn;
            }
            catch (Exception e)
            {
                result.status  = 0;
                result.message = e.Message;
            }

            return(result);
        }
Exemple #19
0
        public JsonResult GetWorkShop(string date)
        {
            var dateTime = DateUtility.GetDateTime(date);

            Response response;

            using (var db = new KiaGalleryContext())
            {
                var query        = db.WorkShopGold.OrderByDescending(x => x.Id).Where(x => DbFunctions.TruncateTime(x.Date) == dateTime);
                var workShopList = query.GroupBy(x => x.WorkshopId).Select(x => new
                {
                    id   = x.Select(y => y.WorkshopId).FirstOrDefault(),
                    name = x.FirstOrDefault().Workshop.Name,
                    sum  = x.Sum(y => y.Weight)
                }).ToList();

                response = new Response()
                {
                    status = 200,
                    data   = new
                    {
                        list    = workShopList,
                        goldSum = workShopList.Sum(x => x.sum)
                    }
                };
            }
            return(Json(response, JsonRequestBehavior.AllowGet));
        }
        public static List <SalesVolumeMonthCategoryModel> GetSalesVolumeByMonthCategory(DateTime month)
        {
            DateTime start = new DateTime(month.Year, month.Month, 1);
            DateTime end   = start.AddYears(1);

            using (var context = new CosmeticSolutionSystemEntities())
            {
                //context.Database.Log = (log) => Debug.WriteLine(log);

                var queryX = from x in context.Categories
                             orderby x.CategoryName
                             select x.CategoryName;

                int i = 0;

                var listX = queryX.ToList();

                foreach (var x in listX)
                {
                    categoryArr[i] = x.ToString();
                    i++;
                }

                var query = (from x in context.SalesLines
                             where DbFunctions.TruncateTime(x.Sale.SelledAt) >= DbFunctions.TruncateTime(start) &&
                             DbFunctions.TruncateTime(x.Sale.SelledAt) <= DbFunctions.TruncateTime(end)
                             select new
                {
                    Date = x.Sale.SelledAt,
                    CategoryName = x.Product.Category.CategoryName,
                    Quantity = x.Quantity
                }).GroupBy(x => new { x.Date.Month, x.CategoryName }).Select
                                (group => new { group.FirstOrDefault().Date, group.FirstOrDefault().CategoryName, Quantity = group.Sum(x => x.Quantity) }
                                );

                var list = query.ToList();

                List <SalesVolumeMonthCategoryModel> model = new List <SalesVolumeMonthCategoryModel>();

                for (int y = 0; y < 12; y++)
                {
                    foreach (var item in categoryArr)
                    {
                        model.Add(new SalesVolumeMonthCategoryModel(start.AddMonths(y), item.ToString(), 0));
                    }
                }

                foreach (var x in list)
                {
                    SalesVolumeMonthCategoryModel categorymodel = model.Find(y => y.Date == new DateTime(x.Date.Year, x.Date.Month, 1) && y.CategoryName == x.CategoryName);

                    if (categorymodel != null)
                    {
                        categorymodel.Date         = new DateTime(x.Date.Year, x.Date.Month, 1);
                        categorymodel.CategoryName = x.CategoryName;
                        categorymodel.Quantity     = x.Quantity;
                    }
                }

                return(model);
            }
        }
        public async static Task <IEnumerable <ProductItemRow> > GetProductItemRowsAsync(int productId, int sectionId, int itemTypeId, string userId, ApplicationDbContext db = null)
        {
            if (db == null)
            {
                db = ApplicationDbContext.Create();
            }

            var today = DateTime.Now.Date;

            var items = await(from i in db.Items
                              join pi in db.ProductItems on i.Id equals pi.ItemId
                              join it in db.ItemTypes on i.ItemTypeId equals it.Id
                              join sp in db.SubscriptionProducts on pi.ProductId equals sp.ProductId
                              join us in db.UserSubscriptions on sp.SubscriptionId equals us.SubscriptionId
                              where i.SectionId.Equals(sectionId) &&
                              pi.ProductId.Equals(productId) &&
                              us.UserId.Equals(userId)
                              orderby i.PartId
                              select new ProductItemRow
            {
                ItemId      = i.Id,
                Description = i.Description,
                Title       = i.Title,
                Link        = it.Title.Equals("Download") ? i.Url : "/ProductContent/Content/" + pi.ProductId + "/" + i.Id,
                ImageUrl    = i.ImageUrl,
                ReleaseDate = DbFunctions.CreateDateTime(us.StartDate.Value.Year, us.StartDate.Value.Month, us.StartDate.Value.Day + i.WaitDays, 0, 0, 0),
                IsAvailable = DbFunctions.CreateDateTime(today.Year, today.Month, today.Day, 0, 0, 0) >= DbFunctions.CreateDateTime(us.StartDate.Value.Year, us.StartDate.Value.Month, us.StartDate.Value.Day + i.WaitDays, 0, 0, 0),
                IsDownload  = it.Title.Equals("Download")
            }).ToListAsync();

            return(items);
        }
Exemple #22
0
        public async Task <IEnumerable <Object> > GetConsultaParametrizadaConvocatoria(Convocatoria parametros)
        {
            try
            {
                var convocatorias = (from conv in _db.Convocatoria.AsNoTracking()
                                     .Include(e => e.TipoFuenteFinanciamiento)
                                     .Include(e => e.FondoPrograma)
                                     select conv);

                if (convocatorias != null)
                {
                    if (!String.IsNullOrEmpty(parametros.busquedaFecha))  //busqueda por fecha
                    {
                        convocatorias = convocatorias.Where(e => (DbFunctions.TruncateTime(e.FechaTermino) >= DbFunctions.TruncateTime(parametros.fechaInicioComparacion) &&
                                                                  DbFunctions.TruncateTime(e.FechaTermino) <= DbFunctions.TruncateTime(parametros.fechaFinalComparacion)));
                    }
                    if (!String.IsNullOrEmpty(parametros.NombreConvocatoria)) //busqueda por nombre de la convocatoria
                    {
                        var listaNombres = await GetConvocatoriasLikeNombreLatin1(parametros.NombreConvocatoria);

                        convocatorias = convocatorias.Where(e => listaNombres.Contains(e.ConvocatoriaId));
                    }

                    if (parametros.TipoFuenteFinanciamientoId != 0 && parametros.TipoFuenteFinanciamientoId != null)  //Busqueda por tipo de convocatoria
                    {
                        convocatorias = convocatorias.Where(e => e.TipoFuenteFinanciamientoId == parametros.TipoFuenteFinanciamientoId);
                    }

                    if (parametros.FondoProgramaId != 0)  //Busqueda por fondo programa
                    {
                        convocatorias = convocatorias.Where(e => e.FondoProgramaId == parametros.FondoProgramaId);
                    }

                    //******Se inicia el proceso de proyeccion******
                    //Los resultados lo guardaremos en una lista de X objeto
                    List <BusquedaParamsCR> datos = convocatorias.Select(x => new BusquedaParamsCR //Es una clase no mapeada que contiene caracteristicas
                                                                                                   //que nos permiten albergar SOLO los datos necesarios
                    {
                        ConvocatoriaId           = x.ConvocatoriaId,                               //Rescatamos los parametros que se requieren para el front
                        NombreConvocatoria       = x.NombreConvocatoria,
                        TipoFuenteFinanciamiento = x.TipoFuenteFinanciamiento.Nombre,
                        FechaTermino             = x.FechaTermino,
                        NombreFP = x.FondoPrograma.NombreFP,
                        Estado   = x.Estado,
                    }).ToList();

                    var listaFK = await(from t in _db.ContactoPorConvocatoria
                                        select new
                    {
                        ConvocatoriaId = t.ConvocatoriaId,
                        ContactoId     = t.ContactoId
                    }).AsNoTracking().ToListAsync();

                    foreach (var c in datos)
                    {
                        //obtenemos los fks de los contactos asociadas a la convocatoria
                        var fks = listaFK.Where(e => e.ConvocatoriaId == c.ConvocatoriaId).Select(e => e.ContactoId);

                        //Obtenemos la lista de nombres de los contactos
                        c.listaNombreContactos = await(from contacto in _db.Contacto
                                                       where fks.Contains(contacto.ContactoId)
                                                       select string.Concat(contacto.NombreContacto, " ", contacto.ApellidoPaterno, " ", contacto.ApellidoMaterno)).AsNoTracking().ToListAsync();
                    }

                    return(datos); //retornamos los datos, y al hacer esto ya no pasamos por el siguiente return (el de abajo)
                }
                return(null);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e);
            }
        }
Exemple #23
0
        public List <Afspraak> AfsprakenSpecifiekeDag(DateTime dag)
        {
            var query = (from a in context.Afspraak.Include(k => k.Klant).Include(m => m.Masseur).Include(ms => ms.SoortAfspraak).Include(k => k.Klant.Adres)
                         where a.Geannuleerd == false && a.Archief == false && SqlFunctions.DateDiff("DAY", dag.Date, DbFunctions.TruncateTime(a.DatumTijdstip)) == 0
                         orderby a.DatumTijdstip ascending
                         select a);

            return(query.ToList <Afspraak>());
        }
Exemple #24
0
        public static List <TwitterSnapshot> UpdateSnapshotsInDb(List <TwitterAccount> accounts)
        {
            // Get latest results
            List <TwitterSnapshot> snapshots = TwitterQuery.GetTwitterSnapshots(accounts);

            // Remove existing results from DB from today and save new ones
            using (SportsDataContext db = new SportsDataContext())
            {
                IEnumerable <TwitterSnapshot> snapshotsToRemove = from s in db.TwitterSnapshot_DbSet
                                                                  where DbFunctions.TruncateTime(s.DateOfSnapshot) == DbFunctions.TruncateTime(DateTime.UtcNow)
                                                                  select s;

                foreach (TwitterSnapshot snapshotToRemove in snapshotsToRemove)
                {
                    db.TwitterSnapshot_DbSet.Remove(snapshotToRemove);
                }

                //db.SaveChanges();

                foreach (TwitterSnapshot snapshotToAdd in snapshots)
                {
                    db.TwitterSnapshot_DbSet.Add(snapshotToAdd);
                }

                db.SaveChanges();
            }

            return(snapshots);
        }
        public IEnumerable <AppointmentsVM> GetAppointmentsByWeek(CalendarVM selection)
        {
            FillDB();

            List <AppointmentsVM> result = new List <AppointmentsVM>();
            int      dayTotalCapacity    = (selection.DoctorID != 0) ? 16 : db.Doctors.Count() * 16;
            DateTime monday = selection.Date.AddDays(-(int)selection.Date.DayOfWeek + (int)DayOfWeek.Monday);
            DateTime sunday = monday.AddDays(6);

            List <Appointment> apps = null;

            if (selection.DoctorID == 0)
            {
                apps = db.Appointments.Where(a => DbFunctions.TruncateTime(a.Date) >= monday.Date && DbFunctions.TruncateTime(a.Date) <= sunday.Date).ToList();
            }
            else
            {
                apps = db.Appointments.Where(a => DbFunctions.TruncateTime(a.Date) >= monday.Date && DbFunctions.TruncateTime(a.Date) <= sunday.Date && a.DoctorID == selection.DoctorID).ToList();
            }

            AppointmentsVM app;
            DateTime       day;

            for (int i = 0; i < 7; i++)
            {
                app               = new AppointmentsVM();
                day               = monday.AddDays(i);
                app.Period        = day.DayOfWeek.ToString() + ", " + day.ToString("MM/dd/yyy");
                app.TotalCapacity = dayTotalCapacity;
                app.Appointments  = apps.Where(a => a.Date.Date == day.Date).Count();
                result.Add(app);
            }
            return(result);
        }
Exemple #26
0
        protected override IEnumerable <RuleDescriptor> LoadDescriptors()
        {
            var stores = _services.StoreService.GetAllStores()
                         .Select(x => new RuleValueSelectListOption {
                Value = x.Id.ToString(), Text = x.Name
            })
                         .ToArray();

            var vatNumberStatus = ((VatNumberStatus[])Enum.GetValues(typeof(VatNumberStatus)))
                                  .Select(x => new RuleValueSelectListOption {
                Value = ((int)x).ToString(), Text = x.GetLocalizedEnum(_services.Localization)
            })
                                  .ToArray();

            var taxDisplayTypes = ((TaxDisplayType[])Enum.GetValues(typeof(TaxDisplayType)))
                                  .Select(x => new RuleValueSelectListOption {
                Value = ((int)x).ToString(), Text = x.GetLocalizedEnum(_services.Localization)
            })
                                  .ToArray();

            var shippingStatus = ((ShippingStatus[])Enum.GetValues(typeof(ShippingStatus)))
                                 .Select(x => new RuleValueSelectListOption {
                Value = ((int)x).ToString(), Text = x.GetLocalizedEnum(_services.Localization)
            })
                                 .ToArray();

            var paymentStatus = ((PaymentStatus[])Enum.GetValues(typeof(PaymentStatus)))
                                .Select(x => new RuleValueSelectListOption {
                Value = ((int)x).ToString(), Text = x.GetLocalizedEnum(_services.Localization)
            })
                                .ToArray();

            var descriptors = new List <FilterDescriptor>
            {
                new FilterDescriptor <Customer, bool>(x => x.Active)
                {
                    Name        = "Active",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.Active"),
                    RuleType    = RuleType.Boolean,
                    Constraints = new IRuleConstraint[0]
                },
                new FilterDescriptor <Customer, bool>(x => x.IsTaxExempt)
                {
                    Name        = "TaxExempt",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.TaxExempt"),
                    RuleType    = RuleType.Boolean,
                    Constraints = new IRuleConstraint[0]
                },
                new FilterDescriptor <Customer, int?>(x => DbFunctions.DiffDays(x.LastActivityDateUtc, DateTime.UtcNow))
                {
                    Name        = "LastActivityDays",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.LastActivityDays"),
                    RuleType    = RuleType.NullableInt,
                    Constraints = new IRuleConstraint[0]
                },
                new FilterDescriptor <Customer, int?>(x => DbFunctions.DiffDays(x.LastLoginDateUtc, DateTime.UtcNow))
                {
                    Name        = "LastLoginDays",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.LastLoginDays"),
                    RuleType    = RuleType.NullableInt,
                    Constraints = new IRuleConstraint[0]
                },
                new FilterDescriptor <Customer, int?>(x => DbFunctions.DiffDays(x.CreatedOnUtc, DateTime.UtcNow))
                {
                    Name        = "CreatedDays",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.CreatedDays"),
                    RuleType    = RuleType.NullableInt,
                    Constraints = new IRuleConstraint[0]
                },
                new FilterDescriptor <Customer, int?>(x => DbFunctions.DiffDays(x.BirthDate, DateTime.UtcNow))
                {
                    Name        = "BirthDateDays",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.BirthDate"),
                    RuleType    = RuleType.NullableInt,
                    Constraints = new IRuleConstraint[0]
                },
                new FilterDescriptor <Customer, int?>(x => x.BillingAddress != null ? x.BillingAddress.CountryId : 0)
                {
                    Name        = "BillingCountry",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.BillingCountry"),
                    RuleType    = RuleType.IntArray,
                    Constraints = new IRuleConstraint[0],
                    SelectList  = new RemoteRuleValueSelectList("Country")
                    {
                        Multiple = true
                    }
                },
                new FilterDescriptor <Customer, int?>(x => x.ShippingAddress != null ? x.ShippingAddress.CountryId : 0)
                {
                    Name        = "ShippingCountry",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.ShippingCountry"),
                    RuleType    = RuleType.IntArray,
                    Constraints = new IRuleConstraint[0],
                    SelectList  = new RemoteRuleValueSelectList("Country")
                    {
                        Multiple = true
                    }
                },
                new FilterDescriptor <Customer, string>(x => x.Salutation)
                {
                    Name        = "Salutation",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.Salutation"),
                    RuleType    = RuleType.String,
                    Constraints = new IRuleConstraint[0]
                },
                new FilterDescriptor <Customer, string>(x => x.Title)
                {
                    Name        = "Title",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.Title"),
                    RuleType    = RuleType.String,
                    Constraints = new IRuleConstraint[0]
                },
                new FilterDescriptor <Customer, string>(x => x.Company)
                {
                    Name        = "Company",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.Company"),
                    RuleType    = RuleType.String,
                    Constraints = new IRuleConstraint[0]
                },
                new FilterDescriptor <Customer, string>(x => x.Gender)
                {
                    Name        = "Gender",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.Gender"),
                    RuleType    = RuleType.String,
                    Constraints = new IRuleConstraint[0]
                },
                new FilterDescriptor <Customer, string>(x => x.CustomerNumber)
                {
                    Name        = "CustomerNumber",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.CustomerNumber"),
                    RuleType    = RuleType.String,
                    Constraints = new IRuleConstraint[0]
                },
                new FilterDescriptor <Customer, string>(x => x.TimeZoneId)
                {
                    Name        = "TimeZone",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.TimeZone"),
                    RuleType    = RuleType.String,
                    Constraints = new IRuleConstraint[0]
                },
                new FilterDescriptor <Customer, int>(x => x.VatNumberStatusId)
                {
                    Name        = "VatNumberStatus",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.VatNumberStatus"),
                    RuleType    = RuleType.Int,
                    Constraints = new IRuleConstraint[0],
                    SelectList  = new LocalRuleValueSelectList(vatNumberStatus)
                },
                new FilterDescriptor <Customer, int>(x => x.TaxDisplayTypeId)
                {
                    Name        = "TaxDisplayType",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.TaxDisplayType"),
                    RuleType    = RuleType.Int,
                    Constraints = new IRuleConstraint[0],
                    SelectList  = new LocalRuleValueSelectList(taxDisplayTypes)
                },
                new FilterDescriptor <Customer, int?>(x => DbFunctions.DiffDays(x.LastForumVisit, DateTime.UtcNow))
                {
                    Name        = "LastForumVisitDays",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.LastForumVisit"),
                    RuleType    = RuleType.NullableInt,
                    Constraints = new IRuleConstraint[0]
                },
                new FilterDescriptor <Customer, string>(x => x.LastUserAgent)
                {
                    Name        = "LastUserAgent",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.LastUserAgent"),
                    RuleType    = RuleType.String,
                    Constraints = new IRuleConstraint[0]
                },

                new AnyFilterDescriptor <Customer, CustomerRoleMapping, int>(x => x.CustomerRoleMappings, rm => rm.CustomerRoleId)
                {
                    Name        = "IsInCustomerRole",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.IsInCustomerRole"),
                    RuleType    = RuleType.IntArray,
                    Constraints = new IRuleConstraint[0],
                    SelectList  = new RemoteRuleValueSelectList("CustomerRole")
                    {
                        Multiple = true
                    }
                },
                new FilterDescriptor <Customer, int>(x => x.ReturnRequests.Count())
                {
                    Name        = "ReturnRequestCount",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.ReturnRequestCount"),
                    RuleType    = RuleType.Int,
                    Constraints = new IRuleConstraint[0]
                },

                new FilterDescriptor <Customer, int>(x => x.Orders.Count(o => !o.Deleted && o.OrderStatusId == 30))
                {
                    Name        = "CompletedOrderCount",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.CompletedOrderCount"),
                    RuleType    = RuleType.Int,
                    Constraints = new IRuleConstraint[0]
                },
                new FilterDescriptor <Customer, int>(x => x.Orders.Count(o => !o.Deleted && o.OrderStatusId == 40))
                {
                    Name        = "CancelledOrderCount",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.CancelledOrderCount"),
                    RuleType    = RuleType.Int,
                    Constraints = new IRuleConstraint[0]
                },
                new FilterDescriptor <Customer, int>(x => x.Orders.Count(o => !o.Deleted && (o.OrderStatusId == 10 || o.OrderStatusId == 20)))
                {
                    Name        = "NewOrderCount",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.NewOrderCount"),
                    RuleType    = RuleType.Int,
                    Constraints = new IRuleConstraint[0]
                },
                new AnyFilterDescriptor <Customer, Order, int>(x => x.Orders.Where(o => !o.Deleted), o => o.StoreId)
                {
                    Name        = "OrderInStore",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.OrderInStore"),
                    RuleType    = RuleType.IntArray,
                    Constraints = new IRuleConstraint[0],
                    SelectList  = new LocalRuleValueSelectList(stores)
                    {
                        Multiple = true
                    }
                },
                new FilterDescriptor <Customer, int?>(x => DbFunctions.DiffDays(x.Orders.Where(o => !o.Deleted).Max(o => o.CreatedOnUtc), DateTime.UtcNow))
                {
                    Name        = "LastOrderDateDays",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.LastOrderDateDays"),
                    RuleType    = RuleType.NullableInt,
                    Constraints = new IRuleConstraint[0]
                },
                new AnyFilterDescriptor <Customer, Order, decimal>(x => x.Orders.Where(o => !o.Deleted), o => o.OrderTotal)
                {
                    Name        = "OrderTotal",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.OrderTotal"),
                    RuleType    = RuleType.Money,
                    Constraints = new IRuleConstraint[0]
                },
                new AnyFilterDescriptor <Customer, Order, decimal>(x => x.Orders.Where(o => !o.Deleted), o => o.OrderSubtotalInclTax)
                {
                    Name        = "OrderSubtotalInclTax",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.OrderSubtotalInclTax"),
                    RuleType    = RuleType.Money,
                    Constraints = new IRuleConstraint[0]
                },
                new AnyFilterDescriptor <Customer, Order, decimal>(x => x.Orders.Where(o => !o.Deleted), o => o.OrderSubtotalExclTax)
                {
                    Name        = "OrderSubtotalExclTax",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.OrderSubtotalExclTax"),
                    RuleType    = RuleType.Money,
                    Constraints = new IRuleConstraint[0]
                },
                new AnyFilterDescriptor <Customer, OrderItem, int>(x => x.Orders.Where(o => !o.Deleted).SelectMany(o => o.OrderItems), oi => oi.ProductId)
                {
                    Name        = "HasPurchasedProduct",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.HasPurchasedProduct"),
                    RuleType    = RuleType.IntArray,
                    Constraints = new IRuleConstraint[0],
                    SelectList  = new RemoteRuleValueSelectList("Product")
                    {
                        Multiple = true
                    }
                },
                new AllFilterDescriptor <Customer, OrderItem, int>(x => x.Orders.Where(o => !o.Deleted).SelectMany(o => o.OrderItems), oi => oi.ProductId)
                {
                    Name        = "HasPurchasedAllProducts",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.HasPurchasedAllProducts"),
                    RuleType    = RuleType.IntArray,
                    Constraints = new IRuleConstraint[0],
                    SelectList  = new RemoteRuleValueSelectList("Product")
                    {
                        Multiple = true
                    }
                },
                new AnyFilterDescriptor <Customer, Order, bool>(x => x.Orders.Where(o => !o.Deleted), o => o.AcceptThirdPartyEmailHandOver)
                {
                    Name        = "AcceptThirdPartyEmailHandOver",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.AcceptThirdPartyEmailHandOver"),
                    RuleType    = RuleType.Boolean,
                    Constraints = new IRuleConstraint[0]
                },
                new AnyFilterDescriptor <Customer, Order, string>(x => x.Orders.Where(o => !o.Deleted), o => o.CustomerCurrencyCode)
                {
                    Name        = "CurrencyCode",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.Currency"),
                    RuleType    = RuleType.String,
                    Constraints = new IRuleConstraint[0],
                    SelectList  = new RemoteRuleValueSelectList("Currency")
                },
                new AnyFilterDescriptor <Customer, Order, int>(x => x.Orders.Where(o => !o.Deleted), o => o.CustomerLanguageId)
                {
                    Name        = "OrderLanguage",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.Language"),
                    RuleType    = RuleType.Int,
                    Constraints = new IRuleConstraint[0],
                    SelectList  = new RemoteRuleValueSelectList("Language")
                },
                new AnyFilterDescriptor <Customer, Order, string>(x => x.Orders.Where(o => !o.Deleted), o => o.PaymentMethodSystemName)
                {
                    Name        = "PaymentMethod",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.PaidBy"),
                    RuleType    = RuleType.String,
                    Constraints = new IRuleConstraint[0],
                    SelectList  = new RemoteRuleValueSelectList("PaymentMethod")
                },
                new AnyFilterDescriptor <Customer, Order, int>(x => x.Orders.Where(o => !o.Deleted), o => o.PaymentStatusId)
                {
                    Name        = "PaymentStatus",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.PaymentStatus"),
                    RuleType    = RuleType.Int,
                    Constraints = new IRuleConstraint[0],
                    SelectList  = new LocalRuleValueSelectList(paymentStatus)
                },
                new AnyFilterDescriptor <Customer, Order, string>(x => x.Orders.Where(o => !o.Deleted), o => o.ShippingMethod)
                {
                    Name        = "ShippingMethod",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.ShippingMethod"),
                    RuleType    = RuleType.String,
                    Constraints = new IRuleConstraint[0],
                    SelectList  = new RemoteRuleValueSelectList("ShippingMethod")
                },
                new AnyFilterDescriptor <Customer, Order, string>(x => x.Orders.Where(o => !o.Deleted), o => o.ShippingRateComputationMethodSystemName)
                {
                    Name        = "ShippingRateComputationMethod",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.ShippingRateComputationMethod"),
                    RuleType    = RuleType.String,
                    Constraints = new IRuleConstraint[0],
                    SelectList  = new RemoteRuleValueSelectList("ShippingRateComputationMethod")
                },
                new AnyFilterDescriptor <Customer, Order, int>(x => x.Orders.Where(o => !o.Deleted), o => o.ShippingStatusId)
                {
                    Name        = "ShippingStatus",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.ShippingStatus"),
                    RuleType    = RuleType.Int,
                    Constraints = new IRuleConstraint[0],
                    SelectList  = new LocalRuleValueSelectList(shippingStatus)
                },
                new TargetGroupFilterDescriptor(_ruleFactory, this)
                {
                    Name        = "RuleSet",
                    DisplayName = _services.Localization.GetResource("Admin.Rules.FilterDescriptor.RuleSet"),
                    RuleType    = RuleType.Int,
                    Operators   = new[] { RuleOperator.IsEqualTo, RuleOperator.IsNotEqualTo },
                    Constraints = new IRuleConstraint[0],
                    SelectList  = new RemoteRuleValueSelectList("TargetGroup")
                }
            };

            descriptors
            .Where(x => x.RuleType == RuleType.Money)
            .Each(x => x.Metadata["postfix"] = _services.StoreContext.CurrentStore.PrimaryStoreCurrency.CurrencyCode);

            return(descriptors);
        }
Exemple #27
0
        /// <summary>
        /// Datas the table.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public JsonResult DataTable(DataTablesRequest request)
        {
            IMediaRepository repository = new DbMediaRepository(new EntityFrameworkSexContext());

            var videos = repository.GetVideos();

//            return Json(
//                request.Response(
//                    videos.AsQueryable(),
//                    new Field<Video, string>(video => video.Hash, (video, search) => video.Hash.Contains(search)),
//                    new Field<Video, string>(video => video.FileName, (video, search) => video.FileName.Contains(search), (videoFileName) => string.Format(@"
//<video id=""videoBox"" class=""video-js vjs-default-skin"" controls preload=""none"" width=""640"" height=""264"" data-setup=""{{}}"">
//   <source src=""{0}"" type='video/mp4' />
//</video>", Url.Action("OceansClip", new { filename = videoFileName }))),
//                    new Field<Video, TimeSpan>(video => video.Duration, (IQueryable<Video> items, string search) =>
//                    {
//                        int maxDuration = int.Parse(search);
//                        return items.Where(video => DbFunctions.DiffMinutes(TimeSpan.Zero, video.Duration) <= maxDuration);
//                    }),
//                    new Field<Video, string>(video => video.NormalizedTags, (video, search) => video.NormalizedTags.Contains(search))),
//                JsonRequestBehavior.AllowGet);
            return(Json(
                       request.Response(
                           videos.AsQueryable(),
                           new Field <Video, string>(
                               video => video.FileName,
                               (video, search) => video.FileName.Contains(search)),
                           new Field <Video, TimeSpan>(
                               video => video.Duration,
                               (IQueryable <Video> items, string search) =>
            {
                try
                {
                    var split = search.Split('-');
                    if (split.Count() == 1)
                    {
                        int maxDuration = int.Parse(search);
                        return items.Where(video => DbFunctions.DiffMinutes(TimeSpan.Zero, video.Duration) <= maxDuration);
                    }

                    if (split.Count() == 2)
                    {
                        int minDuration = int.Parse(split[0]);
                        int maxDuration = int.Parse(split[1]) + 1;
                        return items.Where(video => DbFunctions.DiffMinutes(TimeSpan.Zero, video.Duration) <= maxDuration && DbFunctions.DiffMinutes(TimeSpan.Zero, video.Duration) >= minDuration);
                    }
                }
                catch (Exception)
                {
                }
                return items;
            },
                               duration => duration.ToString(@"hh\:mm\:ss")),
                           new Field <Video, string>(
                               video => video.NormalizedTags,
                               (video, search) => video.NormalizedTags.Contains(search))),
                       JsonRequestBehavior.AllowGet));
        }
Exemple #28
0
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();
            var  personAttribute = GetAttributeValue(action, "PersonAttribute");
            Guid personAttrGuid  = personAttribute.AsGuid();

            if (!personAttrGuid.IsEmpty())
            {
                var personAttributeInst = AttributeCache.Read(personAttrGuid, rockContext);
                if (personAttributeInst != null)
                {
                    string attributePersonValue = action.GetWorklowAttributeValue(personAttrGuid);
                    Guid   personAliasGuid      = attributePersonValue.AsGuid();

                    if (personAliasGuid != null)
                    {
                        var personAlias = (new PersonAliasService(rockContext)).Get(personAliasGuid);
                        if (personAlias != null)
                        {
                            // Get the persons current attendance if it exists
                            try
                            {
                                var currentAttendance = rockContext.Attendances.Where(a => a.PersonAlias.Id == personAlias.Id && DbFunctions.TruncateTime(a.CreatedDateTime.Value) == RockDateTime.Now.Date)
                                                        .FirstOrDefault();

                                if (currentAttendance != null)
                                {
                                    rockContext.Attendances.Remove(currentAttendance);
                                }
                            }
                            catch (ArgumentNullException ane)
                            {
                                errorMessages.Add(string.Format("Could not retrieve currentAttendance for person {0}. Exception: {1}", personAlias.Person.FullName, ane.Message));
                            }
                        }
                    }
                    else
                    {
                        errorMessages.Add(string.Format("PersonAlias cannot be found: {0}", personAliasGuid));
                    }
                }
                else
                {
                    errorMessages.Add(string.Format("Person attribute could not be found for '{0}'!", personAttrGuid.ToString()));
                }
            }
            else
            {
                errorMessages.Add(string.Format("Selected person attribute ('{0}') was not a valid Guid!", personAttribute));
            }
            return(true);
        }
Exemple #29
0
        public string PrintBookingReportList(KendoFilterRequestDto Request)
        {
            using (EAharaDB context = new EAharaDB())
            {
                BasicAuthenticationIdentity identity = (BasicAuthenticationIdentity)User.Identity;

                var user  = context.Users.FirstOrDefault(x => x.Id == identity.Id);
                var query = context.Bookings.Where(x => x.IsActive &&
                                                   ((DbFunctions.TruncateTime(x.OrderDate)) >= (DbFunctions.TruncateTime(Request.FromDate)) &&
                                                    (DbFunctions.TruncateTime(x.OrderDate)) <= (DbFunctions.TruncateTime(Request.ToDate))));

                if (user.Role == "Employee")
                {
                    if (user.Employee != null)
                    {
                        query = query.Where(x => x.LocationId == user.Employee.LocationId);
                    }
                }
                var rep = query;

                if (Request.ShopId > 0)
                {
                    rep = rep.Where(x => x.ShopId == Request.ShopId);
                }

                if (Request.Paid == "Paid")
                {
                    rep = rep.Where(x => x.IsPaid);
                }
                if (Request.Paid == "Not Paid")
                {
                    rep = rep.Where(x => !x.IsPaid);
                }

                long[] items = rep.Select(x => x.Id).ToArray();

                ReportDocument rd = new ReportDocument();

                Guid   id1        = Guid.NewGuid();
                var    pdfName    = "BookingReport" + id1 + ".pdf";
                string strRptPath = System.Web.HttpContext.Current.Server.MapPath("~/") + "Reports\\" + "BookingReport" + ".rpt";
                string strPdfPath = System.Web.HttpContext.Current.Server.MapPath("~/") + "Reports\\" + pdfName;

                rd.Load(strRptPath);
                rd.Refresh();

                string connectionString =
                    ConfigurationManager.ConnectionStrings["EAharaDB"].ConnectionString;

                SqlConnectionStringBuilder SConn = new SqlConnectionStringBuilder(connectionString);

                rd.DataSourceConnections[0].SetConnection(
                    SConn.DataSource, SConn.InitialCatalog, SConn.UserID, SConn.Password);

                foreach (ReportDocument srd in rd.Subreports)
                {
                    srd.DataSourceConnections[0].SetConnection(SConn.DataSource, SConn.InitialCatalog, SConn.UserID, SConn.Password);
                }
                rd.SetParameterValue(0, items);
                System.IO.File.Delete(strPdfPath);
                rd.PrintOptions.PaperSize = PaperSize.PaperA4;
                rd.ExportToDisk(ExportFormatType.PortableDocFormat, strPdfPath);

                return(pdfName);
            }
        }
Exemple #30
0
        public static EficienciaPorDiaDto GetEfficiencyPerDay(DateTime fechaInicio, DateTime fechaTermino)
        {
            #region Declaración
            EficienciaPorDiaDto         eficienciaTotal = new EficienciaPorDiaDto();
            List <DetalleEficienciaDto> lista           = new List <DetalleEficienciaDto>();
            DetalleEficienciaDto        eficiencia      = new DetalleEficienciaDto();
            DetalleEficienciaDto        separador       = new DetalleEficienciaDto();

            ResumenEficienciaDto        resumen      = new ResumenEficienciaDto();
            List <ResumenEficienciaDto> listaResumen = new List <ResumenEficienciaDto>();

            bool     primerUsuario = true;
            bool     primeraFila   = true;
            int      sTotalE       = 0;
            int      sTotalI       = 0;
            int      totalE        = 0;
            int      totalI        = 0;
            TimeSpan horaI         = new TimeSpan();
            TimeSpan horaF         = new TimeSpan();
            TimeSpan totalHora     = new TimeSpan();
            TimeSpan paramEuidHora = new TimeSpan(1, 0, 0);
            string   usuario       = "";
            DateTime dateT         = new DateTime();

            repository  = unitOfWork.Repository <MovimientoPacking>();
            repositoryI = unitOfWork.Repository <InfoFieldBook>();
            repositoryU = unitOfWork.Repository <Usuario>();
            #endregion

            var data = (from mc in repository.Table
                        from us in repositoryU.Table
                        from inf in repositoryI.Table
                        where mc.fechaPacking >= fechaInicio && mc.fechaPacking <= fechaTermino &&
                        mc.usuario == us.nombre_usuario && mc.euid == inf.euid && (mc.indEuid == inf.indEuid || mc.indEuid == "")
                        //orderby DbFunctions.TruncateTime(mc.fechaPacking)
                        //orderby mc.usuario
                        select new DetalleEficienciaDto
            {
                Client = inf.client,
                Crop = inf.crop,
                Euid = mc.euid,
                ExpName = inf.opExpName,
                FechaPacking = mc.fechaPacking,
                Fecha = (DateTime)DbFunctions.TruncateTime(mc.fechaPacking),
                Time = (TimeSpan)DbFunctions.CreateTime(mc.fechaPacking.Hour, mc.fechaPacking.Minute, mc.fechaPacking.Second),
                GmoEvent = inf.gmoEvent,
                IndEuid = mc.indEuid,
                Location = inf.location,
                ProjectLead = inf.projecLead,
                Sag = inf.sag,
                Usuario = mc.usuario,
                NombreCompleto = ""
            }).ToList();

            data = data.OrderBy(o => o.Fecha).ThenBy(o => o.FechaPacking).ThenBy(o => o.Usuario).ToList();

            foreach (var item in data)
            {
                if (dateT != item.Fecha)
                {
                    eficiencia.Fecha        = item.Fecha;
                    eficiencia.FechaPacking = item.FechaPacking;
                    eficiencia.Usuario      = item.Usuario;
                    if (primeraFila)
                    {
                        horaI = item.Time;
                    }

                    if (!primerUsuario)
                    {
                        //Detalle
                        horaF             = lista[lista.Count - 1].Time;
                        separador         = new DetalleEficienciaDto();
                        separador.Usuario = "Sub Total";
                        separador.Euid    = sTotalE.ToString("N0", CultureInfo.CurrentCulture);
                        separador.IndEuid = sTotalI.ToString("N0", CultureInfo.CurrentCulture);
                        separador.Time    = horaF.Subtract(horaI);
                        totalHora         = totalHora.Add(separador.Time);
                        if (separador.Time.TotalMinutes > 0)
                        {
                            var euidHora = 3600 / ((separador.Time.TotalMinutes / sTotalE) * 60);
                            separador.EuidHora = euidHora.ToString("N0", CultureInfo.CurrentCulture);
                        }
                        sTotalE = 0;
                        sTotalI = 0;
                        horaI   = item.Time;

                        lista.Add(separador);

                        //Resumen
                        resumen               = new ResumenEficienciaDto();
                        resumen.Usuario       = item.Usuario;
                        resumen.Fecha         = dateT;
                        resumen.Hora          = separador.Time;
                        resumen.NumeroEuid    = separador.Euid;
                        resumen.NumeroIndEuid = separador.IndEuid;
                        resumen.EuidHora      = separador.EuidHora ?? "0";
                        listaResumen.Add(resumen);
                    }
                    primerUsuario = false;
                    dateT         = item.Fecha;
                }

                if (usuario != item.Usuario)
                {
                    if (!primeraFila)
                    {
                        //Detalle
                        horaF             = lista[lista.Count - 1].Time;
                        separador         = new DetalleEficienciaDto();
                        separador.Usuario = "Sub Total";
                        separador.Euid    = sTotalE.ToString("N0", CultureInfo.CurrentCulture);
                        separador.IndEuid = sTotalI.ToString("N0", CultureInfo.CurrentCulture);
                        separador.Time    = horaF.Subtract(horaI);
                        totalHora         = totalHora.Add(separador.Time);
                        if (separador.Time.TotalMinutes > 0)
                        {
                            var euidHora = 3600 / ((separador.Time.TotalMinutes / sTotalE) * 60);
                            separador.EuidHora = euidHora.ToString("N0", CultureInfo.CurrentCulture);
                        }
                        sTotalE = 0;
                        sTotalI = 0;
                        horaI   = item.Time;

                        lista.Add(separador);

                        //Resumen
                        resumen               = new ResumenEficienciaDto();
                        resumen.Usuario       = usuario;
                        resumen.Fecha         = item.Fecha;
                        resumen.Hora          = separador.Time;
                        resumen.NumeroEuid    = separador.Euid;
                        resumen.NumeroIndEuid = separador.IndEuid;
                        resumen.EuidHora      = separador.EuidHora ?? "0";
                        listaResumen.Add(resumen);
                    }

                    eficiencia.Usuario = item.Usuario;
                    usuario            = item.Usuario;
                }

                eficiencia.Euid        = item.Euid;
                eficiencia.IndEuid     = item.IndEuid;
                eficiencia.Crop        = item.Crop;
                eficiencia.Client      = item.Client;
                eficiencia.ProjectLead = item.ProjectLead;
                eficiencia.Location    = item.Location;
                eficiencia.ExpName     = item.ExpName;
                eficiencia.GmoEvent    = item.GmoEvent;
                eficiencia.Sag         = item.Sag;
                eficiencia.Time        = item.Time;

                if (eficiencia.Euid != "")
                {
                    sTotalE++;
                    totalE++;
                }
                if (eficiencia.IndEuid != "")
                {
                    sTotalI++;
                    totalI++;
                }

                lista.Add(eficiencia);
                eficiencia  = new DetalleEficienciaDto();
                primeraFila = false;
            }

            //Detalle
            separador         = new DetalleEficienciaDto();
            horaF             = lista[lista.Count - 1].Time;
            separador.Usuario = "Sub Total";
            separador.Euid    = sTotalE.ToString("N0", CultureInfo.CurrentCulture);
            separador.IndEuid = sTotalI.ToString("N0", CultureInfo.CurrentCulture);
            separador.Time    = horaF.Subtract(horaI);
            if (separador.Time.TotalMinutes > 0)
            {
                var euidHora = 3600 / ((separador.Time.TotalMinutes / sTotalE) * 60);
                separador.EuidHora = euidHora.ToString("N0", CultureInfo.CurrentCulture);
            }
            totalHora = totalHora.Add(separador.Time);
            sTotalE   = 0;
            sTotalI   = 0;
            lista.Add(separador);

            //Resumen
            resumen               = new ResumenEficienciaDto();
            resumen.Usuario       = usuario;
            resumen.Fecha         = dateT;
            resumen.Hora          = separador.Time;
            resumen.NumeroEuid    = separador.Euid;
            resumen.NumeroIndEuid = separador.IndEuid;
            resumen.EuidHora      = separador.EuidHora ?? "0";
            listaResumen.Add(resumen);

            //Total

            separador         = new DetalleEficienciaDto();
            separador.Usuario = "Total";
            separador.Euid    = totalE.ToString("N0", CultureInfo.CurrentCulture);
            separador.IndEuid = totalI.ToString("N0", CultureInfo.CurrentCulture);
            separador.Time    = totalHora;
            if (separador.Time.TotalMinutes > 0)
            {
                var euidHora = 3600 / ((separador.Time.TotalMinutes / totalE) * 60);
                separador.EuidHora = euidHora.ToString("N0", CultureInfo.CurrentCulture);
            }
            lista.Add(separador);


            //Detalle y Resumen
            eficienciaTotal.Detalle = lista;
            eficienciaTotal.Resumen = listaResumen;

            return(eficienciaTotal);
        }
Exemple #31
0
 protected internal abstract string GetFunction(DbFunctions functionName);
        protected internal override string GetFunction(DbFunctions functionName)
        {
            switch (functionName)
            {

                case DbFunctions.ToLower:
                    return "LOWER";
                case DbFunctions.ToUpper:
                    return "UPPER";
                default:
                    return "";
            }
        }