Beispiel #1
0
        public ActionResult Create([Bind(Include = "CapitalId,UserId,MethodId,FullAmount,Amount,CurrencyId,Date,Type,DateBegin,DateEnd")] tbCapitals tbCapitals)
        {
            if (ModelState.IsValid)
            {
                db.tbCapitals.Add(tbCapitals);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.UserId = new SelectList(db.tbUsers, "UserId", "FirstName", tbCapitals.UserId);
            return(View(tbCapitals));
        }
Beispiel #2
0
        public ActionResult Create([Bind(Include = "MethodId,UserId,Name,Type,IsClosed")] tbMethod tbMethod)
        {
            if (ModelState.IsValid)
            {
                db.tbMethod.Add(tbMethod);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.UserId = new SelectList(db.tbUsers, "UserId", "FirstName", tbMethod.UserId);
            return(View(tbMethod));
        }
Beispiel #3
0
        public ActionResult Create([Bind(Include = "ServiceId,UserId,MethodId,Amount,Date,IsClosed,CurrencyId")] tbServices tbServices)
        {
            if (ModelState.IsValid)
            {
                db.tbServices.Add(tbServices);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.UserId = new SelectList(db.tbUsers, "UserId", "FirstName", tbServices.UserId);
            return(View(tbServices));
        }
Beispiel #4
0
        public IHttpActionResult PutCardStatus(int id, [FromBody] CardDetail cardDetail)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != cardDetail.CustomerID)
            {
                return(BadRequest());
            }

            db.Entry(cardDetail).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CardDetailExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Beispiel #5
0
        public async Task <string> sendOTP(string email, int OTP)
        {
            var user = (from con in db.ConsumerTables
                        where con.Email == email
                        select con.UserName).FirstOrDefault();

            if (user != null)
            {
                db.OTP_Validation.Add(new OTP_Validation {
                    UserName = user, OTP_Sent = OTP
                });
                db.SaveChanges();
                SmtpClient  smtp        = new SmtpClient();
                MailMessage mailMessage = new MailMessage();
                mailMessage.From = new MailAddress("*****@*****.**");
                mailMessage.To.Add(email);
                mailMessage.Subject = "Forgot Password";
                mailMessage.Body    = "Dear User,Your OTP is " + OTP;
                await Task.Run(() => smtp.SendAsync(mailMessage, null));

                return("OTP sent to the email");
            }
            else
            {
                return("Please Enter the valid Email");
            }
        }
        public void AddOrUpdateUser(UserProfile user)
        {
            try
            {
                using (var context = new FinanceEntities())
                {
                    if (user.UserId == 0)
                    {
                        context.UserProfile.Add(user);

                    }
                    else
                    {
                        var dbuser = context.UserProfile.Include(u => u.webpages_Roles).Single(u => u.UserId == user.UserId);
                        context.Entry(dbuser).CurrentValues.SetValues(user);
                        dbuser.webpages_Roles = new List<webpages_Roles>();
                        foreach (var role in user.webpages_Roles)
                        {
                            dbuser.webpages_Roles.Add(context.webpages_Roles.Single(r => r.RoleId == role.RoleId));
                        }
                    }

                    context.SaveChanges();
                }
            }
            catch (DbEntityValidationException e)
            {
                var message = e.Message;
                throw;
            }
            
        }
Beispiel #7
0
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="id">用户id</param>
        /// <param name="newPwd">新密码</param>
        /// <returns>影响行数</returns>
        public int updatePwd(int id, string newPwd)
        {
            Account account = null;
            int     result  = 0;

            try {
                account     = this.getAccount(id);
                account.pwd = newPwd;
                result      = fin.SaveChanges();
            }
            catch (Exception ex)
            {
                FinanceToError.getFinanceToError().toError();
            }
            return(result);
        }
        public HttpResponseMessage RegisterConsumer([FromBody] Consumer consumer)
        {
            try
            {
                Consumer existingConsumer = db.Consumers.Find(consumer.UserName);
                if (existingConsumer != null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Username Already Exists"));
                }

                Bank newConsumerBank = db.Banks.Find(consumer.IFSC);
                if (newConsumerBank == null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid IFSC Code"));
                }

                Consumer newConsumer = new Consumer
                {
                    UserName        = consumer.UserName,
                    Name            = consumer.Name,
                    Email           = consumer.Email,
                    PhoneNumber     = consumer.PhoneNumber,
                    Password        = consumer.Password,
                    AccountNo       = consumer.AccountNo,
                    IFSC            = consumer.IFSC,
                    Address         = consumer.Address,
                    CardTypeNo      = consumer.CardTypeNo,
                    ApplicationDate = DateTime.Now,
                    DateOfBirth     = consumer.DateOfBirth,
                    IsPending       = true,
                    IsOpen          = false
                };

                Card companyCard = db.Cards.Find(consumer.CardTypeNo);
                if (companyCard == null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid Card Scheme"));
                }

                CompanyCard newConsumerCard = new CompanyCard()
                {
                    CardNumber = $"{consumer.UserName}{consumer.IFSC}",
                    CardTypeNo = consumer.CardTypeNo,
                    UserName   = consumer.UserName,
                    Validity   = DateTime.Now.AddMonths(24),
                    Balance    = companyCard.CardLimit,
                    IsOpen     = false
                };

                db.Entry(newConsumer).State     = System.Data.Entity.EntityState.Added;
                db.Entry(newConsumerCard).State = System.Data.Entity.EntityState.Added;
                db.SaveChanges();

                return(Request.CreateResponse(HttpStatusCode.Created, "User Registered Successfully And Awaiting Verification"));
            } catch
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Consumer Could Not Be Registered"));
            }
        }
 public void CreateComment(Comment comment)
 {
     using (var context = new FinanceEntities())
     {
         context.Comment.Add(comment);
         context.SaveChanges();
     }
 }
 public void CreateRequest(Request request)
 {
     using (var context = new FinanceEntities())
     {
         context.Request.Add(request);
         context.SaveChanges();
     }
 }
 public void CreateDeposit(Deposit deposit)
 {
     using (var context = new FinanceEntities())
     {
         context.Deposit.Add(deposit);
         context.SaveChanges();
     }
 }
 public void CreatePayment(CreditPayment creditPayment)
 {
     using (var context = new FinanceEntities())
     {
         context.CreditPayment.Add(creditPayment);
         context.SaveChanges();
     }
 }
 public void UpdateRequest(Request request)
 {
     using (var context = new FinanceEntities())
     {
         context.Request.Attach(request);
         context.Entry(request).State = EntityState.Modified;
         context.SaveChanges();
     }
 }
 public void RemovePayment(int id)
 {
     using (var context = new FinanceEntities())
     {
         var payment = context.CreditPayment.Find(id);
         context.CreditPayment.Remove(payment);
         context.SaveChanges();
     }
 }
 public void UpdateDeposit(Deposit deposit)
 {
     using (var context = new FinanceEntities())
     {
         context.Deposit.Attach(deposit);
         context.Entry(deposit).State = EntityState.Modified;
         context.SaveChanges();
     }
 }
        public void PostChangePassword([FromBody] ChangePass cp) //Post to check if phone number exists in database
        {
            FinanceEntities db = new FinanceEntities();

            var query = (from x in db.Users where x.Phoneno == cp.phone select x).FirstOrDefault();

            query.Password = cp.password;
            db.SaveChanges();
        }
 public void UpdateCredit(Credit credit)
 {
     using (var context = new FinanceEntities())
     {
         context.Credit.Attach(credit);
         context.Entry(credit).State = EntityState.Modified;
         context.SaveChanges();
     }
 }
Beispiel #18
0
        public string Put(int id, [FromBody] Customer newcust)
        {
            string result = "";

            try
            {
                var olddata = db.Customers.Where(x => x.RegNumber == id).SingleOrDefault();
                if (olddata == null)
                {
                    throw new Exception("Invalid Id");
                }
                else
                {
                    // olddata.RegNumber = newcust.RegNumber;
                    olddata.CustName      = newcust.CustName;
                    olddata.PhoneNo       = newcust.PhoneNo;
                    olddata.CustEmail     = newcust.CustEmail;
                    olddata.CustUsername  = newcust.CustUsername;
                    olddata.CustPassword  = newcust.CustPassword;
                    olddata.CustAddress   = newcust.CustAddress;
                    olddata.CardType      = newcust.CardType;
                    olddata.BankName      = newcust.BankName;
                    olddata.AccountNumber = newcust.AccountNumber;
                    olddata.IFSCCode      = newcust.IFSCCode;
                    //  olddata.ApprovalStatus = newcust.ApprovalStatus;

                    var res = db.SaveChanges();
                    if (res > 0)
                    {
                        result = "Update Successful";
                    }
                    else
                    {
                        result = "Not updated";
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(result);
        }
 public void ResetDate()
 {
     using (var context = new FinanceEntities())
     {
         var date = context.GlobalDate.FirstOrDefault();
         if (date == null)
         {
             return;
         }
         date.Date = DateTime.Today;
         context.SaveChanges();
     }
 }
Beispiel #20
0
        public HttpResponseMessage PutConsumer(string id, [FromBody] Consumer updatedConsumer)
        {
            try
            {
                Consumer oldConsumer = financeEntities.Consumers.Find(id);
                if (oldConsumer == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, "Consumer Not Found"));
                }
                else
                {
                    oldConsumer.Name        = updatedConsumer.Name;
                    oldConsumer.PhoneNumber = updatedConsumer.PhoneNumber;
                    oldConsumer.Address     = updatedConsumer.Address;
                    oldConsumer.Email       = updatedConsumer.Email;

                    financeEntities.SaveChanges();
                    return(Request.CreateResponse(HttpStatusCode.Accepted, "Consumer Updated Successfully"));
                }
            } catch
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Consumer Could Not Be Updated"));
            }
        }
        public void SaveUpdateCreditType(CreditType model)
        {
            using (var context = new FinanceEntities())
            {
                if (model.Id == 0)
                {
                    context.CreditType.Add(model);
                }
                else
                {
                    context.Entry(model).State = EntityState.Modified;;
                }

                context.SaveChanges();
            }
        }
Beispiel #22
0
 public bool Post([FromBody] Customer cust)
 {
     try
     {
         fm.Customers.Add(cust);
         var res = fm.SaveChanges();
         if (res > 0)
         {
             return(true);
         }
     }
     catch (Exception e)
     {
         throw e;
     }
     return(false);
 }
Beispiel #23
0
        public void Post([FromBody] CardNew cu)
        {
            FinanceEntities db  = new FinanceEntities();
            CardDetail      c   = new CardDetail();
            Random          rd  = new Random();
            int             rno = rd.Next(000000, 999999);

            c.CustomerID       = (from a in db.Users where a.Username == cu.Username select a.CustomerID).FirstOrDefault();
            c.CardID           = "EMI" + rno;
            c.Validity         = cu.Validity;
            c.CardType         = cu.CardType;
            c.ActivationStatus = cu.ActivationStatus;
            c.TotalCredit      = cu.TotalCredit;
            c.RemainingCredit  = cu.RemainingCredit;
            c.EMIPendingStatus = cu.EmiPendingStatus;
            db.CardDetails.Add(c);
            db.SaveChanges();
        }
Beispiel #24
0
        public void Post([FromBody] Cardadd cu)
        {
            FinanceEntities db     = new FinanceEntities();
            CardDetail      c      = new CardDetail();
            int             custid = (from u in db.Users
                                      where u.Username == cu.Username
                                      select u.CustomerID).FirstOrDefault();
            var entry = (from cd in db.CardDetails
                         where cd.CustomerID == custid
                         select cd);

            foreach (var item in entry)
            {
                //item.RemainingCredit = item.TotalCredit - cu.RemainingCredit;
                item.EMIPendingStatus = true;
            }
            db.SaveChanges();
        }
        public void Post([FromBody] Purchase pur)
        {
            FinanceEntities db = new FinanceEntities();

            PurchaseDetail p = new PurchaseDetail();

            p.PurchaseID   = 1;
            p.ProductID    = pur.id;
            p.CardID       = "EMI093443";
            p.PurchaseDate = DateTime.Now;
            p.CustomerID   = 3;
            p.EmiScheme    = pur.scheme;
            p.EmiPerMonth  = pur.amount / pur.scheme;
            p.EmiPaid      = 0;
            p.EmiLeft      = pur.amount;

            db.PurchaseDetails.Add(p);
            db.SaveChanges();
        }
 public void AddDay()
 {
     using (var context = new FinanceEntities())
     {
         var date = context.GlobalDate.FirstOrDefault();
         if (date == null)
         {
             return;
         }
         date.Date = date.Date.AddDays(1);
         context.SaveChanges();
         try
         {
             context.Database.ExecuteSqlCommand("exec DepositOvercharge");
             context.Database.ExecuteSqlCommand("exec CreditOvercharge");
         }
         catch (Exception)
         {
         }
     }
 }
        public HttpResponseMessage ChangePassword(string id, [FromBody] Password updatePassword)
        {
            try
            {
                Consumer consumer = db.Consumers.Find(id);
                if (consumer == null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "User Does Not Exist"));
                }
                if (consumer.Password != updatePassword.OldPassword)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Wrong Old Password"));
                }
                consumer.Password = updatePassword.NewPassword;
                db.SaveChanges();

                return(Request.CreateResponse(HttpStatusCode.Accepted, "Password Updated Successfully"));
            } catch
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Password Could Not Be Changed"));
            }
        }
Beispiel #28
0
        public HttpResponseMessage useractivate(string username)
        {
            try
            {
                var ad = (from a in db.Admins
                          where a.UserName == username
                          select a).FirstOrDefault();

                if (ad.ActivationStatus == true)
                {
                    throw new Exception("UserActivated Already");
                }
                else
                {
                    ad.ActivationStatus = true;
                    CardTable ct = new CardTable();
                    ct.CardType = (from consumer in db.ConsumerTables
                                   where consumer.UserName == username
                                   select consumer.CardType).FirstOrDefault();
                    ct.Name            = username;
                    ct.RemainingCredit = (from cardtype in db.CardTypeTables
                                          where cardtype.CardType == ct.CardType
                                          select cardtype.TotalCredit).FirstOrDefault();
                    ct.TotalCredit = Convert.ToInt32((from cardtype in db.CardTypeTables
                                                      where cardtype.CardType == ct.CardType
                                                      select cardtype.TotalCredit).FirstOrDefault());
                    ct.ValidTill = db.validtill().FirstOrDefault().ToString();
                    db.CardTables.Add(ct);
                    db.SaveChanges();
                    return(Request.CreateResponse(HttpStatusCode.OK, "UserActivated"));
                }
            }
            catch (Exception)
            {
                return(Request.CreateResponse(HttpStatusCode.OK, "Activation Failed"));
            }
        }
        public void Post([FromBody] Pay pay)
        {
            FinanceEntities db = new FinanceEntities();

            var query = (from x in db.PurchaseDetails
                         where x.PurchaseID == pay.pur_id
                         select x).FirstOrDefault();


            var query1 = (from a in db.CardDetails
                          where a.CardID.Equals(query.CardID)
                          select a).FirstOrDefault();

            if (query.EmiLeft > 0)
            {
                query.EmiPaid          += query.EmiPerMonth;
                query.EmiLeft          -= query.EmiPerMonth;
                query.PaidForMonth      = "YES";
                query1.RemainingCredit += Convert.ToInt32(query.EmiPerMonth);
            }


            db.SaveChanges();
        }
Beispiel #30
0
 public IHttpActionResult PostRegister(ConsumerTable consumertable)
 {
     //if (!ModelState.IsValid)
     //{
     //    return BadRequest(ModelState);
     //}
     //else
     if (consumertable != null)
     {
         db.ConsumerTables.Add(consumertable);
         try {
             db.SaveChanges();
             return(Ok("Registered successfully"));
         }
         catch (Exception)
         {
             return(BadRequest("Enter the data"));
         }
     }
     else
     {
         return(BadRequest("Please enter the data"));
     }
 }
        public IHttpActionResult Put(CardDetail cardDetail)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                CardDetail c = new CardDetail();
                c = db.CardDetails.Find(cardDetail.CustomerID);
                if (c != null)
                {
                    c.ActivationStatus = cardDetail.ActivationStatus;
                }
                db.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }

            return(Ok(cardDetail));
        }
        public ActionResult Monetary()
        {
            Workbook  doc       = new Workbook();
            WebClient webClient = new WebClient();

            using (MemoryStream ms = new MemoryStream(webClient.DownloadData("http://www.cbc.gov.tw/public/Data/782416272371.xls")))
            {
                doc.LoadFromStream(ms);
            }

            MemoryStream stram = new MemoryStream();

            doc.SaveToStream(stram, FileFormat.Version97to2003);
            xlsService.UploadXLSAzure("mvc", "Upload", "Monetary.xls", stram);

            //doc.SaveToFile("https://uploadmvc.blob.core.windows.net/mvc/Upload/Monetary.xls", FileFormat.Version97to2003);
            //doc.SaveToFile(Server.MapPath("~/Upload/Monetary.xls"), FileFormat.Version97to2003);
            doc = null;
            //-------------------------------------

            CurrencyService.ClearData("Monetary");

            //-------------------------------------
            Workbook workbook = new Workbook();
            //workbook.LoadFromFile("https://uploadmvc.blob.core.windows.net/mvc/Upload/Monetary.xls");
            WebClient webClient1 = new WebClient();

            using (MemoryStream ms = new MemoryStream(webClient1.DownloadData("https://uploadmvc.blob.core.windows.net/mvc/Upload/Monetary.xls")))
            {
                workbook.LoadFromStream(ms);
            }
            Worksheet sheet = workbook.Worksheets[0];

            int Rows = sheet.LastRow;

            for (int i = Rows - 23; i < Rows + 1; i++)
            {
                MonetaryAggregate Temp_MA = new MonetaryAggregate();
                Temp_MA.QuotedDate      = DateTime.Parse(sheet.Range["A" + i].Value);
                Temp_MA.M1A_Annual_Rate = Decimal.Parse(sheet.Range["C" + i].Value);
                Temp_MA.M1A_Daily       = Decimal.Parse(sheet.Range["B" + i].Value);
                Temp_MA.M1B_Annual_Rate = Decimal.Parse(sheet.Range["G" + i].Value);
                Temp_MA.M1B_Daily       = Decimal.Parse(sheet.Range["F" + i].Value);
                Temp_MA.M2_Annual_Rate  = Decimal.Parse(sheet.Range["K" + i].Value);
                Temp_MA.M2_Daily        = Decimal.Parse(sheet.Range["J" + i].Value);

                db.MonetaryAggregates.Add(Temp_MA);
            }
            db.SaveChanges();

            MemoryStream stram1 = new MemoryStream();

            workbook.SaveToStream(stram1, FileFormat.Version97to2003);
            xlsService.UploadXLSAzure("mvc", "Upload", "Taifex-" + "Monetary.xls", stram);
            //workbook.SaveToFile("https://uploadmvc.blob.core.windows.net/mvc/Upload/Monetary.xls", FileFormat.Version97to2003);

            sheet    = null;
            workbook = null;

            return(View());
        }
Beispiel #33
0
        public HttpResponseMessage PlaceOrder([FromBody] Order newOrder)
        {
            try
            {
                Consumer consumer = financeEntities.Consumers.Find(newOrder.UserName);
                if (consumer == null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Username Is Invalid"));
                }

                Product selectedProduct = financeEntities.Products.Find(newOrder.ProductID);
                if (selectedProduct == null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Product Could Not Be Found"));
                }

                EMI scheme = financeEntities.EMIs.Find(newOrder.SchemeNo);
                if (scheme == null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "EMI Scheme Could Not Be Found"));
                }

                CompanyCard companyCard = financeEntities.CompanyCards.Where(c => c.UserName == newOrder.UserName).FirstOrDefault();
                if (companyCard == null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Conumser Card Balance Could Not Be Fetched"));
                }

                int emiCost     = CalculateMonthlyEMI(selectedProduct, scheme.Months);
                int orderAmount = emiCost * scheme.Months;

                if (orderAmount > companyCard.Balance)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Insufficient Balance To Place Order"));
                }

                if (DateTime.Compare(companyCard.Validity, DateTime.Now) < 0)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Your Card Is Deactivated"));
                }

                Transaction newTransaction = new Transaction()
                {
                    UserName        = consumer.UserName,
                    ProductID       = selectedProduct.ProductID,
                    SchemeNo        = scheme.SchemeNo,
                    PurchaseDate    = DateTime.Now,
                    EMIAmount       = emiCost,
                    RemainingAmount = orderAmount - emiCost,
                    LastChecked     = DateTime.Now
                };
                financeEntities.Entry(newTransaction).State = System.Data.Entity.EntityState.Added;

                var currentBalance = companyCard.Balance - emiCost;
                companyCard.Balance = currentBalance;

                Deduction newAmountDeduction = new Deduction()
                {
                    UserName      = consumer.UserName,
                    DeductionDate = DateTime.Now,
                    EMIAmout      = emiCost,
                    ProductID     = selectedProduct.ProductID
                };
                financeEntities.Entry(newAmountDeduction).State = System.Data.Entity.EntityState.Added;

                financeEntities.SaveChanges();
                return(Request.CreateResponse(HttpStatusCode.Created, "Order Placed Successfully"));
            } catch
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Order Could Not Be Placed"));
            }
        }
Beispiel #34
0
        public void UpdateStock(int Num)
        {
            try
            {
                List <Stock> stockList = new List <Stock>();
                int          nodes;
                //指定來源網頁
                WebClient url = new WebClient();
                //將網頁來源資料暫存到記憶體內
                MemoryStream ms = new MemoryStream(url.DownloadData("https://www.google.com/finance/historical?q=TPE%3A" + Num + "&start=0&num=220"));
                //以GoogleFinance為範例

                // 使用預設編碼讀入 HTML
                HtmlDocument    doc = new HtmlDocument();
                List <HtmlNode> tdNode;
                HtmlNode        tempNode;
                string          Text0;
                doc.Load(ms, Encoding.Default);

                Text0    = ((doc.DocumentNode.SelectSingleNode(@"/html[1]/body[1]").CssSelect("#gf-viewc").ToList())[0].CssSelect("h3").ToList())[0].InnerHtml.ToString();
                tempNode = (doc.DocumentNode.SelectSingleNode(@"/html[1]/body[1]").CssSelect("#prices").ToList())[0];
                tdNode   = tempNode.CssSelect("td").ToList();
                nodes    = (tempNode.CssSelect("tr").Count()) / 2;

                // 取得股價
                for (int num = 0; num < nodes; num++)
                {
                    string Text1, Text2;
                    Stock  stock_temp = new Stock();
                    stock_temp.Id = Num;

                    if (Text0.IndexOf("Co.") > 0)
                    {
                        stock_temp.stockName = Text0.Remove(Text0.IndexOf("Co.")).Trim();
                    }
                    else
                    {
                        stock_temp.stockName = Text0.Trim();
                    }

                    Text1 = tdNode[0 + 6 * num].InnerText;
                    Text2 = tdNode[1 + 6 * num].InnerText;
                    stock_temp.Price_Date = DateTime.Parse(Text(Text1, Text2));

                    Text1 = tdNode[1 + 6 * num].InnerText;
                    Text2 = tdNode[2 + 6 * num].InnerText;
                    stock_temp.Price_Open = Decimal.Parse(Text(Text1, Text2));

                    Text1 = tdNode[2 + 6 * num].InnerText;
                    Text2 = tdNode[3 + 6 * num].InnerText;
                    stock_temp.Price_High = Decimal.Parse(Text(Text1, Text2));

                    Text1 = tdNode[3 + 6 * num].InnerText;
                    Text2 = tdNode[4 + 6 * num].InnerText;
                    stock_temp.Price_Low = Decimal.Parse(Text(Text1, Text2));

                    Text1 = tdNode[4 + 6 * num].InnerText;
                    Text2 = tdNode[5 + 6 * num].InnerText;
                    stock_temp.Price_Close = Decimal.Parse(Text(Text1, Text2));

                    Text1             = tdNode[5 + 6 * num].InnerText;
                    Text2             = tdNode[6 + 6 * num].InnerText;
                    stock_temp.Volume = Int32.Parse(Text(Text1, Text2));

                    stockList.Add(stock_temp);
                }

                foreach (var item in stockList)
                {
                    db.Stocks.Add(item);
                }
                db.SaveChanges();

                //清除資料
                doc = null;
                url = null;
                ms.Close();
            }
            catch (System.IO.IOException e)
            {
                logger.Error(LogUtility.GetExceptionDetails(e));
                return;
            }
        }
        //making changes on the orderdeatails, products, orders, cardtable on successful order
        #region OrderPayment
        //Calculating the Required field for the order such as total amount, emi per month, processing etc.
        //generating the order id and deducting the amount from card based on the product purchased.
        /// <summary>
        /// OrderPayment
        /// </summary>
        /// <param name=int "productid"></param>
        /// <param name= int "quantity"></param>
        /// <param name=int "EMI"></param>
        /// <param name= from login"username"></param>
        /// <returns>on sucessful order deducts the amount from card</returns>
        public HttpResponseMessage GetOrderinfo(int productid, int quantity, int EMI, string username)
        {
            Product product = (from p in db.Products
                               where p.ProductID == productid
                               select p).FirstOrDefault();
            int    TotalAmount   = quantity * product.CostPerUnit;
            double ProcessingFee = 0.02 * TotalAmount;
            double AmountPayable = TotalAmount + ProcessingFee;
            double EMIperMonth   = AmountPayable / EMI;
            long   cardnumber    = (from c in db.CardTables
                                    where c.Name == username
                                    select c.CardNumber).FirstOrDefault();

            Product pro = new Product();

            if (quantity > pro.AvailableQuantity)
            {
                return(Request.CreateResponse(HttpStatusCode.OK, "Products are out of Stock, Please order in less Quantity"));
            }
            else
            {
                CardTable ct = (from c in db.CardTables
                                where c.CardNumber == cardnumber
                                select c).FirstOrDefault();
                if (AmountPayable > ct.RemainingCredit)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, "You donot Have Enough Credits to buy this Product"));
                }
                else
                {
                    try
                    {
                        db.Orders.Add(new Order {
                            OrderDate = DateTime.Now, AmountPayable = AmountPayable, EMI_Tenure_In_Months = EMI, BillAmountperMonth = EMIperMonth, CardNumber = cardnumber, Remaining_EMI_Tenures = EMI, LastPaymentDate = null
                        });
                        db.SaveChanges();
                    }
                    catch (Exception)
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK, "Order not placed"));
                    }

                    try
                    {
                        int orderid = Convert.ToInt32((from o in db.Orders
                                                       where o.CardNumber == cardnumber
                                                       select o.OrderID).ToList().LastOrDefault());
                        db.OrderDetails.Add(new OrderDetail {
                            OrderID = orderid, ProductID = productid, Quantity = quantity, TotalAmount = TotalAmount, ProcessingFee = ProcessingFee
                        });
                        CardTable cardtable = (from c in db.CardTables
                                               where c.CardNumber == cardnumber
                                               select c).FirstOrDefault();
                        cardtable.RemainingCredit = cardtable.RemainingCredit - AmountPayable;
                        Product Pro1 = (from p in db.Products
                                        where p.ProductID == productid
                                        select p).FirstOrDefault();
                        Pro1.AvailableQuantity = Pro1.AvailableQuantity - quantity;
                        db.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK, e.Message));
                    }
                    return(Request.CreateResponse(HttpStatusCode.OK, "Order Placed & Purchase Successfull. Your EMI amount Per Month is" + " " + EMIperMonth));
                }
            }
        }
        public HttpResponseMessage Adduser(ConsumerTable consumer)
        {
            var username = (from c in db.ConsumerTables
                            where c.UserName == consumer.UserName
                            select c.UserName).ToList();

            if (username.Count > 0)
            {
                return(Request.CreateResponse(HttpStatusCode.OK, "This User Name is taken, Please Choose different username"));
            }
            else
            {
                var email = (from c in db.ConsumerTables
                             where c.Email == consumer.Email
                             select c.Email).ToList();
                if (email.Count > 0)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, "Userdata with given email already exists. Please choose different email or Login with current email"));
                }
                else
                {
                    var phone = (from c in db.ConsumerTables
                                 where c.PhoneNo == consumer.PhoneNo
                                 select c.PhoneNo).ToList();
                    if (phone.Count > 0)
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK, "Userdata with given Phone Number already exists. Please Login"));
                    }
                    else
                    {
                        DateTime currentdate = System.DateTime.Now;
                        TimeSpan time        = currentdate.Subtract(consumer.DateofBirth);
                        if (time.Days < 3650)
                        {
                            return(Request.CreateResponse(HttpStatusCode.OK, "You are Not eligible. The user should be 10 years old or above"));
                        }
                        byte[] encData_byte = new byte[consumer.Password.Length];
                        encData_byte = System.Text.Encoding.UTF8.GetBytes(consumer.Password);
                        string encodedpassword = Convert.ToBase64String(encData_byte);
                        consumer.Password = encodedpassword;

                        ConsumerTable ct = new ConsumerTable();
                        ct.UserName      = consumer.UserName;
                        ct.DateofBirth   = consumer.DateofBirth;
                        ct.Name          = consumer.Name;
                        ct.Email         = consumer.Email;
                        ct.PhoneNo       = consumer.PhoneNo;
                        ct.Password      = consumer.Password;
                        ct.Address       = consumer.Address;
                        ct.CardType      = consumer.CardType;
                        ct.SelectBank    = consumer.SelectBank;
                        ct.AccountNumber = consumer.AccountNumber;
                        ct.IFSC_Code     = consumer.IFSC_Code;
                        try
                        {
                            db.ConsumerTables.Add(ct);
                            db.SaveChanges();
                            db.adduserinadmin(consumer.UserName);
                            db.SaveChanges();
                            return(Request.CreateResponse(HttpStatusCode.OK, "Registered Successfully!!!"));
                        }
                        catch (Exception)
                        {
                            return(Request.CreateResponse(HttpStatusCode.OK, "The mailid or the Name given is too large"));
                        }
                    }
                }
            }
        }