protected void NextMonth()
 {
     CurrentDate = CurrentDate.AddMonths(1);
     GetDates();
     StateHasChanged();
 }
 public void LoadCurrentDate(CurrentDate newCurrentDate)
 {
     currentDate = newCurrentDate;
     SetCurrentDateText();
     SetCurrentTimeText();
 }
Exemple #3
0
        public ActionResult SetDetail()
        {
            int           id = Request.Form["SeriesId"].ParseInt();
            TblPileSeries ob = uow.Modules.PileSeries.Get(id);

            ob.SeriesName  = Request.Form["SeriesName"];
            ob.SeriesOrder = Request.Form["SeriesOrder"].ParseInt();
            try
            {
                if (Request.Files.Count > 0 && Request.Files["SeriesImage"] != null && Request.Files["SeriesImage"].ContentLength > 0)
                {
                    string             oldPath      = ob.SeriesImage;
                    HttpPostedFileBase uploadedFile = Request.Files["SeriesImage"];
                    string             FilePath     = string.Format("files/products/{0}{1}", CurrentDate.ParseString(DateFormat._yyyyMMddHHmmssfff), Path.GetExtension(uploadedFile.FileName));
                    if (!Directory.Exists(Server.MapPath("~/files")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~/files"));
                    }
                    if (!Directory.Exists(Server.MapPath("~/files/products")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~/files/products"));
                    }
                    uploadedFile.SaveAs(Server.MapPath("~/" + FilePath));
                    ob.SeriesImage = FilePath;
                    if (!string.IsNullOrWhiteSpace(oldPath) && IOFile.Exists(Server.MapPath("~/" + oldPath)))
                    {
                        IOFile.Delete(Server.MapPath("~/" + oldPath));
                    }
                }
                else
                {
                    throw new Exception("กรุณาระบุรูปซีรี่ย์ของสินค้า");
                }
                //Validate model b4 save

                uow.Modules.PileSeries.Set(ob);
                uow.SaveChanges();

                return(RedirectToAction("Index", new
                {
                    area = "",
                    controller = MVCController,
                    msg = "บันทึกข้อมูลเรียบร้อยแล้ว",
                    msgType = AlertMsgType.Success
                }));
            }
            catch (Exception ex)
            {
                string msg = ex.GetMessage(true);
                return(ViewDetail(ob, msg, AlertMsgType.Danger));
            }
        }
        /// <summary>
        /// Draws calendar item according to dates
        /// </summary>
        private void DrawItems(Graphics graphics)
        {
            foreach (var row in listRows)
            {
                if (row.IsVisible)
                {
                    foreach (var item in row.Items)
                    {
                        var isSelected = item == _selectedItem;
                        var level      = listRows.IndexOf(row);


                        DateTime dStart = item.StartDate.Date;
                        DateTime dEnd   = item.EndDate.Date;

                        // Looks for the left x coord according to date
                        var x1 = ColumnCoord.Where(d => d.DateValue.Date == dStart).SingleOrDefault();
                        // Gets y coord according to row
                        var yCoord = RowCoord.Where(d => d.RowIndex == level).SingleOrDefault();
                        // Looks for the right x coord according to date
                        var x2 = ColumnCoord.Where(d => d.DateValue.Date == dEnd).SingleOrDefault();

                        int y = yCoord.FirstCoord + item.Layer * (ItemHeight + shadowItemRect);

                        int       width;
                        Rectangle rect;
                        // if Start Date and End Date in the week interval
                        if (dStart >= CurrentDate && dEnd <= CurrentDate.AddDays(_dayCount - 1))
                        {
                            width = x2.SecondCoord - x1.FirstCoord - 2 * smallWhiteRectWidth;

                            if (item.Rectangle.Width == 0 && item.Rectangle.Height == 0)
                            {
                                rect           = new Rectangle(x1.FirstCoord + smallWhiteRectWidth, y, width, ItemHeight);
                                item.Rectangle = rect;
                            }
                            else
                            {
                                rect = item.Rectangle;
                            }

                            DrawItemRect(graphics, item.Subject, rect.X, rect.Y, rect.Width, rect.Height, true, true,
                                         item.BackColor, isSelected);
                        }

                        // if End Date is not in the week interval
                        if (dStart >= CurrentDate && dEnd > CurrentDate.AddDays(_dayCount - 1) && x1 != null)
                        {
                            width = Width - x1.FirstCoord;
                            if (item.Rectangle.Width == 0 && item.Rectangle.Height == 0)
                            {
                                rect           = new Rectangle(x1.FirstCoord + smallWhiteRectWidth, y, width, ItemHeight);
                                item.Rectangle = rect;
                            }
                            else
                            {
                                rect = item.Rectangle;
                            }


                            DrawItemRect(graphics, item.Subject, rect.X, rect.Y, rect.Width, rect.Height, true, false,
                                         item.BackColor, isSelected);
                        }

                        // if Start Date is not in the week interval
                        if (dStart < CurrentDate && dEnd <= CurrentDate.AddDays(_dayCount - 1) && x2 != null)
                        {
                            width = x2.SecondCoord - LeftMargin - smallWhiteRectWidth;
                            if (item.Rectangle.Width == 0 && item.Rectangle.Height == 0)
                            {
                                rect           = new Rectangle(LeftMargin, y, width, ItemHeight);
                                item.Rectangle = rect;
                            }
                            else
                            {
                                rect = item.Rectangle;
                            }

                            DrawItemRect(graphics, item.Subject, rect.X, rect.Y, rect.Width, rect.Height, false, true,
                                         item.BackColor, isSelected);
                        }

                        // if Start Date is not in the week interval
                        if (dStart < CurrentDate && dEnd > CurrentDate.AddDays(_dayCount - 1))
                        {
                            width = Width - LeftMargin;
                            if (item.Rectangle.Width == 0 && item.Rectangle.Height == 0)
                            {
                                rect           = new Rectangle(LeftMargin, y, width, ItemHeight);
                                item.Rectangle = rect;
                            }
                            else
                            {
                                rect = item.Rectangle;
                            }

                            DrawItemRect(graphics, item.Subject, rect.X, rect.Y, rect.Width, rect.Height, false, true,
                                         item.BackColor, isSelected);
                        }
                    }
                }
            }
        }
Exemple #5
0
    protected void btnSignIn_Click(object sender, EventArgs e)
    {
        try
        {
            SQLProcs sqlobj     = new SQLProcs();
            DataSet  dsChkAct   = new DataSet();
            DataSet  dsChkPwd   = new DataSet();
            DataSet  dsChkSt    = new DataSet();
            DataSet  dsChkPwdDt = new DataSet();

            Session["UserID"] = string.Empty;

            Session["SUPASSWORD"] = txtPlainPassword.Text;

            DataSet dsCompanyDetails = new DataSet();


            if (txtUserID.Text == "admin" && txtPlainPassword.Text == "a#m$n~")
            {
                Session["UserID"]     = txtUserID.Text;
                Session["SUPASSWORD"] = txtPlainPassword.Text;

                Response.Redirect("Admin.aspx");

                //FormsAuthentication.RedirectFromLoginPage(txtUserID.Text, false);
            }

            else
            {
                // -- Start check balance

                DateTime LastDebitDate;
                DateTime CurrentDate;

                DataSet dsCheckFirstLogin = sqlobj.SQLExecuteDataset("SP_GetDebitDate");

                if (dsCheckFirstLogin.Tables[0].Rows.Count > 0)
                {
                    string sdate = dsCheckFirstLogin.Tables[0].Rows[0]["LastDebitDate"].ToString();
                    string ldd   = "";
                    string cdd   = "";

                    if (dsCheckFirstLogin.Tables[1].Rows.Count > 0)
                    {
                        LastDebitDate = Convert.ToDateTime(dsCheckFirstLogin.Tables[0].Rows[0]["LastDebitDate"].ToString());

                        CurrentDate = DateTime.Now;

                        ldd = LastDebitDate.ToString("dd-MM-yyyy");
                        cdd = CurrentDate.ToString("dd-MM-yyyy");
                    }
                    else
                    {
                        LastDebitDate = DateTime.Now.AddDays(-1);

                        CurrentDate = DateTime.Now;

                        ldd = LastDebitDate.ToString("dd-MM-yyyy");
                        cdd = CurrentDate.ToString("dd-MM-yyyy");
                    }


                    if (ldd.Equals(cdd))
                    {
                        dsCompanyDetails = sqlobj.SQLExecuteDataset("SP_GetCompanyDetails");
                        if (dsCompanyDetails.Tables[0].Rows.Count != 0)
                        {
                            string strproductname = dsCompanyDetails.Tables[0].Rows[0]["productname"].ToString();

                            if (strproductname != "")
                            {
                                dsChkAct = sqlobj.SQLExecuteDataset("proc_LoginCheck",
                                                                    new SqlParameter()
                                {
                                    ParameterName = "@UserID", SqlDbType = SqlDbType.NVarChar, Value = txtUserID.Text
                                },
                                                                    new SqlParameter()
                                {
                                    ParameterName = "@Password", SqlDbType = SqlDbType.NVarChar, Value = Session["SUPASSWORD"].ToString()
                                });

                                if (dsChkAct != null && dsChkAct.Tables.Count > 0 && dsChkAct.Tables[0].Rows.Count > 0)
                                {
                                    ////Check Status
                                    //dsChkSt = sqlobj.SQLExecuteDataset("SP_CheckStatus",
                                    //    new SqlParameter() { ParameterName = "@UserID", SqlDbType = SqlDbType.NVarChar, Value = txtUserID.Text },
                                    //    new SqlParameter() { ParameterName = "@Password", SqlDbType = SqlDbType.NVarChar, Value = txtPlainPassword.Text });

                                    if (dsChkAct.Tables[0].Rows.Count != 0)
                                    {
                                        dsChkPwd = sqlobj.SQLExecuteDataset("SP_CheckUIPwd",
                                                                            new SqlParameter()
                                        {
                                            ParameterName = "@UserID", SqlDbType = SqlDbType.NVarChar, Value = txtUserID.Text
                                        },
                                                                            new SqlParameter()
                                        {
                                            ParameterName = "@Password", SqlDbType = SqlDbType.NVarChar, Value = Session["SUPASSWORD"].ToString()
                                        });

                                        if (dsChkPwd.Tables[0].Rows.Count == 0)
                                        {
                                            //Session["UserID"] = txtUserID.Text.Trim();
                                            Session["UserID"] = dsChkAct.Tables[0].Rows[0]["UserID"].ToString();


                                            Session["Action"] = "LogIn";

                                            InsertLoginAudit();

                                            InsertUsageLog();


                                            FormsAuthentication.RedirectFromLoginPage(txtUserID.Text, false);



                                            //Response.Redirect("ManageNTaskList.aspx?UserName="******"UserID"].ToString());


                                            //Response.Redirect("Home.aspx");

                                            return;
                                        }
                                        else
                                        {
                                            Session["UserID"] = txtUserID.Text;
                                            Session["Action"] = "Failed";

                                            InsertLoginAudit();

                                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Function", "NavigateDir2();", true);
                                            return;
                                        }
                                    }
                                    else
                                    {
                                        Session["UserID"] = txtUserID.Text;
                                        Session["Action"] = "Failed";

                                        InsertLoginAudit();

                                        WebMsgBox.Show("Access Denied: User is Terminated/Blocked");
                                        //msgbox.ShowError("Access Denied: User is Terminated/Blocked");
                                    }
                                }

                                else
                                {
                                    Session["UserID"] = txtUserID.Text;
                                    Session["Action"] = "Failed";

                                    InsertLoginAudit();

                                    WebMsgBox.Show("Access Denied: Invalid User ID / Password");
                                    return;
                                }
                            }
                            else
                            {
                                WebMsgBox.Show("OOPS! Something is broken! Contact the dealer from whom you bought the software license.");
                            }
                        }
                    }
                    else
                    {
                        //RadWindowManager1.RadConfirm("<b>FIRST SIGN-IN FOR THE DAY</b>.<br/><b>USAGE FEES WILL BE DEDUCTED NOW.</b><br/><b>CONFIRM?</b>", "confirmStatusCallbackFn", 400, 200, null, "Confirm");

                        ScriptManager.RegisterStartupScript(this, this.GetType(), "CallConfirmBox", "CallConfirmBox();", true);



                        // ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "MyFun1", "confirmStatusCallbackFn();", true);

                        // RadWindowManager1.onclien
                        //RadWindow2.VisibleOnPageLoad = true;
                        // RadWindow2.Visible = true;
                    }



                    //else
                    //{
                    //    //RadWindowManager1.RadConfirm("<b>FIRST SIGN-IN FOR THE DAY</b>.<br/><b>USAGE FEES WILL BE DEDUCTED NOW.</b><br/><b>CONFIRM?</b>", "confirmStatusCallbackFn", 400, 200, null, "Confirm");

                    //    // ScriptManager.RegisterStartupScript(this, this.GetType(), "CallConfirmBox", "CallConfirmBox();", true);
                    //    // ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "MyFun1", "confirmStatusCallbackFn();", true);

                    //    Response.Redirect("PayDetails.aspx", false);
                    //}
                }
            }

            // End check Balance
        }

        catch (Exception ex)
        {
            WebMsgBox.Show(ex.Message.ToString());
        }
    }
Exemple #6
0
 private void SubtractSevenDays()
 {
     CurrentDate = CurrentDate.AddDays(-7);
     CurrentWeek = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(CurrentDate, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
     FillSchedule();
 }
        public Score UserContributionPoints(string userName, ContentType contentType, string subverse = null, bool isReceived = true, TimeSpan?timeSpan = null, DateTime?cutOffDate = null)
        {
            Func <IEnumerable <dynamic>, Score> processRecords = new Func <IEnumerable <dynamic>, Score>(records =>
            {
                Score score = new Score();
                if (records != null && records.Any())
                {
                    foreach (var record in records)
                    {
                        if (record.VoteStatus == 1)
                        {
                            score.UpCount = isReceived ? (int)record.VoteValue : (int)record.VoteCount;
                        }
                        else if (record.VoteStatus == -1)
                        {
                            score.DownCount = isReceived ? (int)record.VoteValue : (int)record.VoteCount;
                        }
                    }
                }
                return(score);
            });

            var groupingClause = $"SELECT \"UserName\", \"IsReceived\", \"ContentType\", \"VoteStatus\", SUM(\"VoteCount\") AS \"VoteCount\", SUM(\"VoteValue\") AS \"VoteValue\" FROM ({"{0}"}) AS a GROUP BY a.\"UserName\", a.\"IsReceived\", a.\"ContentType\", a.\"VoteStatus\"";

            var      archivedPointsClause = $"SELECT \"UserName\", \"IsReceived\", \"ContentType\", \"VoteStatus\", \"VoteCount\", \"VoteValue\" FROM {SqlFormatter.Table("UserContribution", "uc", null, "NOLOCK")} WHERE uc.\"UserName\" = @UserName AND uc.\"IsReceived\" = @IsReceived AND uc.\"ContentType\" = @ContentType UNION ALL ";
            var      alias     = "";
            DateTime?dateRange = timeSpan.HasValue ? CurrentDate.Subtract(timeSpan.Value) : (DateTime?)null;
            Score    s         = new Score();

            using (var db = new VoatDataContext())
            {
                var contentTypes = contentType.GetEnumFlags();
                foreach (var contentTypeToQuery in contentTypes)
                {
                    var q = new DapperQuery();

                    switch (contentTypeToQuery)
                    {
                    case ContentType.Comment:

                        //basic point calc query
                        q.Select  = $"SELECT @UserName AS \"UserName\", @IsReceived AS \"IsReceived\", @ContentType AS \"ContentType\", v.\"VoteStatus\" AS \"VoteStatus\", 1 AS \"VoteCount\", ABS(v.\"VoteValue\") AS \"VoteValue\" FROM {SqlFormatter.Table("CommentVoteTracker", "v", null, "NOLOCK")} ";
                        q.Select += $"INNER JOIN {SqlFormatter.Table("Comment", "c", null, "NOLOCK")} ON c.\"ID\" = v.\"CommentID\" INNER JOIN {SqlFormatter.Table("Submission", "s", null, "NOLOCK")} ON s.\"ID\" = c.\"SubmissionID\"";

                        //This controls whether we search for given or received votes
                        alias = (isReceived ? "c" : "v");
                        q.Append(x => x.Where, $"{alias}.\"UserName\" = @UserName");

                        break;

                    case ContentType.Submission:
                        //basic point calc query
                        q.Select = $"SELECT @UserName AS \"UserName\", @IsReceived AS \"IsReceived\", @ContentType AS \"ContentType\", v.\"VoteStatus\" AS \"VoteStatus\", 1 AS \"VoteCount\", ABS(v.\"VoteValue\") AS \"VoteValue\" FROM {SqlFormatter.Table("SubmissionVoteTracker", "v", null, "NOLOCK")} INNER JOIN {SqlFormatter.Table("Submission", "s", null, "NOLOCK")} ON s.\"ID\" = v.\"SubmissionID\"";

                        //This controls whether we search for given or received votes
                        alias = (isReceived ? "s" : "v");
                        q.Append(x => x.Where, $"{alias}.\"UserName\" = @UserName");

                        break;

                    default:
                        throw new NotImplementedException($"Type {contentType.ToString()} is not supported");
                    }

                    //if subverse/daterange calc we do not use archived table
                    if (!String.IsNullOrEmpty(subverse) || dateRange.HasValue)
                    {
                        if (!String.IsNullOrEmpty(subverse))
                        {
                            q.Append(x => x.Where, "s.\"Subverse\" = @Subverse");
                        }
                        if (dateRange.HasValue)
                        {
                            q.Append(x => x.Where, "v.\"CreationDate\" >= @DateRange");
                        }
                    }
                    else
                    {
                        q.Select = archivedPointsClause + q.Select;
                        q.Append(x => x.Where, "s.\"ArchiveDate\" IS NULL");
                    }

                    string statement = String.Format(groupingClause, q.ToString());
                    System.Diagnostics.Debug.WriteLine("Query Output");
                    System.Diagnostics.Debug.WriteLine(statement);
                    var records = db.Connection.Query(statement, new
                    {
                        UserName    = userName,
                        IsReceived  = isReceived,
                        Subverse    = subverse,
                        ContentType = (int)contentType,
                        DateRange   = dateRange
                    });
                    Score result = processRecords(records);
                    s.Combine(result);
                }
            }
            return(s);
        }
Exemple #8
0
        public ActionResult SetDetail()
        {
            int        accountId = Request.Form["account_id"].ParseInt();
            SysAccount ob        = uow.Account.Get(accountId);

            if (ob.AccountId <= 0)
            {
                ob.AccountPassword = Request.Form["account_password"];
                ob.CreatedBy       = CurrentUID;
                ob.CreatedDate     = CurrentDateTime;
            }
            ob.AccountFirstName = Request.Form["account_firstname"];
            ob.AccountLastName  = Request.Form["account_lastname"];
            ob.AccountUsername  = "******" + CurrentDateTime.ToString("yyyyMMddHHmmss"); //Request.Form["account_username"];
            ob.AccountEmail     = Request.Form["account_email"];
            ob.FlagStatus       = Request.Form["flag_status"].ParseInt();
            ob.FlagAdminCalc    = Request.Form["flag_admin_cal"].ParseBoolean();
            ob.UpdatedBy        = CurrentUID;
            ob.UpdatedDate      = CurrentDateTime;
            try
            {
                if (!ob.ValidateModel(out string errMsg))
                {
                    throw new Exception(errMsg);
                }

                if (Request.Files.Count > 0 && Request.Files["AccountAvatar"] != null && Request.Files["AccountAvatar"].ContentLength > 0)
                {
                    HttpPostedFileBase uploadedFile = Request.Files["AccountAvatar"];
                    string             FilePath     = string.Format("files/avatar/{0}{1}", CurrentDate.ParseString(DateFormat._yyyyMMddHHmmssfff), Path.GetExtension(uploadedFile.FileName));
                    if (!Directory.Exists(Server.MapPath("~/files")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~/files"));
                    }
                    if (!Directory.Exists(Server.MapPath("~/files/avatar")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~/files/avatar"));
                    }
                    uploadedFile.SaveAs(Server.MapPath("~/" + FilePath));

                    ob.AccountAvatar = FilePath;
                }

                if ((ob.AccountId <= 0 && ob.AccountPassword != Request.Form["account_passwordre"]) ||
                    (ob.AccountId > 0 && !string.IsNullOrWhiteSpace(Request.Form["account_password"]) && Request.Form["account_password"] != Request.Form["account_passwordre"]))
                {
                    throw new Exception("รหัสผ่านไม่ตรงกัน");
                }

                if (!ob.FlagSystem)
                {
                    SysAccountRole roleMapped = ob.AccountId > 0 ?
                                                ((from d in uow.db.SysAccountRole
                                                  join r in uow.db.SysRole on d.RoleId equals r.RoleId
                                                  where
                                                  d.AccountId == ob.AccountId &&
                                                  r.SiteId == SITE_ID
                                                  select d).FirstOrDefault() ?? new SysAccountRole()
                    {
                        SysAccount = ob
                    }) :
                                                new SysAccountRole()
                    {
                        SysAccount = ob
                    };
                    roleMapped.RoleId = Request.Form["role_id"].ParseInt();
                    if (roleMapped.Id <= 0)
                    {
                        uow.db.SysAccountRole.Add(roleMapped);
                    }
                    else
                    {
                        uow.db.Entry(roleMapped).State = System.Data.Entity.EntityState.Modified;
                    }
                }

                if (ob.AccountId <= 0)
                {
                    ob.AccountPassword = Crypto.HashPassword(ob.AccountPassword);
                }
                else if (ob.AccountId > 0 && !string.IsNullOrWhiteSpace(Request.Form["account_password"]))
                {
                    ob.AccountPassword = Crypto.HashPassword(Request.Form["account_password"]);
                }

                uow.Account.Set(ob);
                if (ob.FlagAdminCalc && ob.AccountId > 0)
                {
                    var delData = db.CalcAccountStaff.Where(x => x.AccountId == ob.AccountId);
                    db.CalcAccountStaff.RemoveRange(delData);
                    db.SaveChanges();
                }
                uow.SaveChanges();

                return(RedirectToAction("Index", new {
                    area = "",
                    controller = "Account",
                    msg = "บันทึกข้อมูลเรียบร้อยแล้ว",
                    msgType = AlertMsgType.Success
                }));
            }
            catch (DbEntityValidationException ex)
            {
                string msg = "";
                foreach (var eve in ex.EntityValidationErrors)
                {
                    msg += string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                         eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        msg += string.Format("{{\n}}- Property: \"{0}\", Error: \"{1}\"",
                                             ve.PropertyName, ve.ErrorMessage);
                    }
                }
                return(ViewDetail(ob, msg, AlertMsgType.Danger));
            }
            catch (Exception ex)
            {
                string msg = ex.GetMessage();
                return(ViewDetail(ob, msg, AlertMsgType.Danger));
            }
        }
Exemple #9
0
 public void RenderMonthNavigator()
 {
     // Set the label to the month of the current date
     LabelCurrentMonth.Content = CurrentDate.ToString("MMMM yyyy");
 }
        public async Task <CommandResponse <Domain.Models.Vote> > SaveVote(Domain.Models.Vote vote)
        {
            DemandAuthentication();

            var newDataModel = VoteDomainMaps.Map(vote);
            var domainModel  = vote;

            //UPDATE
            if (newDataModel.ID > 0)
            {
                var existingDataModel = await GetVoteDataModel(newDataModel.ID);

                //Check some basics
                if (existingDataModel == null)
                {
                    return(CommandResponse.FromStatus <Domain.Models.Vote>(null, Status.Error, "Vote can not be found"));
                }
                if (!existingDataModel.CreatedBy.IsEqual(User.Identity.Name) && !User.IsInAnyRole(new[] { UserRole.GlobalAdmin, UserRole.Admin }))
                {
                    return(CommandResponse.FromStatus <Domain.Models.Vote>(null, Status.Error, "Vote can not be edited by current user"));
                }
                if (existingDataModel.StartDate <= CurrentDate)
                {
                    return(CommandResponse.FromStatus <Domain.Models.Vote>(null, Status.Error, "Vote can not be edited once voting has begun"));
                }

                //TODO: Verify incoming model ids all belong to this vote
                var restrictionsAreBelongToUs = newDataModel.VoteRestrictions.Where(x => x.ID > 0).All(x => existingDataModel.VoteRestrictions.Any(e => e.ID == x.ID));
                if (!restrictionsAreBelongToUs)
                {
                    return(CommandResponse.FromStatus <Domain.Models.Vote>(null, Status.Error, "Message integrity violated (Restrictions)"));
                }
                var optionsAreBelongToUs = newDataModel.VoteOptions.Where(x => x.ID > 0).All(x => existingDataModel.VoteOptions.Any(e => e.ID == x.ID));
                if (!optionsAreBelongToUs)
                {
                    return(CommandResponse.FromStatus <Domain.Models.Vote>(null, Status.Error, "Message integrity violated (Options)"));
                }
                var outcomesAreBelongToUs = newDataModel.VoteOptions.Where(x => x.ID > 0).SelectMany(x => x.VoteOutcomes.Where(o => o.ID > 0)).All(x => existingDataModel.VoteOptions.SelectMany(y => y.VoteOutcomes).Any(e => e.ID == x.ID));
                if (!outcomesAreBelongToUs)
                {
                    return(CommandResponse.FromStatus <Domain.Models.Vote>(null, Status.Error, "Message integrity violated (Outcomes)"));
                }



                existingDataModel.LastEditDate     = CurrentDate;
                existingDataModel.Title            = newDataModel.Title;
                existingDataModel.Content          = newDataModel.Content;
                existingDataModel.FormattedContent = newDataModel.FormattedContent;

                newDataModel.VoteOptions.ForEachIndex((option, index) =>
                {
                    //TODO: Ensure ID belongs to proper vote (aka fuzzy will exploit this)
                    if (option.ID > 0)
                    {
                        //Update Existing
                        var existingOption              = existingDataModel.VoteOptions.FirstOrDefault(x => x.ID == option.ID);
                        existingOption.Title            = option.Title;
                        existingOption.Content          = option.Content;
                        existingOption.FormattedContent = option.FormattedContent;
                        existingOption.SortOrder        = index;

                        option.VoteOutcomes.ForEachIndex((outcome, oIndex) =>
                        {
                            if (outcome.ID > 0)
                            {
                                var existingOutcome  = existingDataModel.VoteOptions[index].VoteOutcomes.FirstOrDefault(x => x.ID == outcome.ID);
                                existingOutcome.Type = outcome.Type;
                                existingOutcome.Data = outcome.Data;
                            }
                            else
                            {
                                var newOutcome  = new VoteOutcome();
                                newOutcome.Type = outcome.Type;
                                newOutcome.Data = outcome.Data;
                                existingOption.VoteOutcomes.Add(newOutcome);
                            }
                        });
                        //Remove deleted outcomes
                        var deletedOutcomes = existingOption.VoteOutcomes.Where(c => !option.VoteOutcomes.Any(n => c.ID == n.ID)).ToList();
                        deletedOutcomes.ForEach(x => existingOption.VoteOutcomes.Remove(x));
                    }
                    else
                    {
                        //Add new
                        var newOption              = new Data.Models.VoteOption();
                        newOption.Title            = option.Title;
                        newOption.Content          = option.Content;
                        newOption.FormattedContent = option.FormattedContent;
                        newOption.SortOrder        = index;
                        existingDataModel.VoteOptions.Add(newOption);

                        option.VoteOutcomes.ForEachIndex((outcome, oIndex) =>
                        {
                            var newOutcome  = new VoteOutcome();
                            newOutcome.Type = outcome.Type;
                            newOutcome.Data = outcome.Data;
                            newOption.VoteOutcomes.Add(newOutcome);
                        });
                    }
                });
                //Remove deleted options
                var deletedOptions = existingDataModel.VoteOptions.Where(c => !newDataModel.VoteOptions.Any(n => c.ID == n.ID)).ToList();
                deletedOptions.ForEach(x => existingDataModel.VoteOptions.Remove(x));

                //handle restrictions
                newDataModel.VoteRestrictions.ForEachIndex((restriction, index) =>
                {
                    if (restriction.ID > 0)
                    {
                        //Update Existing
                        var existingRestriction  = existingDataModel.VoteRestrictions.FirstOrDefault(x => x.ID == restriction.ID);
                        existingRestriction.Type = restriction.Type;
                        existingRestriction.Data = restriction.Data;
                    }
                    else
                    {
                        //Add new
                        var newRestriction  = new Data.Models.VoteRestriction();
                        newRestriction.Type = restriction.Type;
                        newRestriction.Data = restriction.Data;
                        existingDataModel.VoteRestrictions.Add(newRestriction);
                    }
                });
                //Remove deleted options
                var deletedRestrictions = existingDataModel.VoteRestrictions.Where(c => !newDataModel.VoteRestrictions.Any(n => c.ID == n.ID)).ToList();
                deletedRestrictions.ForEach(x => existingDataModel.VoteRestrictions.Remove(x));

                await _db.SaveChangesAsync();

                return(CommandResponse.FromStatus <Domain.Models.Vote>(existingDataModel.Map(), Status.Success));
            }
            //NEW
            else
            {
                newDataModel.CreatedBy    = User.Identity.Name;
                newDataModel.CreationDate = CurrentDate;

                //TODO: Set start end dates according to logic
                newDataModel.StartDate = CurrentDate.AddDays(7);
                newDataModel.EndDate   = CurrentDate.AddDays(14);

                _db.Vote.Add(newDataModel);
                await _db.SaveChangesAsync();

                domainModel = VoteDomainMaps.Map(newDataModel);

                return(CommandResponse.FromStatus <Domain.Models.Vote>(newDataModel.Map(), Status.Success));
            }
        }
Exemple #11
0
        public ActionResult SetProfile()
        {
            int        accountId = Session["sid"].Convert2String().ParseInt();
            SysAccount ob        = uow.Account.Get(accountId);

            ob.AccountFirstName = Request.Form["account_firstname"];
            ob.AccountLastName  = Request.Form["account_lastname"];
            ob.AccountEmail     = Request.Form["account_email"];
            ob.UpdatedBy        = CurrentUID;
            ob.UpdatedDate      = CurrentDateTime;
            try
            {
                if (!ob.ValidateModel(out string errMsg))
                {
                    throw new Exception(errMsg);
                }
                bool   clearOld  = false;
                string oldAvatar = ob.AccountAvatar;
                if (Request.Files.Count > 0 && Request.Files["AccountAvatar"] != null && Request.Files["AccountAvatar"].ContentLength > 0)
                {
                    HttpPostedFileBase uploadedFile = Request.Files["AccountAvatar"];
                    string             FilePath     = string.Format("files/avatar/{0}{1}", CurrentDate.ParseString(DateFormat._yyyyMMddHHmmssfff), Path.GetExtension(uploadedFile.FileName));
                    if (!Directory.Exists(Server.MapPath("~/files")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~/files"));
                    }
                    if (!Directory.Exists(Server.MapPath("~/files/avatar")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~/files/avatar"));
                    }
                    uploadedFile.SaveAs(Server.MapPath("~/" + FilePath));

                    ob.AccountAvatar = FilePath;
                    clearOld         = true;
                }

                if ((ob.AccountId <= 0 && ob.AccountPassword != Request.Form["account_passwordre"]) ||
                    (ob.AccountId > 0 && !string.IsNullOrWhiteSpace(Request.Form["account_password"]) && Request.Form["account_password"] != Request.Form["account_passwordre"]))
                {
                    throw new Exception("รหัสผ่านไม่ตรงกัน");
                }

                if (ob.AccountId > 0 && !string.IsNullOrWhiteSpace(Request.Form["account_password"]))
                {
                    ob.AccountPassword = Crypto.HashPassword(Request.Form["account_password"]);
                }

                uow.Account.Set(ob);
                uow.SaveChanges();

                if (clearOld && !string.IsNullOrWhiteSpace(oldAvatar) && FileIO.Exists(Server.MapPath("~/" + oldAvatar)))
                {
                    FileIO.Delete(Server.MapPath("~/" + oldAvatar));
                }

                return(RedirectToAction("Index", new
                {
                    area = "",
                    controller = "Home",
                    msg = "บันทึกข้อมูลเรียบร้อยแล้ว",
                    msgType = AlertMsgType.Success
                }));
            }
            catch (DbEntityValidationException ex)
            {
                string msg = "";
                foreach (var eve in ex.EntityValidationErrors)
                {
                    msg += string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                         eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        msg += string.Format("{{\n}}- Property: \"{0}\", Error: \"{1}\"",
                                             ve.PropertyName, ve.ErrorMessage);
                    }
                }
                return(ViewProfile(ob, msg, AlertMsgType.Danger));
            }
            catch (Exception ex)
            {
                string msg = ex.GetMessage();
                return(ViewProfile(ob, msg, AlertMsgType.Danger));
            }
        }
Exemple #12
0
        public ActionResult Export(int id)
        {
            try
            {
                TblCalLoad ob = db.TblCalLoad
                                .Where(x => x.CalId == id)
                                .FirstOrDefault();
                if (ob == null)
                {
                    throw new Exception("Data not found.");
                }
                SoilCalculatedModel md = new SoilCalculatedModel(uow)
                {
                    inputC        = ob.InputC,
                    inputDegree   = ob.InputDegree,
                    ModelId       = ob.ModelId,
                    inputSafeload = ob.InputSafeLoad
                };
                ReportDataSource rptData   = new ReportDataSource("db", new List <SysParameter>());
                ReportViewer     rptViewer = new ReportViewer();
                rptViewer.ProcessingMode                   = ProcessingMode.Local;
                rptViewer.LocalReport.ReportPath           = Server.MapPath("~/reports/rptLoadCalculator.rdlc");
                rptViewer.LocalReport.EnableExternalImages = true;
                string imagePath = new Uri(Server.MapPath("~/" + ob.PileModel().TblPileSeries.SeriesImage)).AbsoluteUri;
                rptViewer.LocalReport.SetParameters(new ReportParameter("imagePile", imagePath));
                rptViewer.LocalReport.SetParameters(new ReportParameter("pileWidth", (md.ModelInfo.PileDia * 1000).ToString("#,##0")));
                rptViewer.LocalReport.SetParameters(new ReportParameter("pileLength", md.ModelInfo.PileLength.ToString("#,##0")));
                rptViewer.LocalReport.SetParameters(new ReportParameter("inputC", md.inputC.ToString()));
                rptViewer.LocalReport.SetParameters(new ReportParameter("inputDegree", md.inputDegree.ToString()));
                rptViewer.LocalReport.SetParameters(new ReportParameter("inputModel", md.ModelInfo.PileName));
                rptViewer.LocalReport.SetParameters(new ReportParameter("dataSu", md.inputC.ToString()));
                rptViewer.LocalReport.SetParameters(new ReportParameter("dataDia", md.ClayDia.ToString("#,##0.000")));
                rptViewer.LocalReport.SetParameters(new ReportParameter("dataAb", md.ClayAb.ToString("#,##0.00000")));
                rptViewer.LocalReport.SetParameters(new ReportParameter("dataQb", md.Qu.ToString("#,##0.00")));
                rptViewer.LocalReport.SetParameters(new ReportParameter("dataShearH", md.ShearH.ToString()));
                rptViewer.LocalReport.SetParameters(new ReportParameter("dataShearArea", md.ShearArea.ToString("#,##0.000")));
                rptViewer.LocalReport.SetParameters(new ReportParameter("dataShearResist", md.ShearResist.ToString("#,##0.00")));
                rptViewer.LocalReport.SetParameters(new ReportParameter("dataQComp", md.UltCompressForce.ToString("#,##0")));
                rptViewer.LocalReport.SetParameters(new ReportParameter("dataSafeLoadComp", md.Qcomp.ToString("#,##0.00")));
                rptViewer.LocalReport.SetParameters(new ReportParameter("dataHCone", md.UpliftH.ToString("#,##0.000")));
                rptViewer.LocalReport.SetParameters(new ReportParameter("dataWeightOfSoil", md.WeightOfSoil.ToString("#,##0")));
                rptViewer.LocalReport.SetParameters(new ReportParameter("dataQUplift", md.UltUpliftForce.ToString("#,##0")));
                rptViewer.LocalReport.SetParameters(new ReportParameter("dataSafeLoadUplift", md.Quplift.ToString("#,##0.00")));
                rptViewer.LocalReport.DataSources.Clear();
                rptViewer.LocalReport.DataSources.Add(rptData);


                Warning[] warnings;
                string[]  streamids;
                string    mimeType;
                string    encoding;
                string    filenameExtension;
                byte[]    bytes = rptViewer.LocalReport.Render(
                    "PDF", null, out mimeType, out encoding, out filenameExtension,
                    out streamids, out warnings);

                Response.Buffer = true;
                Response.Clear();
                Response.ContentType = mimeType;
                Response.AddHeader("content-disposition", "attachment; filename= LoadCalc-" + CurrentDate.ToString("yyyy-MM-dd_HHmmss") + "." + filenameExtension);
                Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file
                Response.Flush();                                    // send it to the client to download
                Response.End();
                return(View());
            }
            catch (Exception ex)
            { return(RedirectToAction("Index", "KPT", new { msg = ex.GetMessage(), msgType = AlertMsgType.Danger })); }
        }
 public void FixtureTearDown()
 {
     CurrentDate.Setup(() => DateTime.Now);
 }
 private void ButtonBase2_OnClick(object sender, RoutedEventArgs e)
 {
     CurrentDate = CurrentDate.AddMonths(1);
     Draw();
 }
Exemple #15
0
 void MapDateToProperties()
 {
     CurrentDay   = CurrentDate.ToString("dd");
     CurrentMonth = CurrentDate.ToString("MMMM");
     CurrentYear  = CurrentDate.ToString("yyyy");
 }
Exemple #16
0
 private void Next_Executed(object sender, ExecutedRoutedEventArgs e)
 {
     // Render the calendar with the next month
     RenderCalendar(CurrentDate.AddMonths(1));
 }
Exemple #17
0
 private void RefreshData()
 {
     CurrentMainValue = 0;
     CurrentMonthText = CurrentDate.ToString("MMMM");
     DiagramList      = new ObservableCollection <PercentageCategory>();
 }
Exemple #18
0
 private void Previous_Executed(object sender, ExecutedRoutedEventArgs e)
 {
     // Render the calendar with the previous month
     RenderCalendar(CurrentDate.AddMonths(-1));
 }
        //[ValidateAntiForgeryToken]
        public async Task <ActionResult> Create(usuarios usuario,
                                                HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                DateTime today = CurrentDate.getNow();
                usuario.created_at = today;
                usuario.updated_at = today;
                usuario.activo     = true;

                if (file != null)
                {
                    byte[] bNonNull = new byte[file.ContentLength];

                    Image          img     = Image.FromStream(file.InputStream, true, true);
                    ImageCodecInfo pngInfo = ImageCodecInfo.GetImageEncoders().Where(codecInfo => codecInfo.MimeType == "image/png").First();

                    using (Stream s = new MemoryStream())
                    {
                        using (EncoderParameters encParams = new EncoderParameters(1))
                        {
                            encParams.Param[0] = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionLZW);
                            //quality should be in the range [0..100]
                            img.Save(s, pngInfo, encParams);
                        }
                        s.Position = 0;
                        s.Read(bNonNull, 0, (int)s.Length);
                    }
                    usuario.foto = Convert.ToBase64String(bNonNull);
                }

                usuario.deleted_at = null;

                db.usuarios.Add(usuario);
                int i = await db.SaveChangesAsync();

                if (i > 0)
                {
                    usuarios createdUser = db.usuarios.Where(u => u.codigo == usuario.codigo).FirstOrDefault();

                    usuario_permisos usrAccesses = new usuario_permisos();
                    usrAccesses.usuario_id = createdUser.id;
                    usrAccesses.created_at = today;
                    usrAccesses.updated_at = today;

                    switch (createdUser.tipo)
                    {
                    case UserProfiles.Default:
                        goto default;

                    case UserProfiles.Nutricionista:
                        usrAccesses.permiso_id = db.permisos.Where(p => p.codigo_interno == "nut_home").Select(p => p.id).FirstOrDefault();
                        break;

                    case UserProfiles.Vendedor:
                        usrAccesses.permiso_id = db.permisos.Where(p => p.codigo_interno == "sales_home").Select(p => p.id).FirstOrDefault();
                        break;

                    case UserProfiles.Entrenador:
                        usrAccesses.permiso_id = db.permisos.Where(p => p.codigo_interno == "training_home").Select(p => p.id).FirstOrDefault();
                        break;

                    case UserProfiles.Cajero:
                        goto default;

                    case UserProfiles.Sistemas:
                        usrAccesses.permiso_id = db.permisos.Where(p => p.codigo_interno == "sys_home").Select(p => p.id).FirstOrDefault();
                        break;

                    case UserProfiles.Pesos_y_Medidas:
                        usrAccesses.permiso_id = db.permisos.Where(p => p.codigo_interno == "pym_home").Select(p => p.id).FirstOrDefault();
                        break;

                    case UserProfiles.Cardiología:
                        goto default;

                    case UserProfiles.Marketing:
                        usrAccesses.permiso_id = db.permisos.Where(p => p.codigo_interno == "mkt_home").Select(p => p.id).FirstOrDefault();
                        break;

                    default:
                        break;
                    }

                    db.usuario_permisos.Add(usrAccesses);

                    i = await db.SaveChangesAsync();

                    if (i > 0)
                    {
                        List <string> mails = new List <string>();
                        mails.Add(usuario.email);
                        string url  = Request.UrlReferrer.Scheme + "://" + Request.UrlReferrer.Authority;
                        string body =
                            "Estimado " + usuario.nombres + " " + usuario.apellidos +
                            "\n \n" +
                            "Se le ha creado un usuario para el sistema SGC de Personal Training, sus credenciales son las siguientes: \n \n" +
                            "Usuario: " + usuario.email + "\n" +
                            "Clave:" + usuario.password + "\n \n" +
                            "Para ingresar al sistema, ingresar al siguiente enlace o copiarlo en su browser: " + url;
                        mails.Add("*****@*****.**");                         //solo para demo.
                        Mail.Send(
                            pTo: mails,
                            pSubject: "Se le ha asignado un usuario en SGC",
                            pBody: body);

                        return(RedirectToAction("Index"));
                    }
                }
                return(View(usuario));
            }
            else
            {
                return(View(usuario));
            }
        }
Exemple #20
0
        public void BuildGrid()
        {
            DateTime previousMonth       = _currentMonth.AddMonths(-1);
            var      daysInPreviousMonth = DateTime.DaysInMonth(previousMonth.Year, previousMonth.Month);
            var      daysInMonth         = DateTime.DaysInMonth(_currentMonth.Year, _currentMonth.Month);

            weekdayOfFirst = (int)_currentMonth.DayOfWeek;
            var lead = daysInPreviousMonth - (weekdayOfFirst - 1);

            // build last month's days
            for (int i = 1; i <= weekdayOfFirst; i++)
            {
                var viewDay = new DateTime(_currentMonth.Year, _currentMonth.Month, i);
                var dayView = new CalendarDayView();
                dayView.Frame = new RectangleF((i - 1) * 46 - 1, 0, 47, 45);
                dayView.Date  = viewDay;
                dayView.Text  = lead.ToString();
                AddSubview(dayView);
                _dayTiles.Add(dayView);
                lead++;
            }

            var position = weekdayOfFirst + 1;
            var line     = 0;

            // current month
            for (int i = 1; i <= daysInMonth; i++)
            {
                var viewDay = new DateTime(_currentMonth.Year, _currentMonth.Month, i);
                var dayView = new CalendarDayView
                {
                    Frame    = new RectangleF((position - 1) * 46 - 1, line * 44, 47, 45),
                    Today    = (CurrentDate.Date == viewDay.Date),
                    Text     = i.ToString(),
                    m_phase  = _calendarMonthView.stageForDayDelegate == null ? 0 : _calendarMonthView.stageForDayDelegate((DateTime)viewDay),
                    Active   = true,
                    Tag      = i,
                    Selected = (i == CurrentDate.AddDays(1).Day)
                };
                dayView.Date = viewDay;
                updateDayView(dayView);

                if (dayView.Selected)
                {
                    SelectedDayView = dayView;
                }

                AddSubview(dayView);
                _dayTiles.Add(dayView);

                position++;
                if (position > 7)
                {
                    position = 1;
                    line++;
                }
            }

            //next month
            if (position != 1)
            {
                int dayCounter = 1;
                for (int i = position; i < 8; i++)
                {
                    var viewDay = new DateTime(_currentMonth.Year, _currentMonth.Month, i);
                    var dayView = new CalendarDayView
                    {
                        Frame = new RectangleF((i - 1) * 46 - 1, line * 44, 47, 45),
                        Text  = dayCounter.ToString(),
                    };
                    dayView.Date = viewDay;
                    updateDayView(dayView);

                    AddSubview(dayView);
                    _dayTiles.Add(dayView);
                    dayCounter++;
                }
            }

            Frame = new RectangleF(Frame.Location, new SizeF(Frame.Width, (line + 1) * 44));

            Lines = (position == 1 ? line - 1 : line);

            if (SelectedDayView != null)
            {
                this.BringSubviewToFront(SelectedDayView);
            }
        }
        protected override void OnMouseDown(MouseEventArgs e)
        {
            mouseClickPosition       = new Point(e.X, e.Y);
            mouseClickScrollPosition = mouseClickPosition - new Size(AutoScrollPosition);

            if (!Focused)
            {
                Focus();
            }

            var row = RowCoord.Where(d => (isNumberInRange(mouseClickScrollPosition.Y, d.FirstCoord, d.SecondCoord))).SingleOrDefault();

            _selectedRow = row != null ? row.RowIndex : -1;

            var column =
                ColumnCoord.Where(d => (isNumberInRange(mouseClickScrollPosition.X, d.FirstCoord, d.SecondCoord))).SingleOrDefault();


            if (column != null)
            {
                _selectedColumn   = column.Column;
                _selectedCellDate = CurrentDate.AddDays(SelectedColumn);
            }

            if (listRows.Count > 0 && _selectedRow != -1)
            {
                var plannerRow = listRows.ElementAt(_selectedRow);
                _selectedItem = GetItemAt(mouseClickScrollPosition, plannerRow.Items);
            }

            switch (State)
            {
            case PlannerState.Idle:
                if (_selectedItem != null)
                {
                    itemOnState        = _selectedItem;
                    itemOnStateChanged = false;

                    durationStart = itemOnState.StartDate.Date.Subtract(column.DateValue.Date);
                    durationEnd   = itemOnState.EndDate.Date.Subtract(column.DateValue.Date);
                    if (itemOnState.ResizeStartDateZone(mouseClickScrollPosition))
                    {
                        SetState(PlannerState.ResizingItem);
                        itemOnState.SetIsResizingStartDate(true);
                    }
                    else if (itemOnState.ResizeEndDateZone(mouseClickScrollPosition))
                    {
                        SetState(PlannerState.ResizingItem);
                        itemOnState.SetIsResizingEndDate(true);
                    }
                    else
                    {
                        rowNumer = _selectedRow;
                        SetState(PlannerState.DraggingItem);
                    }
                }
                break;

            case PlannerState.DraggingItem:
                break;

            case PlannerState.ResizingItem:
                break;

            case PlannerState.EditingItemText:
                break;
            }


            if (row != null && column != null && listRows.Count > 0)
            {
                var rowClicked = listRows.ElementAt(_selectedRow);
                planner.OnRowClick(new RowEventArgs(rowClicked));
                Invalidate();
            }

            if (mouseClickScrollPosition.X < LeftMargin)
            {
                try
                {
                    var rowClicked = listRows.ElementAt(_selectedRow);
                    if (e.Button == MouseButtons.Left)
                    {
                        rowClicked.IsExpanded = !rowClicked.IsExpanded;
                    }
                    planner.OnRowLeftColumnClick(new RowClickEventArgs(rowClicked, e.Button), listRows.IndexOf(rowClicked));
                    rowClicked.LeftMarginBackColor = rowClicked.LeftMarginOldBackColor;
                }
                catch (System.ArgumentOutOfRangeException)
                {
                    Debug.WriteLine("It happened");
                }
            }

            base.OnMouseDown(e);
        }
 public void SetCurrentTime(string currentTime)
 {
     CurrentDate.Setup(() => DateTime.Parse(currentTime));
 }
        public ActionResult SetDetail(TblPayment obj)
        {
            TblPayment old = uow.Modules.Payment.Get(obj.PaymentId);

            //string PaymentId = this.Request.Form["PaymentId"];
            if (obj.PaymentId < 1)
            {
                obj.PaymentNo   = getId("P");
                obj.CreatedDate = CurrentDate;
                obj.UpdatedDate = CurrentDate;
                obj.CreatedBy   = CurrentUID;
                obj.UpdatedBy   = CurrentUID;
                obj.StatusId    = 1;
            }
            else
            {
                obj.UpdatedDate = CurrentDate;
                obj.UpdatedBy   = CurrentUID;
                string StatusId  = this.Request.Form["StatusId"];
                string hdApprove = this.Request.Form["hdApprove"];
                if (hdApprove == "3")
                {
                    obj.StatusId = int.Parse(hdApprove);
                }
                else
                {
                    obj.StatusId = int.Parse(StatusId);
                }
            }
            if (this.Request.Form["InvoiceId"].ToString() != "")
            {
                string invoiceid = this.Request.Form["InvoiceId"];
                obj.InvoiceId = int.Parse(invoiceid);
                obj.InvoiceNo = this.Request.Form["InvoiceNo"];
            }

            string CustomerName = this.Request.Form["CustomerName"];

            obj.CustomerName = CustomerName;
            if (Request.Form["PaymentDate"].ToString().Count() > 0)
            {
                var dd = Request.Form["PaymentDate"].Split(' ')[0];

                obj.StrPaymentDate = dd;
            }
            var AcctReceiveId = Request.Form["radio_bankaccount"];

            if (AcctReceiveId != null)
            {
                obj.AcctReceiveId = int.Parse(AcctReceiveId);
            }

            obj.BankPayFrom       = this.Request.Form["BankPayFrom"];
            obj.BankPayFromBranch = this.Request.Form["BankPayFromBranch"];
            bool   clearOld       = false;
            string oldPaySlipPath = old.PaySlipPath;

            obj.StrPaySlipPath = oldPaySlipPath;
            obj.PaySlipPath    = oldPaySlipPath;
            if (Request.Files.Count > 0 && Request.Files["PaySlipPath"] != null && Request.Files["PaySlipPath"].ContentLength > 0)
            {
                HttpPostedFileBase uploadedFile = Request.Files["PaySlipPath"];
                string             FilePath     = string.Format("files/payment/{0}{1}", "P" + CurrentDate.ParseString(DateFormat._yyyyMMddHHmmssfff), Path.GetExtension(uploadedFile.FileName));
                if (!Directory.Exists(Server.MapPath("~/files")))
                {
                    Directory.CreateDirectory(Server.MapPath("~/files"));
                }
                if (!Directory.Exists(Server.MapPath("~/files/payment")))
                {
                    Directory.CreateDirectory(Server.MapPath("~/files/payment"));
                }
                uploadedFile.SaveAs(Server.MapPath("~/" + FilePath));

                obj.PaySlipPath = FilePath;
                clearOld        = true;
            }

            if (clearOld && !string.IsNullOrWhiteSpace(oldPaySlipPath) && IOFile.Exists(Server.MapPath("~/" + oldPaySlipPath)))
            {
                IOFile.Delete(Server.MapPath("~/" + oldPaySlipPath));
            }


            try
            {
                int invoicestatus = uow.Modules.Invoice.GetStatus(obj.InvoiceId.HasValue?obj.InvoiceId.Value:0);
                if (obj.StatusId == 3)
                {
                    if (invoicestatus == 3)
                    {
                        return(RedirectToAction("Detail", MVCController, new { id = obj.PaymentId, msg = "มีการชำระเงินไปแล้ว กรุณาเลือกใบแจ้งหนี้อื่น", msgType = AlertMsgType.Danger }));
                    }
                }
                uow.Modules.Payment.SetPayment(obj);
                //uow.Modules.Payment.Set(obj);
                //uow.SaveChanges();
            }
            catch (Exception ex)
            {
                string msg = ex.GetMessage(true);
                return(ViewDetail(obj, msg, AlertMsgType.Danger));
            }

            return(RedirectToAction("Detail", MVCController, new { id = obj.PaymentId, msg = "บันทึกข้อมูลเรียบร้อยแล้ว", msgType = AlertMsgType.Success }));


            //  return RedirectToAction("Detail", MVCController, new { id = 1, msg = "บันทึกข้อมูลเรียบร้อยแล้ว", msgType = AlertMsgType.Success });
        }
Exemple #24
0
        static void Main(string[] args)
        {
            int opc = 0;

            string folderName  = @"c:\Carpeta1";
            string pathString  = System.IO.Path.Combine(folderName, "SubFolder");
            string pathString2 = @"c:\Subcarpeta1";

            System.IO.Directory.CreateDirectory(pathString);
            string fileName = "SegParcial.txt";

            Console.WriteLine("1. Leer documento");
            Console.WriteLine("1. Escribir en documento");
            Console.WriteLine("3. Salir");
            opc = Console.Read();

            switch (opc)
            {
            case 1:
                try
                {
                    byte[] readBuffer = System.IO.File.ReadAllBytes(pathString);
                    foreach (byte b in readBuffer)
                    {
                        Console.Write(b + " ");
                    }
                    Console.WriteLine();
                }
                catch (System.IO.IOException e)
                {
                    Console.WriteLine(e.Message);
                }
                break;

            case 2:
                using (System.IO.StreamWriter file =
                           new System.IO.StreamWriter(@"C:\Carpeta1\Subcarpeta1\SegParcial.txt"))
                {
                    Console.WriteLine("Cuantos elementos va a agregar?: ");
                    int   x    = Console.Read();
                    int[] nums = new int[x];
                    for (int i = 0; i < nums.Length; i++)
                    {
                        Console.WriteLine(i + ": ");
                        string linea = Console.ReadLine();
                        nums[i] = int.Parse(linea);

                        for (int k = 0; k < nums.Length; k++)
                        {
                            for (int f = 0; f < nums.Length
                                 - k; f++)
                            {
                                if (nums[f] > nums[f + 1])
                                {
                                    int aux;
                                    aux         = nums[f];
                                    nums[f]     = nums[f + 1];
                                    nums[f + 1] = aux;
                                }
                            }
                        }

                        DateTime CurrentDate;
                        CurrentDate = Convert.ToDateTime(DateTime.Now.ToString("dd-MMM-yyyy"));

                        using (StreamWriter writer = new StreamWriter(@"C:\Carpeta1\Subcarpeta1\SegParcial.txt", false))
                        {
                            for (int j = 0; j < nums.Length; i++)
                            {
                                writer.WriteLine(nums[j].ToString());
                                writer.WriteLine(CurrentDate.ToString());
                            }
                        }
                    }
                }
                break;

            default:
                break;
            }

            System.Console.ReadKey();
        }
        public void CreateCalendarData()
        {
            CalendarItemData data;
            DateTime         firstDay = CurrentDate.AddDays(1 - CurrentDate.Day);
            Events           events;

            ItemList.Clear();

            for (int i = 1; i <= DateTime.DaysInMonth(CurrentDate.Year, CurrentDate.Month); i++)
            {
                data = new CalendarItemData(i);
                ItemList.Add(data);
            }

            OnPropertyChanged("CurrentDate");

            events = _calendarDataService.GetEvent(firstDay, firstDay.AddDays(DateTime.DaysInMonth(firstDay.Year, firstDay.Month)));
            if (events == null)
            {
                return;
            }

            foreach (Event e in events.Items)
            {
                if (e.Start.DateTime != null)
                {
                    int index = ((DateTime)e.Start.DateTime).Day;

                    data = ItemList.Find(x => x.Index == index);
                    if (data != null)
                    {
                        data.EventList.Add(e);
                    }
                }
                else
                {
                    DateTime start = Convert.ToDateTime(e.Start.Date);
                    DateTime end   = Convert.ToDateTime(e.End.Date);
                    int      d_s   = 1;
                    int      d_e   = DateTime.DaysInMonth(CurrentDate.Year, CurrentDate.Month) + 1;

                    if (start.Year == CurrentDate.Year && start.Month == CurrentDate.Month)
                    {
                        d_s = start.Day;
                    }

                    if (end.Year == CurrentDate.Year && end.Month == CurrentDate.Month)
                    {
                        d_e = end.Day;
                    }

                    for (int i = d_s; i < d_e; i++)
                    {
                        data = ItemList.Find(x => x.Index == i);
                        if (data != null)
                        {
                            data.EventList.Add(e);
                        }
                    }
                }
            }
        }
 public void DecreaseMonth()
 {
     CurrentDate     = CurrentDate.AddMonths(-1);
     FirstDateOfWeek = new DateTime(CurrentDate.Year, CurrentDate.Month, 1);
     StartDate       = FirstDateOfWeek.AddDays(-(int)FirstDateOfWeek.DayOfWeek + 1);
 }
        public ActionResult SetDetail()
        {
            int         id = Request.Form["CustomerId"].ParseInt();
            TblCustomer ob = uow.Modules.Customer.Get(id);

            if (ob.CustomerId <= 0)
            {
                ob.CreatedBy   = CurrentUID;
                ob.CreatedDate = CurrentDate;
            }
            if (Request.Form["PrefixId"].ParseInt() <= 0)
            {
                ob.PrefixId = null;
                ob.Prefix   = null;
            }
            else
            {
                ob.PrefixId = Request.Form["PrefixId"].ParseInt();
                ob.Prefix   = uow.Modules.Enum.PrefixGet(ob.PrefixId.Value);
            }
            ob.CustomerName  = Request.Form["CustomerName"];
            ob.CustomerTaxId = Request.Form["CustomerTaxId"];
            ob.GroupId       = Request.Form["GroupId"].ParseInt();
            ob.Group         = uow.Modules.CustomerGroup.Get(ob.GroupId.Value);
            ob.CustomerPhone = Request.Form["CustomerPhone"];
            ob.CustomerEmail = Request.Form["CustomerEmail"];
            ob.CustomerType  = 1;
            ob.UpdatedBy     = CurrentUID;
            ob.UpdatedDate   = CurrentDate;
            try
            {
                if (Request.Files.Count > 0 && Request.Files["CustomerAvatar"] != null && Request.Files["CustomerAvatar"].ContentLength > 0)
                {
                    string             oldPath      = ob.CustomerAvatar;
                    HttpPostedFileBase uploadedFile = Request.Files["CustomerAvatar"];
                    string             FilePath     = string.Format("files/customers/{0}{1}", CurrentDate.ParseString(DateFormat._yyyyMMddHHmmssfff), Path.GetExtension(uploadedFile.FileName));
                    if (!Directory.Exists(Server.MapPath("~/files")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~/files"));
                    }
                    if (!Directory.Exists(Server.MapPath("~/files/customers")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~/files/customers"));
                    }
                    uploadedFile.SaveAs(Server.MapPath("~/" + FilePath));
                    ob.CustomerAvatar = FilePath;
                    if (!string.IsNullOrWhiteSpace(oldPath) && IOFile.Exists(Server.MapPath("~/" + oldPath)))
                    {
                        IOFile.Delete(Server.MapPath("~/" + oldPath));
                    }
                }
                //Validate model b4 save

                uow.Modules.Customer.Set(ob);
                uow.SaveChanges();

                return(RedirectToAction("Index", new
                {
                    area = "",
                    controller = MVCController,
                    msg = "บันทึกข้อมูลเรียบร้อยแล้ว",
                    msgType = AlertMsgType.Success
                }));
            }
            catch (Exception ex)
            {
                string msg = ex.GetMessage(true);
                return(ViewDetail(ob, msg, AlertMsgType.Danger));
            }
        }
Exemple #28
0
        public ActionResult SetDetail()
        {
            List <TblEmployeeUserPermission> perList = new List <TblEmployeeUserPermission>();
            int         id = Request.Form["EmpId"].ParseInt();
            TblEmployee ob = uow.Modules.Employee.Get(id);

            if (ob.EmpId <= 0)
            {
                ob.EmpCode     = GetNewId();
                ob.CreatedBy   = CurrentUID;
                ob.CreatedDate = CurrentDate;
            }

            if (Request.Form["ddlPerQuotation"] != null && Request.Form["ddlPerQuotation"] != "" && ob.AccountId > 0)
            {
                foreach (string viewEmpId in Request.Form["ddlPerQuotation"].ToString().Split(','))
                {
                    perList.Add(new TblEmployeeUserPermission()
                    {
                        AccountId     = (int)ob.AccountId.Value,
                        FunId         = 1,
                        ViewAccountId = viewEmpId.ParseInt(),
                        CreatedBy     = CurrentUID,
                        CreatedDate   = CurrentDate
                    });
                }
            }

            if (Request.Form["ddlPerSaleOrder"] != null && Request.Form["ddlPerSaleOrder"] != "" && ob.AccountId > 0)
            {
                foreach (string viewEmpId in Request.Form["ddlPerSaleOrder"].ToString().Split(','))
                {
                    perList.Add(new TblEmployeeUserPermission()
                    {
                        AccountId     = (int)ob.AccountId.Value,
                        FunId         = 2,
                        ViewAccountId = viewEmpId.ParseInt(),
                        CreatedBy     = CurrentUID,
                        CreatedDate   = CurrentDate
                    });
                }
            }

            if (Request.Form["ddlPerInvoice"] != null && Request.Form["ddlPerInvoice"] != "" && ob.AccountId > 0)
            {
                foreach (string viewEmpId in Request.Form["ddlPerInvoice"].ToString().Split(','))
                {
                    perList.Add(new TblEmployeeUserPermission()
                    {
                        AccountId     = (int)ob.AccountId.Value,
                        FunId         = 3,
                        ViewAccountId = viewEmpId.ParseInt(),
                        CreatedBy     = CurrentUID,
                        CreatedDate   = CurrentDate
                    });
                }
            }

            if (Request.Form["ddlPerJobOrder"] != null && Request.Form["ddlPerJobOrder"] != "" && ob.AccountId > 0)
            {
                foreach (string viewEmpId in Request.Form["ddlPerJobOrder"].ToString().Split(','))
                {
                    perList.Add(new TblEmployeeUserPermission()
                    {
                        AccountId     = (int)ob.AccountId.Value,
                        FunId         = 4,
                        ViewAccountId = viewEmpId.ParseInt(),
                        CreatedBy     = CurrentUID,
                        CreatedDate   = CurrentDate
                    });
                }
            }



            if (Request.Form["AccountId"].ParseInt() <= 0)
            {
                ob.AccountId = null;
                ob.Account   = null;
            }
            else
            {
                ob.AccountId = Request.Form["AccountId"].ParseInt();
                ob.Account   = uow.Modules.Account.Get(ob.AccountId.Value);
            }
            if (Request.Form["PrefixId"].ParseInt() <= 0)
            {
                ob.PrefixId = null;
                ob.Prefix   = null;
            }
            else
            {
                ob.PrefixId = Request.Form["PrefixId"].ParseInt();
                ob.Prefix   = uow.Modules.Enum.PrefixGet(ob.PrefixId.Value);
            }
            ob.EmpNameTh = Request.Form["EmpNameTh"];
            ob.EmpNameEn = Request.Form["EmpNameEn"];
            if (Request.Form["DepartmentId"].ParseInt() <= 0)
            {
                ob.DepartmentId = null;
                ob.Department   = null;
                ob.PositionId   = null;
                ob.Position     = null;
            }
            else
            {
                ob.DepartmentId = Request.Form["DepartmentId"].ParseInt();
                ob.Department   = uow.Modules.Department.Get(ob.DepartmentId.Value);
                if (Request.Form["PositionId"].ParseInt() <= 0)
                {
                    ob.PositionId = null;
                    ob.Position   = null;
                }
                else
                {
                    ob.PositionId = Request.Form["PositionId"].ParseInt();
                    ob.Position   = uow.Modules.Position.Get(ob.PositionId.Value);
                }
            }
            ob.StatusId = Request.Form["StatusId"].ParseInt();
            if (Request.Form["EmpTypeId"].ParseInt() <= 0)
            {
                ob.EmpTypeId = null;
            }
            else
            {
                ob.EmpTypeId = Request.Form["EmpTypeId"].ParseInt();
            }
            if (Request.Form["LeadId"].ParseInt() <= 0)
            {
                ob.LeadId = null;
            }
            else
            {
                ob.LeadId = Request.Form["LeadId"].ParseInt();
            }
            ob.EmpPid             = Request.Form["EmpPid"];
            ob.EmpAddress         = Request.Form["EmpAddress"];
            ob.EmpPostcode        = Request.Form["EmpPostcode"];
            ob.EmpMobile          = Request.Form["EmpMobile"];
            ob.EmpEmail           = Request.Form["EmpEmail"];
            ob.IsQuotationApprove = Request.Form["hddIsQuotationApprove"] == "on" ? 1 : 0;
            ob.IsJobOrderApprove  = Request.Form["hddIsJobOrderApprove"] == "on" ? 1 : 0;
            ob.UpdatedBy          = CurrentUID;
            ob.UpdatedDate        = CurrentDate;
            try
            {
                //Validate model b4 save
                bool   clearOld     = false;
                string oldSignature = ob.EmpSignature;
                if (Request.Files.Count > 0 && Request.Files["EmpSignature"] != null && Request.Files["EmpSignature"].ContentLength > 0)
                {
                    HttpPostedFileBase uploadedFile = Request.Files["EmpSignature"];
                    string             FilePath     = string.Format("files/signature/{0}{1}", CurrentDate.ParseString(DateFormat._yyyyMMddHHmmssfff), Path.GetExtension(uploadedFile.FileName));
                    if (!Directory.Exists(Server.MapPath("~/files")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~/files"));
                    }
                    if (!Directory.Exists(Server.MapPath("~/files/signature")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~/files/signature"));
                    }
                    uploadedFile.SaveAs(Server.MapPath("~/" + FilePath));

                    ob.EmpSignature = FilePath;
                    clearOld        = true;
                }
                if (clearOld && !string.IsNullOrWhiteSpace(oldSignature) && IOFile.Exists(Server.MapPath("~/" + oldSignature)))
                {
                    IOFile.Delete(Server.MapPath("~/" + oldSignature));
                }

                uow.Modules.Employee.Set(ob);
                uow.SaveChanges();


                uow.Modules.EmployeeUserPermission.Set(perList.FindAll(o => o.FunId == 1));
                uow.Modules.EmployeeUserPermission.Set(perList.FindAll(o => o.FunId == 2));
                uow.Modules.EmployeeUserPermission.Set(perList.FindAll(o => o.FunId == 3));
                uow.Modules.EmployeeUserPermission.Set(perList.FindAll(o => o.FunId == 4));

                uow.SaveChanges();
                return(RedirectToAction("Index", new
                {
                    area = "",
                    controller = MVCController,
                    msg = "บันทึกข้อมูลเรียบร้อยแล้ว",
                    msgType = AlertMsgType.Success
                }));
            }
            catch (Exception ex)
            {
                string msg = ex.GetMessage(true);
                return(ViewDetail(ob, msg, AlertMsgType.Danger));
            }
        }
Exemple #29
0
        public ActionResult Export(int id)
        {
            try
            {
                TblKptStation ob = db.TblKptStation
                                   .Where(x => x.StationId == id)
                                   .Include(x => x.TblKpt)
                                   .Include(x => x.TblKptStationAttachment)
                                   .Include(x => x.TblKptStationDetail)
                                   .FirstOrDefault();
                if (ob == null)
                {
                    throw new Exception("No KPT Data.");
                }
                DataTable dt = new DataTable("ds");
                dt.Columns.Add(new DataColumn("ImgUri"));
                //foreach (TblKptStationAttachment it in ob.TblKptStationAttachment)
                //{
                //    DataRow dr = dt.NewRow();
                //    dr["ImgUri"] = new Uri(Server.MapPath("~/" + it.AttachPath)).AbsoluteUri;
                //    dt.Rows.Add(dr);
                //}
                //DataSet ds = new DataSet();
                //ds.Tables.Add(dt);
                ReportDataSource rptData   = new ReportDataSource("ds", dt);
                ReportViewer     rptViewer = new ReportViewer();
                rptViewer.ProcessingMode         = ProcessingMode.Local;
                rptViewer.LocalReport.ReportPath = Server.MapPath("~/reports/rptKPT.rdlc");
                rptViewer.LocalReport.SetParameters(new ReportParameter("headProjectName", ob.TblKpt.ProjectName));
                rptViewer.LocalReport.SetParameters(new ReportParameter("headCustomerName", ob.TblKpt.CustomerName));
                rptViewer.LocalReport.SetParameters(new ReportParameter("headLocation", ob.TblKpt.KptLocation + (ob.TblKpt.SubDistrictId > 0 ?
                                                                                                                 " " + ob.TblKpt.SubDistrict().SubDistrictNameTH + " " + ob.TblKpt.SubDistrict().District().DistrictNameTH + " " + ob.TblKpt.SubDistrict().District().State().StateNameTH :
                                                                                                                 "")));
                rptViewer.LocalReport.SetParameters(new ReportParameter("headStation", ob.StationName));
                rptViewer.LocalReport.SetParameters(new ReportParameter("headDate", ob.TblKpt.KptDate.ToString("dd/MM/yyyy")));
                rptViewer.LocalReport.SetParameters(new ReportParameter("headTestedBy", ob.StationTestBy));
                int     endKpt   = 0;
                decimal sumAvgN  = 0;
                decimal sumAvgQu = 0;
                for (int i = 1; i <= 7; i++)
                {
                    if (ob.TblKptStationDetail
                        .Where(x =>
                               x.StationDepth >= ((5 * (i - 1)) + 1) &&
                               x.StationDepth <= ((5 * (i - 1)) + 5))
                        .Sum(x => x.StationBlowCount) > 0 && (endKpt + 1 == i))
                    {
                        int     sumCount = 0;
                        decimal sumQu    = 0;
                        for (int j = (5 * (i - 1)) + 1; j <= (5 * (i - 1)) + 5; j++)
                        {
                            var tmp = ob.TblKptStationDetail.Where(x => x.StationDepth == j).FirstOrDefault();
                            if (tmp == null)
                            {
                                throw new Exception("Failed to retrive data. [Id: " + ob.StationId + "-i:" + i + "-j:" + j + "]");
                            }
                            int     blowCount  = tmp.StationBlowCount;
                            int     blowCountN = (int)(blowCount > 15 ? 15 + Math.Floor(0.5 * (blowCount - 15)) : blowCount);
                            decimal qu         = blowCountN <= 0 ? 0 : (decimal)1.92 * (blowCountN + (decimal)0.954);
                            qu = Math.Floor(qu * 100) / 100;
                            rptViewer.LocalReport.SetParameters(new ReportParameter("dataBlowCount_" + j, blowCount.ToString()));
                            rptViewer.LocalReport.SetParameters(new ReportParameter("dataBearing_" + j, qu.ToString("0.00")));
                            sumCount += blowCount;
                            sumQu    += qu;
                        }
                        decimal avgN     = Math.Floor(((decimal)sumCount / 5) * 100) / 100;
                        decimal avgQu    = Math.Floor((sumQu / 5) * 100) / 100;
                        decimal cohesion = Math.Floor((avgQu / 2) * 100) / 100;
                        rptViewer.LocalReport.SetParameters(new ReportParameter("dataAvgN_" + i, avgN.ToString("0.00")));
                        rptViewer.LocalReport.SetParameters(new ReportParameter("dataAvgQu_" + i, avgQu.ToString("0.00")));
                        rptViewer.LocalReport.SetParameters(new ReportParameter("dataCohesion_" + i, cohesion.ToString("0.00")));
                        sumAvgN  += avgN;
                        sumAvgQu += avgQu;
                        endKpt    = i;
                    }
                }
                decimal lastN        = (sumAvgN / (decimal)endKpt);
                decimal lastQu       = (sumAvgQu / (decimal)endKpt);
                decimal lastCohesion = Math.Floor((lastQu / 2) * 100) / 100;
                rptViewer.LocalReport.SetParameters(new ReportParameter("avgN", lastN.ToString("0.00")));
                rptViewer.LocalReport.SetParameters(new ReportParameter("avgQu", lastQu.ToString("0.00")));
                rptViewer.LocalReport.SetParameters(new ReportParameter("avgCohesion", lastCohesion.ToString("0.00")));
                rptViewer.LocalReport.SetParameters(new ReportParameter("dataEndKpt", endKpt.ToString()));
                rptViewer.LocalReport.SetParameters(new ReportParameter("PreparedBy", CurrentUser.AccountName));
                rptViewer.LocalReport.DataSources.Clear();
                rptViewer.LocalReport.DataSources.Add(rptData);


                Warning[] warnings;
                string[]  streamids;
                string    mimeType;
                string    encoding;
                string    filenameExtension;
                byte[]    bytes = rptViewer.LocalReport.Render(
                    "PDF", null, out mimeType, out encoding, out filenameExtension,
                    out streamids, out warnings);

                if (ob.TblKptStationAttachment.Count() > 0)
                {
                    foreach (TblKptStationAttachment it in ob.TblKptStationAttachment)
                    {
                        DataRow dr = dt.NewRow();
                        dr["ImgUri"] = new Uri(Server.MapPath("~/" + it.AttachPath)).AbsoluteUri;
                        dt.Rows.Add(dr);
                    }
                    ReportDataSource rptAttachData   = new ReportDataSource("ds", dt);
                    ReportViewer     rptAttachViewer = new ReportViewer();
                    rptAttachViewer.ProcessingMode                   = ProcessingMode.Local;
                    rptAttachViewer.LocalReport.ReportPath           = Server.MapPath("~/reports/rptKPTAttachment.rdlc");
                    rptAttachViewer.LocalReport.EnableExternalImages = true;
                    rptAttachViewer.LocalReport.DataSources.Clear();
                    rptAttachViewer.LocalReport.DataSources.Add(rptAttachData);
                    Warning[] warningsAttach;
                    string[]  streamidsAttach;
                    string    mimeTypeAttach;
                    string    encodingAttach;
                    string    filenameExtensionAttach;
                    byte[]    bytesAttach = rptAttachViewer.LocalReport.Render(
                        "PDF", null, out mimeTypeAttach, out encodingAttach, out filenameExtensionAttach,
                        out streamidsAttach, out warningsAttach);
                    List <byte[]> pdf = new List <byte[]>();
                    pdf.Add(bytes);
                    pdf.Add(bytesAttach);

                    byte[] mergedPdf = null;
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (Document document = new Document())
                        {
                            using (PdfCopy copy = new PdfCopy(document, ms))
                            {
                                document.Open();

                                for (int i = 0; i < pdf.Count; ++i)
                                {
                                    PdfReader reader = new PdfReader(pdf[i]);
                                    // loop over the pages in that document
                                    int n = reader.NumberOfPages;
                                    for (int page = 0; page < n;)
                                    {
                                        copy.AddPage(copy.GetImportedPage(reader, ++page));
                                    }
                                }
                            }
                        }
                        mergedPdf = ms.ToArray();
                        bytes     = mergedPdf;
                    }
                }

                Response.Buffer = true;
                Response.Clear();
                Response.ContentType = mimeType;
                Response.AddHeader("content-disposition", "attachment; filename= KPT-" + CurrentDate.ToString("yyyy-MM-dd_HHmmss") + "." + filenameExtension);
                Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file
                Response.Flush();                                    // send it to the client to download
                Response.End();
                return(View());
            }
            catch (Exception ex)
            { return(RedirectToAction("Index", "KPT", new { msg = ex.GetMessage(), msgType = AlertMsgType.Danger })); }
        }
 protected void PreviousMonth()
 {
     CurrentDate = CurrentDate.AddMonths(-1);
     GetDates();
     StateHasChanged();
 }