internal Tuple <DataTable, string> GetAllContactsCustomQuery()
        {
            CustomQuery custom = new CustomQuery(UserConnection, "Select Id, Name, Phone, Email from Contact");

            DataTable dt;

            using (DBExecutor dbExecutor = UserConnection.EnsureDBConnection(QueryKind.General))
            {
                using (IDataReader reader = custom.ExecuteReader(dbExecutor))
                {
                    dt = reader.ReadToDataTable("Contact");
                }
            }
            custom.BuildParametersAsValue = true;
            return(new Tuple <DataTable, string>(dt, custom.GetSqlText()));
        }
示例#2
0
        public static string ExecuteSQL(string script, UserConnection userConnection)
        {
            script = script.Replace("|nl|", Environment.NewLine);
            var query = new CustomQuery(userConnection, script);
            var isChangeStateScript = GetIsChangeStateScript(script);

            if (isChangeStateScript)
            {
                var count = query.Execute();
                return(count.ToString());
            }
            var records   = query.ExecuteReader(userConnection.EnsureDBConnection());
            var dataTable = new DataTable {
                TableName = "bpmcliTable"
            };

            dataTable.Load(records);
            return(JsonConvert.SerializeObject(dataTable, Formatting.Indented));
        }
示例#3
0
        public Stream GenerateSalaryReport(string key)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                System.Diagnostics.Debugger.Break();
            }
            var          UserConnection = (UserConnection)HttpContext.Current.Session["UserConnection"];
            MemoryStream stream         = new MemoryStream();
            var          filters        = (Dictionary <string, string>)UserConnection.ApplicationCache[key];

            UserConnection.ApplicationCache.Remove(key);

            string StartDate     = filters["StartDate"];
            string DueDate       = filters["DueDate"];
            string location      = filters["location"];
            string ServicesScope = filters["services"];


            ////////////////////////Attributes for sql filter///////////////////////////////////////////
            string subId2 = ";";
            int    mi1    = 0;
            int    mi2;
            int    k = 1;
            string ServiceItemName;
            string quot      = "'";
            string sqlfilter = "";
            string teststr   = ServicesScope;

            ////////////////////////Attributes for sql filter end///////////////////////////////////////////
            ////////////////////////SQL FILTER BY SERVICE ITEM///////////////////////////////////////////
            if (teststr != String.Empty)
            {
                sqlfilter = " and ServiceItemId in (select Id from ServiceItem where Name = ";
                //parse:
                while (teststr != String.Empty)
                {
                    mi2             = teststr.IndexOf(subId2);
                    ServiceItemName = teststr.Substring(mi1, mi2);
                    teststr         = teststr.Remove(mi2, 1);
                    teststr         = teststr.Remove(0, ServiceItemName.Length);
                    if (k == 1)
                    {
                        sqlfilter = sqlfilter + quot + ServiceItemName + quot;
                        k++;
                    }
                    else if (k > 1)
                    {
                        sqlfilter = sqlfilter + " or Name = " + quot + ServiceItemName + quot;
                    }
                }
                //if (teststr != String.Empty) {
                //    goto parse;
                //}
                sqlfilter = sqlfilter + ")";
            }
            ////////////////////////SQL FILTER BY SERVICE ITEM END///////////////////////////////////////////

            string StrStartDate = String.Format("{0:yyyy-MM-dd H:mm:ss}", StartDate);
            string StrDueDate   = String.Format("{0:yyyy-MM-dd H:mm:ss}", DueDate);

            var dateFilter = "WHERE a.CreatedOn BETWEEN '" + StrStartDate + "' AND '" + StrDueDate + "'";

            var userConnection = (UserConnection)HttpContext.Current.Session["UserConnection"];
            var select         = string.Empty;
            int CountActivity  = 0;

            int    flag      = 1;
            string errorText = "";

            try
            {
                //------------------------Считать кол-во всех обращений за период----------------------//
                var sqlQuery = string.Format(@"SELECT 
					Count(a.Id) AS  [CountActivity]
					FROM [Case] a WITH(NOLOCK)
					{0} "                    , dateFilter);
                select = sqlQuery;                 //проверка запроса
                flag   = 2;
                var resultQuery = new CustomQuery(userConnection, sqlQuery);
                flag = 3;

                using (var dbExecutor = userConnection.EnsureDBConnection())
                {
                    using (var reader = resultQuery.ExecuteReader(dbExecutor))
                    {
                        while (reader.Read())
                        {
                            flag          = 4;
                            CountActivity = reader["CountActivity"] != DBNull.Value  ? (int)reader["CountActivity"] : 0;
                            flag          = 5;
                        }
                    }
                }

                //------------------------Считать кол-во всех обращений c плохой оценкой за период----------------------//
                var dateFilterb = "WHERE a.CreatedOn BETWEEN '" + StrStartDate + "' AND '" + StrDueDate + "'";
                var sqlQueryb   = string.Format(@"SELECT 
					Count(a.Id) AS  [CountActivity]
					FROM [Case] a WITH(NOLOCK)
					{0} "                    , dateFilterb);
                select = sqlQueryb;                 //проверка запроса
                var resultQueryb   = new CustomQuery(userConnection, sqlQueryb);
                int CountActivityb = 0;

                using (var dbExecutorb = userConnection.EnsureDBConnection())
                {
                    using (var readerb = resultQueryb.ExecuteReader(dbExecutorb))
                    {
                        while (readerb.Read())
                        {
                            CountActivityb = readerb["CountActivity"] != DBNull.Value  ? (int)readerb["CountActivity"] : 0;
                        }
                    }
                }

                var dateFilterb2a = "WHERE a.CreatedOn BETWEEN '" + StrStartDate + "' AND '" + StrDueDate + "'";
                var sqlQueryb2a   = string.Format(@"SELECT 
					Count(a.Id) AS  [CountActivity]
					FROM [Case] a WITH(NOLOCK)
					{0} "                    , dateFilterb2a);
                select = sqlQueryb2a;                 //проверка запроса
                var resultQueryb2a   = new CustomQuery(userConnection, sqlQueryb2a);
                int CountActivityb2a = 0;

                using (var dbExecutorb2a = userConnection.EnsureDBConnection())
                {
                    using (var readerb2a = resultQueryb2a.ExecuteReader(dbExecutorb2a))
                    {
                        while (readerb2a.Read())
                        {
                            CountActivityb2a = readerb2a["CountActivity"] != DBNull.Value  ? (int)readerb2a["CountActivity"] : 0;
                        }
                    }
                }

                using (var wb = new XLWorkbook())
                {
                    flag = 6;
                    //------------------------Header----------------------//
                    //------------------------Первая страница----------------------//
                    var ws   = wb.Worksheets.Add("Статистика");
                    var row1 = ws.Row(3);

                    ws.Range("A1:D1").Merge();
                    ws.Range("A3:D3").Merge();
                    //ws.Range("A5:B5").Merge();
                    //ws.Range("A6:B6").Merge();
                    //ws.Range("A7:B7").Merge();
                    ws.Row(1).Cell(1).Value = "Отчетная статистика c " + StrStartDate.ToString() + " по " + StrDueDate.ToString();
                    row1.Cell(1).Value      = "Качественно и своевременно решенные обращения";

                    var row3 = ws.Row(5);
                    row3.Cell(1).Value = teststr;
                    row3.Cell(4).Value = sqlfilter;
                    var row4 = ws.Row(6);
                    var row5 = ws.Row(7);
                    var row6 = ws.Row(8);
                    row4.Cell(1).Value = "Имеющие плохую оценку: ";
                    row4.Cell(4).Value = CountActivityb.ToString();
                    row5.Cell(1).Value = "Имеющие просроченность по разрешению: ";
                    row5.Cell(4).Value = CountActivityb2a.ToString();
                    row6.Cell(1).Value = "Качественно решенные обращения за период: ";
                    row6.Cell(4).Value = Convert.ToString(CountActivity);


                    //************************************************************************************************
                    //************************************************************************************************
                    //************************************************************************************************
                    //************************************************************************************************
                    //************************************************************************************************


                    //-----------------------Настройка стилей-----------------------//
                    //-----------------------Первая страница-----------------------//
                    ws.Row(1).Cell(1).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center).Alignment.Vertical = XLAlignmentVerticalValues.Center;
                    ws.Row(3).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center).Alignment.Vertical         = XLAlignmentVerticalValues.Center;
                    ws.Column(4).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center).Alignment.Vertical      = XLAlignmentVerticalValues.Center;
                    ws.Columns().AdjustToContents(1, 8);
                    ws.Column(1).Width = 26.00;
                    ws.Column(2).Width = 26.00;
                    ws.Column(3).Width = 26.00;
                    ws.Column(3).Width = 4.00;
                    ws.Row(5).CellsUsed().Style.Font.Bold     = true;
                    ws.Row(6).CellsUsed().Style.Font.Bold     = true;
                    ws.Row(7).CellsUsed().Style.Font.Bold     = true;
                    ws.Row(8).CellsUsed().Style.Font.Bold     = true;
                    ws.Row(1).CellsUsed().Style.Font.Bold     = true;
                    ws.Row(3).CellsUsed().Style.Font.FontSize = 14;
                    ws.Row(3).CellsUsed().Style.Font.Bold     = true;

                    ws.Row(10).Cell(1).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center).Alignment.Vertical = XLAlignmentVerticalValues.Center;
                    ws.Row(12).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center).Alignment.Vertical         = XLAlignmentVerticalValues.Center;
                    ws.Row(14).CellsUsed().Style.Font.Bold     = true;
                    ws.Row(15).CellsUsed().Style.Font.Bold     = true;
                    ws.Row(16).CellsUsed().Style.Font.Bold     = true;
                    ws.Row(12).CellsUsed().Style.Font.Bold     = true;
                    ws.Row(12).CellsUsed().Style.Font.FontSize = 14;

                    ws.Row(19).Cell(1).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center).Alignment.Vertical = XLAlignmentVerticalValues.Center;
                    ws.Row(21).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center).Alignment.Vertical         = XLAlignmentVerticalValues.Center;
                    ws.Row(23).CellsUsed().Style.Font.Bold     = true;
                    ws.Row(24).CellsUsed().Style.Font.Bold     = true;
                    ws.Row(25).CellsUsed().Style.Font.Bold     = true;
                    ws.Row(21).CellsUsed().Style.Font.Bold     = true;
                    ws.Row(21).CellsUsed().Style.Font.FontSize = 14;

                    ws.Cell(3, 1).Style.Font.FontColor  = XLColor.FromTheme(XLThemeColor.Accent1);
                    ws.Cell(12, 1).Style.Font.FontColor = XLColor.FromTheme(XLThemeColor.Accent1);
                    ws.Cell(21, 1).Style.Font.FontColor = XLColor.FromTheme(XLThemeColor.Accent1);

                    //-----------------------Save-----------------------//
                    var memStream = new MemoryStream();
                    wb.SaveAs(memStream);
                    memStream.Position = 0;

                    if (WebOperationContext.Current != null)
                    {
                        WebOperationContext.Current.OutgoingResponse.ContentType   = "application/octet-stream";
                        WebOperationContext.Current.OutgoingResponse.ContentLength = memStream.Length;
                        WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-Disposition",
                                                                                 "attachment; filename=\"" + "CaseReport" + ".xlsx\"");
                    }
                    return(memStream);
                }
            }
            catch (Exception ex)
            {
                using (var workbook = new XLWorkbook())
                {
                    var worksheet = workbook.Worksheets.Add("Exception");
                    var row1      = worksheet.Row(1);
                    row1.Cell("A").Value = " - " + flag + " - " + select;
                    var row2 = worksheet.Row(2);
                    row2.Cell("A").Value = ex.Message;

                    var row5 = worksheet.Row(5);
                    row5.Cell("A").Value = "errorText: " + errorText;

                    var memStream = new MemoryStream();
                    workbook.SaveAs(memStream);
                    memStream.Position = 0;
                    if (WebOperationContext.Current != null)
                    {
                        WebOperationContext.Current.OutgoingResponse.ContentType   = "application/octet-stream";
                        WebOperationContext.Current.OutgoingResponse.ContentLength = memStream.Length;
                        WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-Disposition",
                                                                                 "attachment; filename=\"" + "CaseReport" + ".xlsx\"");
                    }
                    return(memStream);
                }
            }
        }
        public static TimeSpan GetRessult(DateTime startDate, DateTime endDate, Guid calendarId, string calendarTimeZone, string userTimeZone, UserConnection userConnection)
        {
            if (startDate > endDate)
            {
                return(new TimeSpan(0, 0, 0));
            }

            TimeZoneInfo timeZoneInfoKazahstan = TimeZoneInfo.FindSystemTimeZoneById(calendarTimeZone);
            TimeZoneInfo timeZoneInfoLocal     = TimeZoneInfo.FindSystemTimeZoneById(userTimeZone);
            TimeSpan     additionHours         = timeZoneInfoKazahstan.BaseUtcOffset - timeZoneInfoLocal.BaseUtcOffset;

            startDate += additionHours;
            endDate   += additionHours;

            DayOfWeek startTimeDayOfWeek = startDate.DayOfWeek;
            DayOfWeek endTimeDayOfWeek   = endDate.DayOfWeek;

            TimeSpan startTime = new TimeSpan(startDate.Hour, startDate.Minute, startDate.Second);
            TimeSpan endTime   = new TimeSpan(endDate.Hour, endDate.Minute, endDate.Second);

            //startDate = new DateTime(startDate.Year, startDate.Month, startDate.Day + 1);
            //Вот именно в мессте + 1 и ошибка. Сегодня тот самый последний день в календаре для месяца.
            //32 числа в июле нету. Внимательно посмотрите на 76 строку и только так добавляте в будущем дни, месяца и года, часы, минуты и т.д.
            startDate = new DateTime(startDate.Year, startDate.Month, startDate.Day);
            startDate = startDate.AddDays(1);
            endDate   = new DateTime(endDate.Year, endDate.Month, endDate.Day);

            //var userConnection = (UserConnection)HttpContext.Current.Session["UserConnection"];
            //var userConnection = new UserConnection(new AppConnection());

            //место для запроса
            var sqlQuery = string.Format(@"Select  c.Id as CId,
                                            c.Name as CName, 
                                            c.TimeZoneId as CTimeZoneId , 
                                            c.Depth  as CDepth , 
                                            c.AroundClock as CAroundClock , 
                                            c.WithoutDayOff as CWithoutDayOff,  
											dic.DayTypeId  as DICDayTypeId  ,
											dic.DayOfWeekId as DICDayOfWeekId, 
											dic.Date as DICDay,
											dow.Name as DOWNAme,  
											dow.Code as DOWCode,
											dow.Number as DOWNumber,
											dt.Name as DTName, 
											dt.IsWeekend as DTIsWeekend, 
											dt.NonWorking as DTNonWorking , 
											wti.DayOffId as WTIDayOffId , 
											wti.[From] as WTIfROM , 
											wti.[To] AS WTITo
											from [DayInCalendar] dic
											join [Calendar] as c on c.Id = dic.CalendarId
											join [DayOfWeek] as dow on dow.Id =  dic.DayOfWeekId
											join [DayType] as dt on dt.Id = dic.DayTypeId
											join [WorkingTimeInterval] as wti on wti.DayInCalendarId= dic.Id
											where dic.CalendarId = '{0}'  
											Order by   dow.Number asc"                                            , calendarId);

            var sqlQueryDayOff = string.Format(@"Select top 20 do.Date as DODate,
                                            dt.Name as DTName, 
                                            wti.[From] as WTIfROM ,
                                            wti.[To] AS WTITo
                                            from [DayOff] do 
                                            left join [DayType] as dt on dt.Id = do.DayTypeId
                                            left join [WorkingTimeInterval] as wti on wti.DayOffId= do.Id
                                            where do.CalendarId = '{0}'", calendarId);

            List <UsrDayInCalendar> usrDays    = new List <UsrDayInCalendar>();
            List <UsrDayOff>        usrDaysOff = new List <UsrDayOff>();

            var resultQuery = new CustomQuery(userConnection, sqlQuery);

            using (var dbExecutor = userConnection.EnsureDBConnection())
            {
                using (var reader = resultQuery.ExecuteReader(dbExecutor))
                {
                    while (reader.Read())
                    {
                        usrDays.Add(new UsrDayInCalendar()
                        {
                            CId            = reader["CId"] != DBNull.Value ? reader["CId"].ToString() : string.Empty,
                            CName          = reader["CName"] != DBNull.Value ? reader["CName"].ToString() : string.Empty,
                            CTimeZoneId    = reader["CTimeZoneId"] != DBNull.Value ? reader["CTimeZoneId"].ToString() : string.Empty,
                            CDepth         = reader["CDepth"] != DBNull.Value ? reader["CDepth"].ToString() : string.Empty,
                            CAroundClock   = reader["CAroundClock"] != DBNull.Value ? reader["CAroundClock"].ToString() : string.Empty,
                            CWithoutDayOff = reader["CWithoutDayOff"] != DBNull.Value ? reader["CWithoutDayOff"].ToString() : string.Empty,
                            DICDayTypeId   = reader["DICDayTypeId"] != DBNull.Value ? reader["DICDayTypeId"].ToString() : string.Empty,
                            DICDayOfWeekId = reader["DICDayOfWeekId"] != DBNull.Value ? reader["DICDayOfWeekId"].ToString() : string.Empty,
                            DICDay         = reader["DICDay"] != DBNull.Value ? reader["DICDay"].ToString() : string.Empty,
                            DOWNAme        = reader["DOWNAme"] != DBNull.Value ? reader["DOWNAme"].ToString() : string.Empty,
                            DOWCode        = reader["DOWCode"] != DBNull.Value ? reader["DOWCode"].ToString() : string.Empty,
                            DOWNumber      = reader["DOWNumber"] != DBNull.Value ? (int)reader["DOWNumber"] : 0,
                            DTName         = reader["DTName"] != DBNull.Value ? reader["DTName"].ToString() : string.Empty,
                            DTIsWeekend    = reader["DTIsWeekend"] != DBNull.Value ? reader["DTIsWeekend"].ToString() : string.Empty,
                            DTNonWorking   = reader["DTNonWorking"] != DBNull.Value ? reader["DTNonWorking"].ToString() : string.Empty,
                            WTIDayOffId    = reader["WTIDayOffId"] != DBNull.Value ? reader["WTIDayOffId"].ToString() : string.Empty,
                            WTIfROM        = reader["WTIfROM"] != DBNull.Value ? reader["WTIfROM"].ToString() : string.Empty,
                            WTITo          = reader["WTITo"] != DBNull.Value ? reader["WTITo"].ToString() : string.Empty

                                             //Quantity = reader["Quantity"] != DBNull.Value ? (decimal)reader["Quantity"] : 0
                        });
                    }
                }
            }

            var resultQueryDayOff = new CustomQuery(userConnection, sqlQueryDayOff);

            using (var dbExecutor = userConnection.EnsureDBConnection())
            {
                using (var reader = resultQueryDayOff.ExecuteReader(dbExecutor))
                {
                    while (reader.Read())
                    {
                        usrDaysOff.Add(new UsrDayOff()
                        {
                            DODate  = reader["DODate"] != DBNull.Value ? (DateTime)reader["DODate"] : new DateTime(2000, 1, 1),
                            DTName  = reader["DTName"] != DBNull.Value ? reader["DTName"].ToString() : string.Empty,
                            WTIfROM = reader["WTIfROM"] != DBNull.Value ? reader["WTIfROM"].ToString() : string.Empty,
                            WTITo   = reader["WTITo"] != DBNull.Value ? reader["WTITo"].ToString() : string.Empty
                        });
                    }
                }
            }


            //Расчет часов для каждого дня недели
            List <UsrDayOn> usrDaysOn = new List <UsrDayOn>();

            usrDaysOn.Add(new UsrDayOn()
            {
                dayOfWeek = DayOfWeek.Monday, allDayHours = new TimeSpan(0, 0, 0)
            });
            usrDaysOn.Add(new UsrDayOn()
            {
                dayOfWeek = DayOfWeek.Tuesday, allDayHours = new TimeSpan(0, 0, 0)
            });
            usrDaysOn.Add(new UsrDayOn()
            {
                dayOfWeek = DayOfWeek.Wednesday, allDayHours = new TimeSpan(0, 0, 0)
            });
            usrDaysOn.Add(new UsrDayOn()
            {
                dayOfWeek = DayOfWeek.Thursday, allDayHours = new TimeSpan(0, 0, 0)
            });
            usrDaysOn.Add(new UsrDayOn()
            {
                dayOfWeek = DayOfWeek.Friday, allDayHours = new TimeSpan(0, 0, 0)
            });
            usrDaysOn.Add(new UsrDayOn()
            {
                dayOfWeek = DayOfWeek.Saturday, allDayHours = new TimeSpan(0, 0, 0)
            });
            usrDaysOn.Add(new UsrDayOn()
            {
                dayOfWeek = DayOfWeek.Sunday, allDayHours = new TimeSpan(0, 0, 0)
            });

            foreach (var currentDayOfWeek in usrDaysOn)
            {
                foreach (var item in usrDays.Where(t => t.DOWCode == currentDayOfWeek.dayOfWeek.ToString()))
                {
                    currentDayOfWeek.allDayHours += TimeSpan.Parse(item.WTITo) - TimeSpan.Parse(item.WTIfROM);
                }
            }

            TimeSpan TSRessult = new TimeSpan(0, 0, 0, 0);

            //Расчет первой и последней даты

            //Если первая и последняя даты тот же день
            if (endDate == startDate.AddDays(-1))
            {
                //Сокращенный или праздничный день
                if (usrDaysOff.Where(h => h.DODate == endDate).Count() > 0)
                {
                    //Сокращенный день
                    foreach (var item in usrDaysOff.Where(t => t.DODate == endDate && (t.DTName == "Сокращенный" || t.DTName == "Рабочий день")))
                    {
                        TimeSpan from = TimeSpan.Parse(item.WTIfROM);
                        TimeSpan to   = TimeSpan.Parse(item.WTITo);

                        if (endTime > startTime)
                        {
                            if (endTime <= from || to <= startTime)
                            {
                            }
                            else if (startTime <= from && from < endTime && endTime <= to)
                            {
                                TSRessult += endTime - from;
                            }
                            else if (startTime <= from && to <= endTime)
                            {
                                TSRessult += to - from;
                            }
                            else if (from <= startTime && endTime <= to)
                            {
                                TSRessult += endTime - startTime;
                            }
                            else if (from <= startTime && startTime < to && to <= endTime)
                            {
                                TSRessult += to - startTime;
                            }
                            else
                            {
                            }
                        }
                    }
                }
                else // обычный день
                {
                    foreach (var item in usrDays.Where(t => t.DOWCode == startTimeDayOfWeek.ToString()))
                    {
                        TimeSpan from = TimeSpan.Parse(item.WTIfROM);
                        TimeSpan to   = TimeSpan.Parse(item.WTITo);

                        if (endTime > startTime)
                        {
                            if (endTime <= from || to <= startTime)
                            {
                            }
                            else if (startTime <= from && from < endTime && endTime <= to)
                            {
                                TSRessult += endTime - from;
                            }
                            else if (startTime <= from && to <= endTime)
                            {
                                TSRessult += to - from;
                            }
                            else if (from <= startTime && endTime <= to)
                            {
                                TSRessult += endTime - startTime;
                            }
                            else if (from <= startTime && startTime < to && to <= endTime)
                            {
                                TSRessult += to - startTime;
                            }
                            else
                            {
                            }
                        }
                    }
                }
            }
            else //Если последняя дата > первой
            {
                //Расчет часов начальной даты
                //Сокращенный день или праздник
                if (usrDaysOff.Where(h => h.DODate == startDate.AddDays(-1)).Count() > 0)
                {
                    foreach (var item in usrDaysOff.Where(t => t.DODate == startDate.AddDays(-1) && (t.DTName == "Сокращенный" || t.DTName == "Рабочий день")))
                    {
                        TimeSpan from = TimeSpan.Parse(item.WTIfROM);
                        TimeSpan to   = TimeSpan.Parse(item.WTITo);

                        if (startTime <= from)
                        {
                            TSRessult += to - from;
                        }
                        else if (startTime > from && startTime < to)
                        {
                            TSRessult += to - startTime;
                        }
                        else
                        {
                        }
                    }
                }
                else // Обычный день
                {
                    foreach (var item in usrDays.Where(t => t.DOWCode == startTimeDayOfWeek.ToString()))
                    {
                        TimeSpan from = TimeSpan.Parse(item.WTIfROM);
                        TimeSpan to   = TimeSpan.Parse(item.WTITo);

                        if (startTime <= from)
                        {
                            TSRessult += to - from;
                        }
                        else if (startTime > from && startTime < to)
                        {
                            TSRessult += to - startTime;
                        }
                        else
                        {
                        }
                    }
                }

                //Расчет часов конечной даты
                //Сокращенный день или праздник
                if (usrDaysOff.Where(h => h.DODate == endDate).Count() > 0)
                {
                    foreach (var item in usrDaysOff.Where(t => t.DODate == endDate && (t.DTName == "Сокращенный" || t.DTName == "Рабочий день")))
                    {
                        TimeSpan from = TimeSpan.Parse(item.WTIfROM);
                        TimeSpan to   = TimeSpan.Parse(item.WTITo);

                        if (endTime <= from)
                        {
                        }
                        else if (endTime > from && endTime < to)
                        {
                            TSRessult += endTime - from;
                        }
                        else
                        {
                            TSRessult += to - from;
                        }
                    }
                }
                else //обычный день
                {
                    foreach (var item in usrDays.Where(t => t.DOWCode == endTimeDayOfWeek.ToString()))
                    {
                        TimeSpan from = TimeSpan.Parse(item.WTIfROM);
                        TimeSpan to   = TimeSpan.Parse(item.WTITo);

                        if (endTime <= from)
                        {
                        }
                        else if (endTime > from && endTime < to)
                        {
                            TSRessult += endTime - from;
                        }
                        else
                        {
                            TSRessult += to - from;
                        }
                    }
                }
            }



            //Расчет срединного промежутка
            if (startDate < endDate)
            {
                for (DateTime currentDate = startDate; currentDate < endDate; currentDate = currentDate.AddDays(1))
                {
                    if (usrDaysOff.Where(h => h.DODate == currentDate).Count() > 0)
                    {
                        foreach (var item in usrDaysOff.Where(t => t.DODate == currentDate && (t.DTName == "Сокращенный" || t.DTName == "Рабочий день")))
                        {
                            TSRessult += TimeSpan.Parse(item.WTITo) - TimeSpan.Parse(item.WTIfROM);
                        }
                    }
                    else
                    {
                        TSRessult += usrDaysOn.Where(f => f.dayOfWeek == currentDate.DayOfWeek).FirstOrDefault().allDayHours;
                    }
                }
            }
            return(TSRessult);
        }