How to save image to the database after it is scanned - c#-4.0

I have developed a windows application to scan images.After the image is scanned i want to save it directly to the database not in local machine...The code which i have used is as follows
try
{
String str = string.Empty;
WIA.CommonDialogClass scanner;
ImageFile imageObject;
scanner = new CommonDialogClass();
imageObject = scanner.ShowAcquireImage
(WiaDeviceType.ScannerDeviceType,
WiaImageIntent.ColorIntent,
WiaImageBias.MinimizeSize,
ImageFormat.Jpeg.Guid.ToString("B"),
false,
true,
true);
str = DateTime.Now.ToString();
str = str.Replace("/", "");
str = str.Replace(":", "");
Directory.CreateDirectory("D:\\scanned1");
// MessageBox.Show(string.Format("File Extension = {0}\n
//\nFormat = {1}", imageObject.FileExtension, imageObject.FormatID));
imageObject.SaveFile(#"D:\scanned1\lel" + str + ".jpg");
MessageBox.Show("Scanning Done");
}
catch (Exception ex)
{
MessageBox.Show("Please check if the scanner is connected properly.");
}
Instead of saving it to D drive i want to save it to database.....How can i do it?Plz reply...

I've got no idea what "ImageFile" is really, but there should be a way to transform it into the byte array (byte[]). Afterwards you would need to insert that array to varbinary field in your sql.
something like this:
using(SqlCommand cmd = new SqlCommand("INSERT INTO MyTable (myvarbinarycolumn) VALUES (#myvarbinaryvalue)", conn))
{
cmd.Parameters.Add("#myvarbinaryvalue", SqlDbType.VarBinary, myarray.length).Value = myarray;
cmd.ExecuteNonQuery();
}
ofc sqlcommand should be opened and valid.
myarray is of type byte[]

Related

OpenXml Cannot Read or Write To Azure Blob Storage with FileMode or FileAccess value is invalid for the stream

We are working with DocumentFormat.OpenXml.WordDocument and opening a template of a Wordfile inside the Azure Blob, writing to it and saving it. There are two issues:
During the opening of the Document
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(streamToWrite, true))
Here the issue is like this ->
DocumentFormat.OpenXml.Packaging.OpenXmlPackageException: 'The stream was not opened for writing.'
If I replaces the IsEditable=trueto false, the issue will go. But the another issue occurs subsequently during the reading of the stream, after the changing the texts.
// Writing the changed document using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.OpenOrCreate)))
The Error is like this-> System.ArgumentException: 'Stream was not writable.'
Final Code is like this, which is referred from this link : -https://learn.microsoft.com/en-us/office/open-xml/how-to-search-and-replace-text-in-a-document-part
public async Task<IActionResult> UpdateDocumentAsync([FromBody] ProcessingQuery query)
{
BlobClient readblob = new BlobClient(new Uri("https://XXXXXX/docxviewer/outputviewer/blob.docx?sp=racwd"));
using (HttpClient client = new HttpClient())
{
using (Stream streamToWrite = await client.GetStreamAsync(readblob.Uri))
{
try
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(streamToWrite, false))
{
string docText = null;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
//Writing of Single Queries this will become dictionary key-value pair
Regex regexText1 = new Regex("{first_name}");
docText = regexText1.Replace(docText, query?.first_Name);
Regex regexText2 = new Regex("{last_name}");
docText = regexText2.Replace(docText, query?.last_Name);
Regex regexText3 = new Regex("{phone}");
docText = regexText2.Replace(docText, query?.phone);
// Writing the changed document
using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.OpenOrCreate)))
{
sw.Write(docText);
sw.Flush();
sw.Close();
}
wordDoc.Close();
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
streamToWrite.Close();
}
}
return Ok(readblob);
}
Please help us on this codes with relevant codes and documents. If there is any issue in blob storage token Kindly help us in that too.. :)

Input output stream not working in Web Forms function

Can someone tell me why I keep getting a read and write timeout on this function? I have this as a code behind function on click even from a button. Everything as far as the data looks good until I get to the stream section and it still steps through, but when I check the Stream object contents after stepping into that object it states Read Timeout/Write Timeout: System invalid Operation Exception.
protected void SubmitToDB_Click(object sender, EventArgs e)
{
if (FileUploader.HasFile)
{
try
{
if (SectionDropDownList.SelectedValue != null)
{
if (TemplateDropDownList.SelectedValue != null)
{
// This gets the full file path on the client's machine ie: c:\test\myfile.txt
string strFilePath = FileUploader.PostedFile.FileName;
//use the System.IO Path.GetFileName method to get specifics about the file without needing to parse the path as a string
string strFileName = Path.GetFileName(strFilePath);
Int32 intFileSize = FileUploader.PostedFile.ContentLength;
string strContentType = FileUploader.PostedFile.ContentType;
//Convert the uploaded file to a byte stream to save to your database. This could be a database table field of type Image in SQL Server
Stream strmStream = FileUploader.PostedFile.InputStream;
Int32 intFileLength = (Int32)strmStream.Length;
byte[] bytUpfile = new byte[intFileLength + 1];
strmStream.Read(bytUpfile, 0, intFileLength);
strmStream.Close();
saveFileToDb(strFileName, intFileSize, strContentType, bytUpfile); // or use FileUploader.SaveAs(Server.MapPath(".") + "filename") to save to the server's filesystem.
lblUploadResult.Text = "Upload Success. File was uploaded and saved to the database.";
}
}
}
catch (Exception err)
{
lblUploadResult.Text = "The file was not updloaded because the following error happened: " + err.ToString();
}
}
else
{
lblUploadResult.Text = "No File Uploaded because none was selected.";
}
}
Try something like this:
using (var fileStream = FileUploader.PostedFile.InputStream)
{
using (var reader = new BinaryReader(fileStream))
{
byte[] bytUpfile = reader.ReadBytes((Int32)fileStream.Length);
// SAVE TO DB...
}
}

Export Rich Text to plain text c#

Good day to Stackoverflow community,
I am in need of some expert assistance. I have an MVC4 web app that has a few rich text box fields powered by TinyMCE. Up until now the system is working great. Last week my client informed me that they want to export the data stored in Microsoft SQL to Excel to run custom reports.
I am able to export the data to excel with the code supplied. However it is exporting the data in RTF rather than Plain text. This is causing issues when they try to read the content.
Due to lack of knowledge and or understanding I am unable to figure this out. I did read that it is possible to use regex to do this however I have no idea how to implement this. So I turn to you for assistance.
public ActionResult ExportReferralData()
{
GridView gv = new GridView();
gv.DataSource = db.Referrals.ToList();
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=UnderwritingReferrals.xls");
Response.ContentType = "application/ms-excel";
Response.AddHeader("Content-Type", "application/vnd.ms-excel");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return RedirectToAction("Index");
}
I would really appreciate any assistance. and thank you in advance.
I have looked for solutions on YouTube and web forums with out any success.
Kind Regards
Francois Muller
One option you can perform is to massage the Data you write to the XML file.
For example, idenfity in your string and replace it with string.Empty.
Similarly can be replaced with string.Empty.
Once you have identified all the variants of the Rich Text HTML tags, you can just create a list of the Tags, and inside a for FOR loop replace each of them with a suitable string.
Did you try saving the file as .xslx and sending over to the client.
The newer Excel format might handle the data more gracefully?
Add this function to your code, and then you can invoke the function passing it in the HTML string. The return output will be HTML free.
Warning: This does not work for all cases and should not be used to process untrusted user input. Please test it with variants of your input string.
public static string StripTagsCharArray(string source)
{
char[] array = new char[source.Length];
int arrayIndex = 0;
bool inside = false;
for (int i = 0; i < source.Length; i++)
{
char let = source[i];
if (let == '<')
{ inside = true; continue; }
if (let == '>') { inside = false; continue; }
if (!inside) { array[arrayIndex] = let; arrayIndex++; }
}
return new string(array, 0, arrayIndex);
}
So I managed to resolve this issue by changing the original code as follow:
As I'm only trying to convert a few columns, I found this to be working well. This will ensure each records is separated by row in Excel and converts the Html to plain text allowing users to add column filters in Excel.
I hope this helps any one else that has a similar issue.
GridView gv = new GridView();
var From = RExportFrom;
var To = RExportTo;
if (RExportFrom == null || RExportTo == null)
{
/* The actual code to be used */
gv.DataSource = db.Referrals.OrderBy(m =>m.Date_Logged).ToList();
}
else
{
gv.DataSource = db.Referrals.Where(m => m.Date_Logged >= From && m.Date_Logged <= To).OrderBy(m => m.Date_Logged).ToList();
}
gv.DataBind();
foreach (GridViewRow row in gv.Rows)
{
if (row.Cells[20].Text.Contains("<"))
{
row.Cells[20].Text = Regex.Replace(row.Cells[20].Text, "<(?<tag>.+?)(>|>)", " ");
}
if (row.Cells[21].Text.Contains("<"))
{
row.Cells[21].Text = Regex.Replace(row.Cells[21].Text, "<(?<tag>.+?)(>|>)", " ");
}
if (row.Cells[22].Text.Contains("<"))
{
row.Cells[22].Text = Regex.Replace(row.Cells[22].Text, "<(?<tag>.+?)(>|>)", " ");
}
if (row.Cells[37].Text.Contains("<"))
{
row.Cells[37].Text = Regex.Replace(row.Cells[37].Text, "<(?<tag>.+?)(>|>)", " ");
}
if (row.Cells[50].Text.Contains("<"))
{
row.Cells[50].Text = Regex.Replace(row.Cells[37].Text, "<(?<tag>.+?)(>|>)", " ");
}
}
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=Referrals " + DateTime.Now.ToString("dd/MM/yyyy") + ".xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("Content-Type", "application/vnd.ms-excel");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
//This code will export the data to Excel and remove all HTML Tags to pass everything into Plain text.
//I am using HttpUtility.HtmlDecode twice as the first instance changes null values to "Â" the second time it will run the replace code.
//I am using Regex.Replace to change the headings to more understandable headings rather than the headings produced by the Model.
Response.Write(HttpUtility.HtmlDecode(sw.ToString())
.Replace("Cover_Details", "Referral Detail")
.Replace("Id", "Identity Number")
.Replace("Unique_Ref", "Reference Number")
.Replace("Date_Logged", "Date Logged")
.Replace("Logged_By", "File Number")
.Replace("Date_Referral", "Date of Referral")
.Replace("Referred_By", "Name of Referrer")
.Replace("UWRules", "Underwriting Rules")
.Replace("Referred_To", "Name of Referrer")
);
Response.Flush();
Response.End();
TempData["success"] = "Data successfully exported!";
return RedirectToAction("Index");
}

how to get values from SqlDataReader to forloop execution?

Here I coding for get each and every StudyUID(as string) from database to SqlDataReader,but i need to know how the reader value call to forloop execution.
Get to read each and every StudyUID for execution.Here is the code :.
public void automaticreport()
{
//string autsdyid="";
SqlConnection con = new SqlConnection(constr);
con.Open();
string autoquery = "Select StudyUID From StudyTable Where status='2'";
SqlCommand cmd = new SqlCommand(autoquery, con);
SqlDataReader rdr = cmd.ExecuteReader();
for()
{
//how to call each StudyUId from database through for loop
if (!this.reportchk)
{
Reportnew cf = new Reportnew();
ThreadPool.QueueUserWorkItem((WaitCallback)(o => cf.ReportRetrive(this, autsdyid, true)));
}
else
{
int num = (int)System.Windows.Forms.MessageBox.Show("Reports checking in progress, Please wait sometime and try again later", "OPTICS", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
con.Close();
}
Like #R.T and others have mentioned you can use the Read method on the data reader. Looking at your sample code you might want to refactor it slightly to meet more of the SOLID principles and make sure you're not leaking database connections
Here's an example of code that has been refactored a bit.
public void automaticreport()
{
foreach (var autsdyid in LoadStudyIdentifiers())
{
if (!this.reportchk)
{
Reportnew cf = new Reportnew();
ThreadPool.QueueUserWorkItem((WaitCallback)(o => cf.ReportRetrive(this, autsdyid, true)));
}
else
{
int num = (int)System.Windows.Forms.MessageBox.Show("Reports checking in progress, Please wait sometime and try again later", "OPTICS", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
}
private string[] LoadStudyIdentifiers()
{
var results = new List<string>();
// adding a using statement will close the database connection if there are any errors
// avoiding consuming the database connection pool
using (var con = new SqlConnection(constr))
{
conn.Open();
var autoquery = "Select StudyUID From StudyTable Where status='2'";
using (var cmd = new SqlCommand(autoquery, con))
{
SqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
results.Add(rdr.GetString(rdr.GetOrdinal("StudyUID")));
}
}
}
return results.ToArray();
}
Note: I wrote this in notepad so there is no guarantee it will compile but should give an indication as to how you could refactor your code.
if (rdr.HasRows)
{
while (rdr.Read())
{
Console.WriteLine(rdr.getString("columnName"));
}
}
You can use something like:
while (reader.Read())
{
string value = reader.getString("columnName");
}
You may use the while loop like this:
while (rdr.Read())
{
string s = rdr.GetString(rdr.GetOrdinal("Column"));
//Apply logic to retrieve here
}

EntityDataReader to ToList()

my code :
public List<Book> GetBook(string Field, object Value)
{
using (EntityConnection conn = new EntityConnection("name=Entities"))
{
conn.Open();
// Create an EntityCommand.
using (EntityCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "Select VALUE b FROM Entities.Book as b where Cast(b." + Field + " as Edm.String) like '%" + Value.ToString() + "%'";
// Execute the command.
using (EntityDataReader rdr =
cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
conn.Close();
var s = from d in rdr.OfType<Book>().AsEnumerable()
select d;
return (s.ToList());
}
}
}
return (null);
}
why The result is always empty???
What is the correct code?
Why are you closing connection before you started to read from the reader? Reader is like cursor - it doesn't buffer all results to memory when you open it but it loads them incrementally so you could easily terminate connection (and reading functionality as well) before you read any result. You don't have to close the connection explicitly - that is responsibility of using block.
You can also use SQL profiler to validate the it really builds the query you expect.
using (EntityConnection conn = new EntityConnection("name=Entities"))
{
conn.Open();
// Create an EntityCommand.
using (EntityCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "Select VALUE b FROM Entities.Book as b where Cast(b." + Field + " as Edm.String) like '%" + Value.ToString() + "%'";
// Execute the command.
using (EntityDataReader rdr =
cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
var s = from d in rdr.OfType<Book>().AsEnumerable()
select d;
return (s.ToList());
}
}
}
s.ToList().Count returns 0 because rdr.OfType<Book> is always empty collection. EntitDataReader doesn't materialize entities - it is just wrapper about database related DataReader and it works in the same way. You must read columns and fill them to properties of your entity.
If you don't want to do it you can use objectContext.Translate method but once you start to work with ObjectContext you don't need EntityCommand and EntityDataReader at all.

Resources