Insert signature data into SQL Server in MVC 2 C# - c#

I have working code that uses signature pad data to create and save a signature bmp image to a file location. My question is: how can I modify this code to insert the image into a SQL Server 2008 image field?
The following from my Controller obtains signature data from a signature tablet and creates a bmp image and saves it to a file location.
[PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
public ActionResult SaveSignature2(IPrincipal principal) {
int userId = ((ScoutIdentity)principal.Identity).UserId.Value;
//Put user code to initialize the page here
SIGPLUSLib.SigPlus sigObj = new SIGPLUSLib.SigPlus();
sigObj.InitSigPlus();
sigObj.AutoKeyStart();
string visitorname = Request.Form["visitorname"];
visitorname = visitorname.Replace(" ", ""); //combines the first name with last name with no spaces
visitorname = visitorname.Trim();
string thevrvIDstr = Request.Form["vrvID"];
int thevrvID = Convert.ToInt32(thevrvIDstr);
//use the same data to decrypt signature
sigObj.AutoKeyData = Request.Form["SigText"];
sigObj.AutoKeyFinish();
sigObj.SigCompressionMode = 1;
sigObj.EncryptionMode = 2;
//Now, get sigstring from client
//Sigstring can be stored in a database if
//a biometric signature is desired rather than an image
sigObj.SigString = Request.Form["hidden"];
if (sigObj.NumberOfTabletPoints() > 0) {
sigObj.ImageFileFormat = 0;
sigObj.ImageXSize = 500;
sigObj.ImageYSize = 150;
sigObj.ImagePenWidth = 8;
sigObj.SetAntiAliasParameters(1, 600, 700);
sigObj.JustifyX = 5;
sigObj.JustifyY = 5;
sigObj.JustifyMode = 5;
long size;
byte[] byteValue;
sigObj.BitMapBufferWrite();
size = sigObj.BitMapBufferSize();
byteValue = new byte[size];
byteValue = (byte[])sigObj.GetBitmapBufferBytes();
sigObj.BitMapBufferClose();
System.IO.MemoryStream ms = new System.IO.MemoryStream(byteValue);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
String path;
path = System.AppDomain.CurrentDomain.BaseDirectory;
path = path + "/uploadFiles/Signatures/"+thevrvIDstr+".bmp";
img.Save(path, System.Drawing.Imaging.ImageFormat.Bmp);
ViewData["Result"] = ("Image saved successfully to " + path);
}
else {
ViewData["Result"] = "signature has not been returned successfully!";
}
ViewData["Result"] = sigObj.SigString;
//return RedirectToAction("vrSignIn");
return View();
}
I also have code elsewhere in my controller that gets an uploaded file and inserts it into the database. This code works OK.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadTempFiles(string id, string u)
{
//this method temporarily stores files
string userIdString = Cryptographer.DecryptSymmetric("RijndaelManaged", SecurityImpl.UrlToBase64(u));
int userId = Convert.ToInt32(userIdString);
if (Request.Files.Count > 0)
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase file = Request.Files[i];
int contentlength = file.ContentLength;
byte[] b = new byte[contentlength];
Stream s;
s = file.InputStream;
s.Read(b, 0, contentlength);
VisitRequest.AddVisitorSignature(userId, b);
}
}
return View("UploadFiles");
}
I'm thinking that I can use some part of the second code to interrupt the image creation process in the first code and insert the image into the database INSTEAD of saving the image to a file location. I don't know how to do that.

I had same problem, and I solved it:
Comment these three lines:
//path = System.AppDomain.CurrentDomain.BaseDirectory;
//path = path + "/uploadFiles/Signatures/"+thevrvIDstr+".bmp";
//img.Save(path, System.Drawing.Imaging.ImageFormat.Bmp);
Convert image to String data (assumed that your variable 'strSignature' was declared before):
strSignature = img.ToString();
Save it with your Stored Procedure.
Hope this help you!

Related

Excel sheet in Microsoft excel interop. Save an image to a file

I have installed EPPlus in my c# project and used it to locate the proper image in an Excel worksheet. I want to take the image now and save it as a PNG file.
FileInfo fi = new FileInfo(#"c:/folder/workbook.xlsx");
using (ExcelPackage excelPackage = new ExcelPackage(fi))
{
ExcelWorksheet ws = excelPackage.Workbook.Worksheets[0];
int imageCount = firstWorksheet.Drawings.Count;
for (int i = 0; i <= imageCount-1; i++)
{
if (firstWorksheet.Drawings[i].DrawingType.ToString().ToLower() == "picture")
{
save it to a file;
}
}
}
Here is what I did that works great. Of course this is a little abbreviated.
OfficeOpenXml.Drawing.ExcelDrawing image = firstWorksheet.Drawings[i];
OfficeOpenXml.Drawing.ExcelPicture p = (OfficeOpenXml.Drawing.ExcelPicture)image;
p.Image.Save(#"c:/autocell/becbec.png");
This works with embedded xml files / tables. I also pasted in jpegs and pngs and bitmaps and this code found and saved them just fine too.
You can give the export URL and then it will be shown in the excel file
Get Absolute URL function
private string GetAbsoluteUrl(string relativeUrl)
{
relativeUrl = relativeUrl.Replace("~/", string.Empty);
string[] splits = Request.Url.AbsoluteUri.Split('/');
if (splits.Length >= 2)
{
string url = splits[0] + "//";
for (int i = 2; i < splits.Length - 1; i++)
{
url += splits[i];
url += "/";
}
return url + relativeUrl;
}
return relativeUrl;
}
and save it like this
//Convert the Relative Url to Absolute Url and set it to Image control.
Image1.ImageUrl = this.GetAbsoluteUrl(Image1.ImageUrl);
FileInfo fi = new FileInfo(#"c:/folder/workbook.xlsx");
using (ExcelPackage excelPackage = new ExcelPackage(fi))
{
ExcelWorksheet ws = excelPackage.Workbook.Worksheets[0];
int imageCount = firstWorksheet.Drawings.Count;
for (int i = 0; i <= imageCount-1; i++)
{
if (firstWorksheet.Drawings[i].DrawingType.ToString().ToLower() ==
"picture")
{
// save it to a file;
OfficeOpenXml.Drawing.ExcelDrawing image = firstWorksheet.Drawings[i];
OfficeOpenXml.Drawing.ExcelPicture p =
(OfficeOpenXml.Drawing.ExcelPicture)image;
p.Image.Save(#"c:/autocell/becbec.png");
}
}
}

How to scan two-sided (Duplex?) using WIA - C#

I'm writing a C # method that scans a lot of documents, but I need to scan these documents two-sided, ie for each sheet, scan the front and back of the document using the scanner's ADF. But I've tried all the ways I found on the internet and I could not. My code is below:
//user select the scanner
int indexScanner = Convert.ToInt32(Console.ReadLine());
// Connect to the first available scanner
var device = deviceManager.DeviceInfos[indexScanner - 1].Connect();
// Select the scanner
var scannerItem = device.Items[1];
int resolution = 150;
int width_pixel = 1250;
int height_pixel = 1700;
int color_mode = 1;
int adf_mode = 1;
int pages_mode = 1;
device.Properties["3096"].set_Value(pages_mode);
//device.Properties["3088"].set_Value(adf_mode);
scannerItem.Properties["3088"].set_Value(adf_mode);
AdjustScannerSettings(scannerItem, resolution, 0, 0, width_pixel, height_pixel, 0, 0, color_mode);
CommonDialogClass dlg = new CommonDialogClass();
object scanResult = dlg.ShowTransfer(scannerItem, FormatID.wiaFormatJPEG, true);
if (scanResult != null)
{
ImageFile image = (ImageFile)scanResult;
string filename = "scan.jpeg";
if (File.Exists(filename))
File.Delete(filename);
image.SaveFile(filename);
}
scanResult = dlg.ShowTransfer(scannerItem, FormatID.wiaFormatJPEG, true);
if (scanResult != null)
{
ImageFile image = (ImageFile)scanResult;
string filename = "scan1.jpeg";
if (File.Exists(filename))
File.Delete(filename);
image.SaveFile(filename);
}

How to read .DAT files in a folder one by one

I'm creating a software to get the data from .dat file and write those data in database. There are so many .dat files so I need to do a batch process. I'm currently reading one dat file by using this code
UDisk udisk = new UDisk();
byte[] byDataBuf = null;
int iLength;//length of the bytes to get from the data
string sPIN2 = "";
string sVerified = "";
string sTime_second = "";
string sDeviceID = "";
string sStatus = "";
string sWorkcode = "";
openFileDialog1.Filter = "1_attlog(*.dat)|*.dat";
openFileDialog1.FileName = "1_attlog.dat";//1 stands for one possible deviceid
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
FileStream stream = new FileStream(openFileDialog1.FileName, FileMode.OpenOrCreate, FileAccess.Read);
byDataBuf = File.ReadAllBytes(openFileDialog1.FileName);
iLength = Convert.ToInt32(stream.Length);
lvSSRAttLog.Items.Clear();
int iStartIndex = 0;
int iOneLogLength;//the length of one line of attendence log
for (int i = iStartIndex; i < iLength - 2; i++)//modify by darcy on Dec.4 2009
{
if (byDataBuf[i] == 13 && byDataBuf[i + 1] == 10)
{
iOneLogLength = (i + 1) + 1 - iStartIndex;
byte[] bySSRAttLog = new byte[iOneLogLength];
Array.Copy(byDataBuf, iStartIndex, bySSRAttLog, 0, iOneLogLength);
udisk.GetAttLogFromDat(bySSRAttLog, iOneLogLength, out sPIN2, out sTime_second, out sDeviceID, out sStatus, out sVerified, out sWorkcode);
ListViewItem list = new ListViewItem();
list.Text = sPIN2;
list.SubItems.Add(sTime_second);
list.SubItems.Add(sDeviceID);
list.SubItems.Add(sStatus);
list.SubItems.Add(sVerified);
list.SubItems.Add(sWorkcode);
lvSSRAttLog.Items.Add(list);
bySSRAttLog = null;
iStartIndex += iOneLogLength;
iOneLogLength = 0;
}
}
stream.Close();
}
How can I read files one by one and transfer those data into database.
My database is - SMS
table is -
CHECKINOUT
columns -CHECKDate datetime
CHECKTime datetime
InOutMode int
Status varchar(50)
WorkCode varchar(50)
Memoinfo varchar(50)
sn int
sn2 int
Ip varchar(16)
Updated int
Given a folder path, you can use Directory.EnumerateFiles to get .dat files one by one:
string folder = #"D:\your\Folder";
foreach(var file in Directory.EnumerateFiles(
folder, // folder path
"*.dat" // file type you want
/*, SearchOption.AllDirectories*/)) // uncomment it if you want open files in subfolder
{
FileStream stream = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Read);
byDataBuf = File.ReadAllBytes(openFileDialog1.FileName);
iLength = Convert.ToInt32(stream.Length);
// Do your stuff here
stream.Close();
}

OutOfMemoryException error in Loop

I am trying to create a Windows app which uploads files to FTP. Essentially, it looks for .jpeg files in a given folder, it reads through the barcodes found in the .jpg files before uploading it into the FTP server, and entering the URL into the database for our records.
As there will be multiple files at any given time in the folder, I am essentially trying to read them in a loop, and process them accordingly. However, I get an OutOfMemoryException whenever the loop starts again. I am trying to figure out what I'm doing wrong here. I have appended my code below:
private void btnProcess_Click(object sender, RoutedEventArgs e)
{
podPath = Directory.GetFiles(DestPath, "*.jpg");
List<string> scans = new List<string>(podPath.Length);
List<string> badscans = new List<string>();
byte[] imageBytes;
string filename, result;
POD conpod = new POD();
OTPOD otpod = new OTPOD();
ConsignmentObj scanJob;
//Pickup OTScan;
//Consolidate ccv;
for (int i = 0; i < podPath.Count(); i++ )
{
filename = podPath[i].ToString();
using (Bitmap bm = (Bitmap)Bitmap.FromFile(filename))
{
var results = barcodeReader.Decode(bm);
result = results.ToString();
bm.Dispose();
}
if (result != null)
{
//if barcode can be read, we throw the value into the database to pull out relevant information
if (result.Contains(ConNotePrefix))
{
#region Consignments
scanJob = getCon(result.ToString());
final = ImageFolder + "\\" + result.ToString() + ".jpg";
using (System.Drawing.Image img = System.Drawing.Image.FromFile(filename))
{
MemoryStream ms = new MemoryStream();
try
{
img.Save(ms, ImageFormat.Jpeg);
imageBytes = ms.ToArray();
img.Dispose();
}
finally
{
ms.Flush();
ms.Close();
ms.Dispose();
}
}
lock (filename)
{
if (System.IO.File.Exists(filename))
{
File.Delete(filename);
}
}
using (var stream = File.Create(final)) { }
File.WriteAllBytes(final, imageBytes);
File.Delete(filename);
conpod.ConsignmentID = scanJob.ConsignmentID;
conpod.UserID = 1;
conpod.Location = ftpUrl + "//" + result.ToString() + ".jpg";
conpod.rowguid = Guid.NewGuid();
UploadFilesToFtp(ftpUrl, ftpUser, ftpPass, final, result.ToString() + ".jpg");
insertPOD(conpod);
scans.Add(result.ToString());
#endregion
}
}
else
{
badscans.Add(filename);
}
}
this.lbScans.ItemsSource = scans;
this.lbBadScans.ItemsSource = badscans;
}
The FTP method, UploadFilesToFtp(x, x, x, x, x, x) is not a problem here. All feedback will be much appreciated.
An OutOfMemoryException can also be thrown by the method FromFile of the Image class when
The file does not have a valid image format.
or
GDI+ does not support the pixel format of the file.
So i think there is a problem with one of your image files you are reading. One solution is to catch the OutOfMemoryException and adding the file to the badscans.
try{
using (Bitmap bm = (Bitmap)Bitmap.FromFile(filename)) {
var results = barcodeReader.Decode(bm);
result = results.ToString();
bm.Dispose();
}
}
catch(OutOfMemoryException) {
badscans.add(filename);
}

Read Image file metadata

I want to upload an image file and then extract its basic information (author, dimensions, date created, modified, etc) and display it to the user. How can I do it.
A solution or reference to this problem in asp.net c# code would be helpful. But javascript or php would be ok as well.
Check this Link. You will get more Clearance about GetDetailsOf() and its File Properties based on the Win-OS version wise.
If you want to use C# code use below code to get Metadata's:
List<string> arrHeaders = new List<string>();
Shell shell = new ShellClass();
Folder rFolder = shell.NameSpace(_rootPath);
FolderItem rFiles = rFolder.ParseName(filename);
for (int i = 0; i < short.MaxValue; i++)
{
string value = rFolder.GetDetailsOf(rFiles, i).Trim();
arrHeaders.Add(value);
}
C# solution could be found here:
Link1
Link2
Bitmap image = new Bitmap(fileName);
PropertyItem[] propItems = image.PropertyItems;
foreach (PropertyItem item in propItems)
{
Console.WriteLine("iD: 0x" + item.Id.ToString("x"));
}
MSDN Reference
C# Tutorial Reference
try this...
private string doUpload()
{
// Initialize variables
string sSavePath;
sSavePath = "images/";
// Check file size (mustn’t be 0)
HttpPostedFile myFile = FileUpload1.PostedFile;
int nFileLen = myFile.ContentLength;
if (nFileLen == 0)
{
//**************
//lblOutput.Text = "No file was uploaded.";
return null;
}
// Check file extension (must be JPG)
if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
{
//**************
//lblOutput.Text = "The file must have an extension of JPG";
return null;
}
// Read file into a data stream
byte[] myData = new Byte[nFileLen];
myFile.InputStream.Read(myData, 0, nFileLen);
// Make sure a duplicate file doesn’t exist. If it does, keep on appending an
// incremental numeric until it is unique
string sFilename = System.IO.Path.GetFileName(myFile.FileName);
int file_append = 0;
while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
{
file_append++;
sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
+ file_append.ToString() + ".jpg";
}
// Save the stream to disk
System.IO.FileStream newFile
= new System.IO.FileStream(Server.MapPath(sSavePath + sFilename),
System.IO.FileMode.Create);
newFile.Write(myData, 0, myData.Length);
newFile.Close();
return sFilename;
}

Categories

Resources