Archive

Category Archives for "Development"

Saving Image To Database Using MVC

Saving an image to a database is not hard to do as you might think. I developed a sample Asp.net MVC application demonstrating this. You may get the complete code from my github.

Below is the Model I have. The important thing here is byte[] which is the one that is saved in the database while the HttpPostedFileBase is the data posted from the View.

[Table("Car")]
public class Car
{
  [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)
      , Key()]
  public int CarId { get; set; }

  [Required]
  [StringLength(100)]
  public string Name { get; set; }

  //[Required]
  [StringLength(100)]
  public string Type { get; set; }

  public byte[] ImageFile { get; set; }

  [StringLength(200)]
  public string ImageContentType { get; set; }

  [StringLength(200)]
  public string ImageFileName { get; set; }

  List<Maintenance> MaintenanceSchedule { get; set; }

  [NotMapped]
  [Required]
  public HttpPostedFileBase FileAttach { get; set; }

}

This is the View control code in its simple form. You can see the complete code of the control from this link.

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = 
       "multipart/form-data" }))
{
    <div class="form-group">
        @Html.LabelFor(model => model.ImageFile, htmlAttributes: 
          new { @class = "control-label col-md-2" })
            <div class="col-md-10">
        @Html.TextBoxFor(m => m.FileAttach, new { type = "file", 
           accept = "image/jpeg,image/jpg,image/png", 
           placeholder = Html.DisplayNameFor(m => m.FileAttach), 
           @class = "form-control" })
        @Html.ValidationMessageFor(model => model.FileAttach, "", 
           new {@class = "text-danger" })
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
           <input type="submit" value="Create" 
                 class="btn btn-default" />
            </div>
        </div>
    </div>
}

Here is the code in the Controller to save in the database using Entity Framework.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = 
      "CarId,Name,Type,ImageFile,FileAttach")] Car car)
{   
    UpdateFileDetails(car);
    if (ModelState.IsValid)
    {
        db.Car.Add(car);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(car);
}

private void UpdateFileDetails(Car car)
{
    HttpPostedFileBase postedFile = car.FileAttach;
    if (postedFile != null)
    {
         byte[] bytes;
         using (BinaryReader br = new BinaryReader
                (postedFile.InputStream))
         {
                bytes = br.ReadBytes(postedFile.ContentLength);
         }

         car.ImageFileName = Path.GetFileName(postedFile.FileName);
         car.ImageContentType = postedFile.ContentType;
         car.ImageFile = bytes;
     }
}

As you can see from the code above, with a few lines of code, you will be able to save an image to a database. Hope this helps anyone who is looking to implement this in their project!

Encrypting PDF with a Password

If you are developer and looking for a way to put a password on a PDF file for free, you may want to look into qpdf command line tool. You can install this in Linux and Windows as well.

I develop using c# and was able to utilize this tool inside the program that I was doing. You can actually use this in any kind of programming language by just calling it through a command line interface.

Please see code snippet below.

public static string qpdfEncrypt(string inFile, string outFile, 
     string password)
{
     using (System.Diagnostics.Process pProcess = new 
        System.Diagnostics.Process())
     {
        pProcess.StartInfo.FileName = 
           System.AppDomain.CurrentDomain.BaseDirectory 
           + @"\\qpdf\\qpdf.exe";
        pProcess.StartInfo.Arguments = $"--encrypt {password} 
           {password} 256 -- \"{inFile}\" \"{outFile}\"";
        pProcess.StartInfo.UseShellExecute = false;
        pProcess.StartInfo.RedirectStandardOutput = true;
        pProcess.StartInfo.RedirectStandardError = true;
        pProcess.StartInfo.WindowStyle = 
            System.Diagnostics.ProcessWindowStyle.Normal;
        pProcess.StartInfo.CreateNoWindow = true;
        pProcess.Start();
        string output = pProcess.StandardError.ReadToEnd();
        pProcess.WaitForExit();
        return output;
      }
}

As you can see, the code just opens the process command interface and calls the qpdf executable. You can actually use the same code in calling any kind of command line utility that you want to integrate in your code.

Happy Coding!