Ejemplo n.º 1
0
        public async Task CreateFileData_Always_CreatesFileData()
        {
            // Arrange
            CustomerFile customerFile = new CustomerFile("WEE", (ulong)12345);
            var          customerFileGeneratorResult         = new IbisFileGeneratorResult <CustomerFile>(customerFile, A.Dummy <List <Exception> >());
            IIbisCustomerFileGenerator customerFileGenerator = A.Fake <IIbisCustomerFileGenerator>();

            A.CallTo(() => customerFileGenerator.CreateAsync(A <ulong> ._, A <InvoiceRun> ._))
            .Returns(customerFileGeneratorResult);

            TransactionFile transactionFile         = new TransactionFile("WEE", (ulong)12345);
            var             ibisFileGeneratorResult = new IbisFileGeneratorResult <TransactionFile>(transactionFile, A.Dummy <List <Exception> >());
            IIbisTransactionFileGenerator transactionFileGenerator = A.Fake <IIbisTransactionFileGenerator>();

            A.CallTo(() => transactionFileGenerator.CreateAsync(A <ulong> ._, A <InvoiceRun> ._))
            .Returns(ibisFileGeneratorResult);

            IIbisFileDataErrorTranslator errorTranslator = A.Dummy <IIbisFileDataErrorTranslator>();

            IbisFileDataGenerator generator = new IbisFileDataGenerator(
                customerFileGenerator,
                transactionFileGenerator,
                errorTranslator);

            // Act
            var result = await generator.CreateFileDataAsync(A.Dummy <ulong>(), A.Dummy <InvoiceRun>());

            var ibistFileData = result.IbisFileData;

            // Assert
            Assert.NotNull(ibistFileData);
            Assert.False(string.IsNullOrEmpty(ibistFileData.CustomerFileData));
            Assert.False(string.IsNullOrEmpty(ibistFileData.TransactionFileData));
        }
Ejemplo n.º 2
0
        public IActionResult OnGet(int?Id)
        {
            //DBConnection DBCon = new DBConnection();
            string        DbString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Isaac Bowyer\source\repos\Primark\Primark\Data\Customer_Files.mdf;Integrated Security=True";
            SqlConnection conn     = new SqlConnection(DbString);

            conn.Open();

            using (SqlCommand command = new SqlCommand())
            {
                command.Connection  = conn;
                command.CommandText = @"SELECT * FROM CustomerFile WHERE Id = @Id";
                command.Parameters.AddWithValue("@Id", Id);

                var reader = command.ExecuteReader();

                CusFileRec = new CustomerFile();
                while (reader.Read())
                {
                    CusFileRec.Id            = reader.GetInt32(0);
                    CusFileRec.CustomerFName = reader.GetString(1);
                    CusFileRec.CustomerLName = reader.GetString(2);
                    CusFileRec.FileName      = reader.GetString(3);
                }

                Console.WriteLine("File name : " + CusFileRec.FileName);
            }

            return(Page());
        }
        public async Task <FileResult> Download(string fileId, string fileName)
        {
            //return File(Path.Combine(Server.MapPath("~/App_Data/Upload/"), p), System.Net.Mime.MediaTypeNames.Application.Octet, d);
            CustomerFile custFile = await APIServices.DownloadFile(fileId).ConfigureAwait(false);

            return(File(custFile.DocumentData, System.Net.Mime.MediaTypeNames.Application.Octet, fileName));
        }
Ejemplo n.º 4
0
        public async Task <IHttpActionResult> DownloadFile()
        {
            if (ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value != "user_impersonation")
            {
                throw new HttpResponseException(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.Unauthorized, ReasonPhrase = "The Scope claim does not contain 'user_impersonation' or scope claim not found"
                });
            }

            Claim subject = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier);

            CustomerFile custFile = await ProcessCustomerFileData();

            CloudBlobContainer container = GetContainer();

            custFile = SqlDBRepository.GetLegalDocumentData(custFile.Id);

            CloudBlobDirectory caseDirectory = container.GetDirectoryReference("case" + custFile.CaseId.ToString().ToLower());
            CloudBlockBlob     blockBlob     = caseDirectory.GetBlockBlobReference(custFile.Id.ToString() + "_" + custFile.DocumentType);

            blockBlob.FetchAttributes();
            byte[] byteData = new byte[blockBlob.Properties.Length];
            blockBlob.DownloadToByteArray(byteData, 0);

            custFile.DocumentData = byteData;

            return(Ok(custFile));
        }
Ejemplo n.º 5
0
        public async Task <HttpResponseMessage> DeleteFile()
        {
            if (ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value != "user_impersonation")
            {
                throw new HttpResponseException(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.Unauthorized, ReasonPhrase = "The Scope claim does not contain 'user_impersonation' or scope claim not found"
                });
            }

            Claim subject = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier);

            CustomerFile custFile = await ProcessCustomerFileData();

            CloudBlobContainer container = GetContainer();

            custFile = SqlDBRepository.GetLegalDocumentData(custFile.Id);
            // Delete customer case directory from container for broker.

            CloudBlobDirectory caseDirectory = container.GetDirectoryReference("case" + custFile.CaseId.ToString().ToLower());
            CloudBlockBlob     blockBlob     = caseDirectory.GetBlockBlobReference(custFile.Id.ToString() + "_" + custFile.DocumentType);

            blockBlob.DeleteIfExists();

            bool status = SqlDBRepository.DeleteLegalDocument(custFile);

            return(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK
            });
        }
Ejemplo n.º 6
0
        public void OnGet()
        {
            //DBConnection DBCon = new DBConnection();
            string        DbString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Isaac Bowyer\source\repos\Primark\Primark\Data\Customer_Files.mdf;Integrated Security=True";
            SqlConnection conn     = new SqlConnection(DbString);

            conn.Open();

            using (SqlCommand command = new SqlCommand())
            {
                command.Connection  = conn;
                command.CommandText = @"SELECT * FROM CustomerFile";

                var reader = command.ExecuteReader();

                FileRec = new List <CustomerFile>();

                while (reader.Read())
                {
                    CustomerFile rec = new CustomerFile();
                    rec.Id            = reader.GetInt32(0);
                    rec.CustomerFName = reader.GetString(1);
                    rec.CustomerLName = reader.GetString(2);
                    rec.FileName      = reader.GetString(3);
                    FileRec.Add(rec);
                }
            }
        }
Ejemplo n.º 7
0
        public ActionResult AddFile(int customerId, HttpPostedFileBase upload)
        {
            var customer = db.Read(customerId);

            if (isAuthorized(customer.Id) == AuthState.NoAuth)
            {
                return(View("NotAuthorized"));
            }
            if (upload != null && upload.ContentLength > 0)
            {
                var attachment = new CustomerFile()
                {
                    ContentType         = upload.ContentType,
                    CustomerContentType = new CustomerContentType(),
                    Name = System.IO.Path.GetFileName(upload.FileName),
                };

                using (var reader = new System.IO.BinaryReader(upload.InputStream))
                {
                    attachment.CustomerContentType.Content = reader.ReadBytes(upload.ContentLength);
                }
                attachment.CustomerId  = customerId;
                attachment.Customer    = new Customer();
                attachment.Customer.Id = customerId;
                dbFile.Create(attachment);
            }
            return(Redirect(Request.UrlReferrer.ToString()));
        }
        public async Task CreateFileData_Always_CreatesFileData()
        {
            // Arrange
            CustomerFile customerFile = new CustomerFile("WEE", (ulong)12345);
            var customerFileGeneratorResult = new IbisFileGeneratorResult<CustomerFile>(customerFile, A.Dummy<List<Exception>>());
            IIbisCustomerFileGenerator customerFileGenerator = A.Fake<IIbisCustomerFileGenerator>();
            A.CallTo(() => customerFileGenerator.CreateAsync(A<ulong>._, A<InvoiceRun>._))
                .Returns(customerFileGeneratorResult);

            TransactionFile transactionFile = new TransactionFile("WEE", (ulong)12345);
            var ibisFileGeneratorResult = new IbisFileGeneratorResult<TransactionFile>(transactionFile, A.Dummy<List<Exception>>());
            IIbisTransactionFileGenerator transactionFileGenerator = A.Fake<IIbisTransactionFileGenerator>();
            A.CallTo(() => transactionFileGenerator.CreateAsync(A<ulong>._, A<InvoiceRun>._))
                .Returns(ibisFileGeneratorResult);

            IIbisFileDataErrorTranslator errorTranslator = A.Dummy<IIbisFileDataErrorTranslator>();

            IbisFileDataGenerator generator = new IbisFileDataGenerator(
                customerFileGenerator,
                transactionFileGenerator,
                errorTranslator);

            // Act
            var result = await generator.CreateFileDataAsync(A.Dummy<ulong>(), A.Dummy<InvoiceRun>());
            var ibistFileData = result.IbisFileData;

            // Assert
            Assert.NotNull(ibistFileData);
            Assert.False(string.IsNullOrEmpty(ibistFileData.CustomerFileData));
            Assert.False(string.IsNullOrEmpty(ibistFileData.TransactionFileData));
        }
        public async Task CreateFileData_WithFileID_CreatesFilesWithCorrectFileNames()
        {
            // Arrange
            ulong fileID = 123;

            CustomerFile customerFile = new CustomerFile("WEE", (ulong)12345);
            var customerFileGeneratorResult = new IbisFileGeneratorResult<CustomerFile>(customerFile, A.Dummy<List<Exception>>());
            IIbisCustomerFileGenerator customerFileGenerator = A.Fake<IIbisCustomerFileGenerator>();
            A.CallTo(() => customerFileGenerator.CreateAsync(A<ulong>._, A<InvoiceRun>._))
                .Returns(customerFileGeneratorResult);

            TransactionFile transactionFile = new TransactionFile("WEE", (ulong)12345);
            var ibisFileGeneratorResult = new IbisFileGeneratorResult<TransactionFile>(transactionFile, A.Dummy<List<Exception>>());
            IIbisTransactionFileGenerator transactionFileGenerator = A.Fake<IIbisTransactionFileGenerator>();
            A.CallTo(() => transactionFileGenerator.CreateAsync(A<ulong>._, A<InvoiceRun>._))
                .Returns(ibisFileGeneratorResult);

            IIbisFileDataErrorTranslator errorTranslator = A.Dummy<IIbisFileDataErrorTranslator>();

            IbisFileDataGenerator generator = new IbisFileDataGenerator(
                customerFileGenerator,
                transactionFileGenerator,
                errorTranslator);

            // Act
            var result = await generator.CreateFileDataAsync(fileID, A.Dummy<InvoiceRun>());
            var ibistFileData = result.IbisFileData;

            // Assert
            Assert.NotNull(ibistFileData);
            Assert.Equal("WEEHC00123.dat", ibistFileData.CustomerFileName);
            Assert.Equal("WEEHI00123.dat", ibistFileData.TransactionFileName);
        }
Ejemplo n.º 10
0
 private void accordionControlElement45_Click(object sender, EventArgs e)
 {
     cf = new CustomerFile();
     cf.Show();
     cf.Dock = DockStyle.Fill;
     panel2.Controls.Clear();
     panel2.Controls.Add(cf);
 }
Ejemplo n.º 11
0
 public IHttpActionResult PostCustomerFile(CustomerFile file)
 {
     if (!ModelState.IsValid)
     {
         return(BadRequest(ModelState));
     }
     db.Create(file);
     return(CreatedAtRoute("DefaultApi", new { id = file.Id }, file));
 }
Ejemplo n.º 12
0
    } // End of the GetCountByCustomerId method

    #endregion

    #region Get methods

    /// <summary>
    /// Get one customer file based on id
    /// </summary>
    /// <param name="customerId">The customer id</param>
    /// <param name="productId">The product id</param>
    /// <param name="languageId">The language id</param>
    /// <returns>A reference to a customer file post</returns>
    public static CustomerFile GetOneById(Int32 customerId, Int32 productId, Int32 languageId)
    {
        // Create the post to return
        CustomerFile post = null;

        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "SELECT * FROM dbo.customers_files WHERE customer_id = @customer_id AND " 
            + "product_id = @product_id AND language_id = @language_id;";

        // The using block is used to call dispose automatically even if there is a exception
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there is a exception
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@customer_id", customerId);
                cmd.Parameters.AddWithValue("@product_id", productId);
                cmd.Parameters.AddWithValue("@language_id", languageId);

                // Create a reader
                SqlDataReader reader = null;

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Fill the reader with one row of data.
                    reader = cmd.ExecuteReader();

                    // Loop through the reader as long as there is something to read and add values
                    while (reader.Read())
                    {
                        post = new CustomerFile(reader);
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    // Call Close when done reading to avoid memory leakage.
                    if (reader != null)
                        reader.Close();
                }
            }
        }

        // Return the post
        return post;

    } // End of the GetOneById method
Ejemplo n.º 13
0
        public IHttpActionResult GetCustomerFile(int id)
        {
            CustomerFile asset = db.Read(id);

            if (asset == null)
            {
                return(NotFound());
            }

            return(Ok(asset));
        }
Ejemplo n.º 14
0
        public IHttpActionResult DeleteCustomerFile(int id)
        {
            CustomerFile file = db.Read(id);

            if (file == null)
            {
                return(NotFound());
            }
            db.Delete(file);

            return(Ok(file));
        }
Ejemplo n.º 15
0
        } // End of the delete method

        #endregion

        #region Helper methods

        /// <summary>
        /// Update the payment status
        /// </summary>
        /// <param name="order">A reference to the order</param>
        /// <param name="paymentStatus">The payment status as a string</param>
        /// <returns>An error message as a string</returns>
        private string UpdatePaymentStatus(Order order, string paymentStatus)
        {
            // Create the string to return
            string error_message = "";

            // Check the status change
            if (paymentStatus == "payment_status_invoice_approved" || paymentStatus == "payment_status_paid")
            {
                CustomerFile.AddCustomerFiles(order);
            }

            // Return the error message
            return error_message;

        } // End of the UpdatePaymentStatus method
Ejemplo n.º 16
0
        public IHttpActionResult PutCustomerFile(int id, CustomerFile asset)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != asset.Id)
            {
                return(BadRequest());
            }
            db.Update(asset);


            return(StatusCode(HttpStatusCode.NoContent));
        }
Ejemplo n.º 17
0
        public ActionResult Upload(CustomerUploadVM vm)
        {
            var customer = _context.Customers.Include(c => c.CustomerFiles).SingleOrDefault(c => c.Id == vm.CustomerId);

            try
            {
                if (vm.File.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(vm.File.FileName);
                    var path     = Path.Combine(Server.MapPath("~/App_Data/CustomerFiles"), fileName);
                    vm.File.SaveAs(path);



                    var customerFile = new CustomerFile();

                    var userId = User.Identity.GetUserId();
                    var user   = _context.Users.SingleOrDefault(u => u.Id == userId);

                    customerFile.UploadedBy = user;
                    customerFile.DateTime   = DateTime.Now;
                    customerFile.Customer   = customer;
                    customerFile.FilePath   = path;
                    customerFile.FileName   = fileName;

                    _context.CustomerFiles.Add(customerFile);
                    customer.CustomerFiles.Add(customerFile);

                    _context.SaveChanges();
                }


                //ViewBag.Message = "Upload successful";

                //find customer by Id and add 'path' to files iCollection
                //return RedirectToAction("Index");


                return(RedirectToAction("CustomerFiles", new { id = customer.Id }));
            }
            catch
            {
                ViewBag.Message = "Upload failed";
                return(RedirectToAction("Uploads"));
            }
        }
Ejemplo n.º 18
0
        public ActionResult delete_file(Int32 customerId = 0, Int32 productId = 0, string returnUrl = "")
        {
            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();
            ViewBag.CurrentDomain = currentDomain;

            // Get query parameters
            ViewBag.QueryParams = new QueryParams(returnUrl);

            // Check if the administrator is authorized
            if (Administrator.IsAuthorized(new string[] { "Administrator" }) == true)
            {
                ViewBag.AdminSession = true;
            }
            else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true)
            {
                ViewBag.AdminSession = true;
                ViewBag.AdminErrorCode = 1;
                ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");
                return View("index");
            }
            else
            {
                // Redirect the user to the start page
                return RedirectToAction("index", "admin_login");
            }

            // Create an error code variable
            Int32 errorCode = 0;

            // Delete the customer file and all the connected posts (CASCADE)
            errorCode = CustomerFile.DeleteOnId(customerId, productId);

            // Check if there is an error
            if (errorCode != 0)
            {
                ViewBag.AdminErrorCode = errorCode;
                ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");
                return View("index");
            }

            // Redirect the user to the list
            return Redirect("/admin_customers" + returnUrl);

        } // End of the delete_file method
Ejemplo n.º 19
0
        private async Task <CustomerFile> ProcessCustomerFileData()
        {
            CustomerFile custFile = new CustomerFile();

            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var outerMultipart = await Request.Content.ReadAsMultipartAsync();

            var multipart = outerMultipart.Contents[0];

            String jsonObj = await multipart.ReadAsStringAsync();

            custFile = JsonConvert.DeserializeObject <CustomerFile>(jsonObj);

            return(custFile);
        }
Ejemplo n.º 20
0
        public async Task CreateFileData_WithErrorGeneratingIbisFile_TranslatesError_AndReturnNoIbisFileData()
        {
            // Arrange
            ulong fileID = 123;

            var customerFile = new CustomerFile("WEE", fileID);
            var customerFileGeneratorResult = new IbisFileGeneratorResult <CustomerFile>(customerFile, A.Dummy <List <Exception> >());

            var customerFileGenerator = A.Fake <IIbisCustomerFileGenerator>();

            A.CallTo(() => customerFileGenerator.CreateAsync(A <ulong> ._, A <InvoiceRun> ._))
            .Returns(customerFileGeneratorResult);

            var transactionFile = new TransactionFile("WEE", (ulong)12345);
            var error           = new Exception();
            var transactionFileGeneratorResult = new IbisFileGeneratorResult <TransactionFile>(transactionFile, new List <Exception> {
                error
            });

            var transactionFileGenerator = A.Fake <IIbisTransactionFileGenerator>();

            A.CallTo(() => transactionFileGenerator.CreateAsync(A <ulong> ._, A <InvoiceRun> ._))
            .Returns(transactionFileGeneratorResult);

            var errorTranslator = A.Fake <IIbisFileDataErrorTranslator>();

            A.CallTo(() => errorTranslator.MakeFriendlyErrorMessages(A <List <Exception> > ._))
            .Returns(new List <string> {
                "error"
            });

            IbisFileDataGenerator generator = new IbisFileDataGenerator(
                customerFileGenerator,
                transactionFileGenerator,
                errorTranslator);

            // Act
            var result = await generator.CreateFileDataAsync(fileID, A.Dummy <InvoiceRun>());

            // Assert
            Assert.NotEmpty(result.Errors);
            Assert.Null(result.IbisFileData);
        }
Ejemplo n.º 21
0
        internal static async Task <CustomerFile> DownloadFile(string fileId)
        {
            CustomerFile custFile = new CustomerFile();

            custFile.Id = new Guid(fileId);
            var json       = JsonConvert.SerializeObject(custFile);
            var strContent = new StringContent(json, Encoding.UTF8, "application/json");
            var content    = new MultipartContent();

            content.Add(strContent);

            HttpResponseMessage response = await SendApiRequest("api/Upload/DownloadFile", content);

            if (response.IsSuccessStatusCode)
            {
                custFile = await response.Content.ReadAsAsync <CustomerFile>();
            }
            return(custFile);
        }
Ejemplo n.º 22
0
    } // End of the Add method

    /// <summary>
    /// Add customer files 
    /// </summary>
    /// <param name="order">A reference to the order</param>
    public static void AddCustomerFiles(Order order)
    {
        // Get the current domain
        Domain domain = Tools.GetCurrentDomain();

        // Get the order rows
        List<OrderRow> orderRows = OrderRow.GetByOrderId(order.id);

        // Get the customer
        Customer customer = Customer.GetOneById(order.customer_id);

        // Loop all of the order rows
        for (int i = 0; i < orderRows.Count; i++)
        {
            // Get the product
            Product product = Product.GetOneById(orderRows[i].product_id, domain.back_end_language);

            // Continue if the product is null
            if (product == null) { continue; }

            // Check if the product has a downloadable files
            if (product.downloadable_files == true)
            {
                // Create the customer file
                CustomerFile customerFile = new CustomerFile();
                customerFile.customer_id = customer.id;
                customerFile.product_id = product.id;
                customerFile.language_id = customer.language_id;
                customerFile.order_date = order.order_date;

                // Check if the file already exists
                CustomerFile savedFile = CustomerFile.GetOneById(customerFile.customer_id, customerFile.product_id, customerFile.language_id);

                if (savedFile == null)
                {
                    // Add the customer file
                    CustomerFile.Add(customerFile);
                }
            }
        }

    } // End of the AddCustomerFiles method
        public Task <IbisFileGeneratorResult <CustomerFile> > CreateAsync(ulong fileID, InvoiceRun invoiceRun)
        {
            CustomerFile customerFile = new CustomerFile("WEE", fileID);

            var errors = new List <Exception>();

            IEnumerable <Scheme> schemes = invoiceRun.MemberUploads
                                           .Select(mu => mu.Scheme)
                                           .Distinct();

            foreach (Scheme scheme in schemes)
            {
                try
                {
                    var postCode = GetIbisPostCode(scheme.Address);

                    Address address = new Address(
                        scheme.Contact.FullName,
                        scheme.Address.Address1,
                        scheme.Address.Address2,
                        null,
                        scheme.Address.TownOrCity,
                        scheme.Address.CountyOrRegion,
                        postCode);

                    Customer customer = new Customer(
                        scheme.IbisCustomerReference,
                        scheme.Organisation.OrganisationName,
                        address);

                    customerFile.AddCustomer(customer);
                }
                catch (Exception ex)
                {
                    errors.Add(new SchemeFieldException(scheme, ex));
                }
            }

            var ibisFileGeneratorResult = new IbisFileGeneratorResult <CustomerFile>(errors.Count == 0 ? customerFile : null, errors);

            return(Task.FromResult(ibisFileGeneratorResult));
        }
        public Task<IbisFileGeneratorResult<CustomerFile>> CreateAsync(ulong fileID, InvoiceRun invoiceRun)
        {
            CustomerFile customerFile = new CustomerFile("WEE", fileID);

            var errors = new List<Exception>();

            IEnumerable<Scheme> schemes = invoiceRun.MemberUploads
                .Select(mu => mu.Scheme)
                .Distinct();

            foreach (Scheme scheme in schemes)
            {
                try
                {
                    var postCode = GetIbisPostCode(scheme.Organisation.OrganisationAddress);

                    Address address = new Address(
                        scheme.Organisation.Contact.FullName,
                        scheme.Organisation.OrganisationAddress.Address1,
                        scheme.Organisation.OrganisationAddress.Address2,
                        null,
                        scheme.Organisation.OrganisationAddress.TownOrCity,
                        scheme.Organisation.OrganisationAddress.CountyOrRegion,
                        postCode);

                    Customer customer = new Customer(
                            scheme.IbisCustomerReference,
                            scheme.Organisation.OrganisationName,
                            address);

                    customerFile.AddCustomer(customer);
                }
                catch (Exception ex)
                {
                    errors.Add(new SchemeFieldException(scheme, ex));
                }
            }

            var ibisFileGeneratorResult = new IbisFileGeneratorResult<CustomerFile>(errors.Count == 0 ? customerFile : null, errors);
            return Task.FromResult(ibisFileGeneratorResult);
        }
Ejemplo n.º 25
0
        public JsonResult InsertFile([FromBody] CustomerFile obj)
        {
            var msg = new JMessage {
                Error = false, Title = ""
            };

            try
            {
                obj.FileType    = System.IO.Path.GetExtension(obj.FileName);
                obj.CreatedTime = DateTime.Now.Date;
                _context.CustomerFiles.Add(obj);
                _context.SaveChanges();
                msg.Title = "Thêm tệp tin thành công!";
            }
            catch (Exception ex)
            {
                msg.Error = true;
                msg.Title = "Có lỗi xảy ra!";
            }
            return(Json(msg));
        }
Ejemplo n.º 26
0
        public JsonResult UpdateFile([FromBody] CustomerFile obj)
        {
            var msg = new JMessage {
                Error = false, Title = ""
            };

            try
            {
                obj.UpdatedTime = DateTime.Now.Date;
                _context.CustomerFiles.Update(obj);
                _context.SaveChanges();
                msg.Title = "Chỉnh sửa tệp tin thành công!";
            }
            catch (Exception ex)
            {
                msg.Error  = true;
                msg.Title  = "Có lỗi xảy ra!";
                msg.Object = ex;
            }
            return(Json(msg));
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Creates the data representing 1B1S customer and transaction files for the specified list
        /// of member uploads.
        /// </summary>
        /// <param name="fileID">The ID that the 1B1S files will use. This must be unique for every pair of 1B1S files
        /// and must be in the range of 0 to 99999. To avoid clashes with IDs used by the incumbent system, a seed
        /// value may need to be used.</param>
        /// <param name="invoiceRun">The invoice run specifying the list of member uploads to be included.</param>
        /// <returns>Returns an <see cref="IbisFileDataGeneratorResult"/> which provides the data and file names of the
        /// generated 1B1S customer and transaction files or a list of error which occurred during the process.</returns>
        public async Task <IbisFileDataGeneratorResult> CreateFileDataAsync(ulong fileID, InvoiceRun invoiceRun)
        {
            var customerFileGeneratorResult = await ibisCustomerFileGenerator.CreateAsync(fileID, invoiceRun);

            var ibisTransactionFileGeneratorResult = await ibisTransactionFileGenerator.CreateAsync(fileID, invoiceRun);

            IbisFileData ibisFileData = null;
            var          errors       = new List <string>();

            if (customerFileGeneratorResult.Errors.Count == 0 &&
                ibisTransactionFileGeneratorResult.Errors.Count == 0)
            {
                CustomerFile    customerFile    = customerFileGeneratorResult.IbisFile;
                TransactionFile transactionFile = ibisTransactionFileGeneratorResult.IbisFile;

                string customerFileName    = string.Format("WEEHC{0:D5}.dat", fileID);
                string transactionFileName = string.Format("WEEHI{0:D5}.dat", fileID);

                string customerFileData    = customerFile.Write();
                string transactionFileData = transactionFile.Write();

                ibisFileData = new IbisFileData(
                    fileID,
                    customerFileName,
                    customerFileData,
                    transactionFileName,
                    transactionFileData);
            }
            else
            {
                errors = ibisFileDataErrorTranslator
                         .MakeFriendlyErrorMessages(customerFileGeneratorResult
                                                    .Errors
                                                    .Union(ibisTransactionFileGeneratorResult.Errors)
                                                    .ToList());
            }

            return(new IbisFileDataGeneratorResult(ibisFileData, errors));
        }
Ejemplo n.º 28
0
        public void Write_WithOneCustomer_GeneratesCorrectOutput()
        {
            // Arrange
            Address  address  = new Address("1 High Street", "Flat 123", "Business Park", "Newtown", "Nr Oldtown", "Testshire", "AA1 1AA");
            Customer customer = new Customer("WEE0001", "Test customer", address);

            CustomerFile file = new CustomerFile("WEE", 0);

            file.AddCustomer(customer);

            // Act
            string result = file.Write();

            // Assert
            string expectedDate   = DateTime.UtcNow.Date.ToString("dd-MMM-yyyy").ToUpperInvariant();
            string expectedOutput =
                "\"H\",\"0000000\",\"WEE\",\"H\",\"C\",\"00000\",\"" + expectedDate + "\"" + Environment.NewLine +
                "\"D\",\"0000001\",\"WEE0001\",\"Test customer\",\"1 High Street\",\"Flat 123\",\"Business Park\",\"Newtown\",\"Nr Oldtown\",\"Testshire\",\"AA1 1AA\"" + Environment.NewLine +
                "\"T\",\"0000002\",\"0000003\"" + Environment.NewLine;

            Assert.Equal(expectedOutput, result);
        }
Ejemplo n.º 29
0
        internal static bool DeleteLegalDocument(CustomerFile custFile)
        {
            try
            {
                using (SqlConnection sqlConnection = new SqlConnection(sqlConnectionString))
                {
                    sqlConnection.Open();
                    string deleteLegDocQuery = "DELETE FROM LegalDocument WHERE LegalDocumentID = @legalDocId;";

                    using (SqlCommand sqlCommand = new SqlCommand(deleteLegDocQuery, sqlConnection))
                    {
                        sqlCommand.Parameters.Add("@legalDocId", SqlDbType.UniqueIdentifier).Value = custFile.Id;
                        sqlCommand.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
            }

            return(true);
        }
        public void Write_WithOneCustomer_GeneratesCorrectOutput()
        {
            // Arrange
            Address address = new Address("1 High Street", "Flat 123", "Business Park", "Newtown", "Nr Oldtown", "Testshire", "AA1 1AA");
            Customer customer = new Customer("WEE0001", "Test customer", address);

            CustomerFile file = new CustomerFile("WEE", 0);

            file.AddCustomer(customer);

            // Act
            string result = file.Write();

            // Assert
            string expectedDate = DateTime.UtcNow.Date.ToString("dd-MMM-yyyy").ToUpperInvariant();
            string expectedOutput =
                "\"H\",\"0000000\",\"WEE\",\"H\",\"C\",\"00000\",\"" + expectedDate + "\"" + Environment.NewLine +
                "\"D\",\"0000001\",\"WEE0001\",\"Test customer\",\"1 High Street\",\"Flat 123\",\"Business Park\",\"Newtown\",\"Nr Oldtown\",\"Testshire\",\"AA1 1AA\"" + Environment.NewLine +
                "\"T\",\"0000002\",\"0000003\"" + Environment.NewLine;

            Assert.Equal(expectedOutput, result);
        }
Ejemplo n.º 31
0
        internal static async Task <bool> DeleteFile(string id)
        {
            CustomerFile custFile = new CustomerFile();

            custFile.Id = new Guid(id);
            //custFile.DocumentType = docType;
            //custFile.CaseId = caseId;
            var json       = JsonConvert.SerializeObject(custFile);
            var strContent = new StringContent(json, Encoding.UTF8, "application/json");

            var content = new MultipartContent();

            content.Add(strContent);

            HttpResponseMessage response = await SendApiRequest("api/Upload/DeleteFile", content);

            if (response.IsSuccessStatusCode)
            {
                return(true);
            }
            return(false);
        }
Ejemplo n.º 32
0
        public ActionResult Create(Customer customer)
        {
            try
            {
                if (customer.UploadFiles != null && customer.UploadFiles[0] != null)
                {
                    var customerFiles = new List <CustomerFile>();
                    foreach (var uploadFile in customer.UploadFiles)
                    {
                        var customerFile = new CustomerFile();
                        var fileByte     = new byte[uploadFile.ContentLength];
                        uploadFile.InputStream.Read(fileByte, 0, uploadFile.ContentLength);
                        customerFile.File     = fileByte;
                        customerFile.FileName = uploadFile.FileName;

                        customerFiles.Add(customerFile);
                    }

                    customer.CustomerFiles = customerFiles;
                }
                var isSaved = _customerManager.Save(customer);

                if (isSaved)
                {
                    ViewBag.SMsg = "Saved Successful";
                }
                else
                {
                    ViewBag.FMsg = "Save Failed";
                }
            }
            catch (Exception e)
            {
                ViewBag.FMsg = e.Message;
            }

            return(RedirectToAction("ShowCustomers"));
        }
Ejemplo n.º 33
0
    } // End of the constructor

    #endregion

    #region Insert methods

    /// <summary>
    /// Add one customer file post
    /// </summary>
    /// <param name="post">A reference to a customer file post</param>
    public static void Add(CustomerFile post)
    {
        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "INSERT INTO dbo.customers_files (customer_id, product_id, language_id, order_date) "
            + "VALUES (@customer_id, @product_id, @language_id, @order_date);";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@customer_id", post.customer_id);
                cmd.Parameters.AddWithValue("@product_id", post.product_id);
                cmd.Parameters.AddWithValue("@language_id", post.language_id);
                cmd.Parameters.AddWithValue("@order_date", post.order_date);

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases
                try
                {
                    // Open the connection
                    cn.Open();

                    // Execute the insert
                    cmd.ExecuteNonQuery();

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

    } // End of the Add method
Ejemplo n.º 34
0
        public static CustomerFile GetLegalDocumentData(Guid fileId)
        {
            string GetQuery = "Select * from LegalDocument ld inner join customer c on ld.CustomerId = c.CustomerId where LegalDocumentID='" + fileId.ToString() + "'";

            //List<Customer> customerList = new List<Customer>();
            CustomerFile customer = null;

            using (SqlConnection connection = new SqlConnection(sqlConnectionString))
            {
                SqlCommand command = new SqlCommand(GetQuery, connection);
                command.Connection.Open();
                SqlDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    customer              = new CustomerFile();
                    customer.Id           = fileId;
                    customer.CaseId       = reader["CaseId"].ToString();
                    customer.DocumentType = reader["DocumentType"].ToString();
                }
            }

            return(customer);
        }
        public async Task CreateFileData_WithErrorGeneratingCustomerFile_TranslatesError()
        {
            // Arrange
            ulong fileID = 123;

            var customerFile = new CustomerFile("WEE", fileID);
            var error = new Exception();
            var customerFileGeneratorResult = new IbisFileGeneratorResult<CustomerFile>(customerFile, new List<Exception> { error });

            var customerFileGenerator = A.Fake<IIbisCustomerFileGenerator>();
            A.CallTo(() => customerFileGenerator.CreateAsync(A<ulong>._, A<InvoiceRun>._))
                .Returns(customerFileGeneratorResult);

            var transactionFile = new TransactionFile("WEE", (ulong)12345);
            var transactionFileGeneratorResult = new IbisFileGeneratorResult<TransactionFile>(transactionFile, A.Dummy<List<Exception>>());

            var transactionFileGenerator = A.Fake<IIbisTransactionFileGenerator>();
            A.CallTo(() => transactionFileGenerator.CreateAsync(A<ulong>._, A<InvoiceRun>._))
                .Returns(transactionFileGeneratorResult);

            var errorTranslator = A.Fake<IIbisFileDataErrorTranslator>();

            IbisFileDataGenerator generator = new IbisFileDataGenerator(
                customerFileGenerator,
                transactionFileGenerator,
                errorTranslator);

            // Act
            await generator.CreateFileDataAsync(fileID, A.Dummy<InvoiceRun>());

            // Assert
            A.CallTo(() => errorTranslator.MakeFriendlyErrorMessages(A<List<Exception>>._))
                .MustHaveHappened();
        }