I have the code working from Visual Studio. But when I put it onto the IIS it doesn't print the barcode, it just gives me the numbers on the label.
I've tried looking up examples but couldn't find anything. This is my first time using barcodes and printing from IIS. Below is the code I have that currently works on Visual Studio but just prints text when I print from my website hosted on IIS.
protected void grdList_RowCommand(object sender,
GridViewCommandEventArgs e)
{
oDL.UpdateCookieExpiry();
try
{
if (e.CommandName == "View")
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
int id =
Convert.ToInt32(grdList.DataKeys[rowIndex].Values[0]);
string url = "/Stock.aspx?ob_RecordID=" + id;
Response.Redirect(url, false);
Context.ApplicationInstance.CompleteRequest();
}
else if (e.CommandName == "Print")
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
int id =
Convert.ToInt32(grdList.DataKeys[rowIndex].Values[0]);
try
{
outerboxbc o = new outerboxbc();
o = oDL.Get_Outerboxbc(id);
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
this.ob_Barcode.Text = o.barcode.bc_Barcode.ToString();
// Set the printer name.
// pd.PrinterSettings.PrinterName = "\\NS5\hpoffice
pd.PrinterSettings.PrinterName = "ZDesigner GK420d (Copy
1)";
pd.Print();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.ToString());
}
}
}
catch (Exception ex)
{
Console.Write("Error: " + ex.Message);
}
}
void pd_PrintPage(object print, PrintPageEventArgs ev)
{
long de_RecordID = Convert.ToInt32(this.de_RecordID.Value);
cDelivery d = new cDelivery();
d = oDL.get_cDelivery(de_RecordID);
System.Drawing.Image img =
System.Drawing.Image.FromFile(#"C:AlphaLogo.png");
int printHeight = 100;
int printWidth = 250;
int leftMargin = 0;
int rightMargin = 0;
ev.Graphics.DrawImage(img, new Rectangle(leftMargin, rightMargin,
printWidth, printHeight));
Font printFont = new Font("3 of 9 Barcode", 24);
Font printFont1 = new Font("Times New Roman", 14, FontStyle.Bold);
SolidBrush br = new SolidBrush(Color.Black);
ev.Graphics.DrawString("*" + this.ob_Barcode.Text + "*", printFont,
br, 10, 130);
ev.Graphics.DrawString(d.de_ProjectNumber, printFont1, br, 110,
170);
}
So an example of the barcode.text is "AAC12342313". This prints as a barcode when run using Visual Studio but looks like this on the label "AAC12342313" when ran from the website.
Related
I'm exploring Microsoft Cognitive Face API and I'm very new to it. I'm able to achieve Face Attributes with an image which is easy but, my question is how can I get Face Attributes of a person in a real time video feed from Kinect in WPF c#. It would be great if somebody can help me out. Thanks in Advance!
I have tried capturing the frame from the Kinect color feed at every 2 seconds to some file location and use that file path and converted it to a Stream and then pass it on to the Face-API Functions and that worked. Following is the code I tried.
namespace CognitiveFaceAPISample
{
public partial class MainWindow : Window
{
private readonly IFaceServiceClient faceServiceClient = new FaceServiceClient("c2446f84b1eb486ca11e2f5d6e670878");
KinectSensor ks;
ColorFrameReader cfr;
byte[] colorData;
ColorImageFormat format;
WriteableBitmap wbmp;
BitmapSource bmpSource;
int imageSerial;
DispatcherTimer timer,timer2;
string streamF = "Frames//frame.jpg";
public MainWindow()
{
InitializeComponent();
ks = KinectSensor.GetDefault();
ks.Open();
var fd = ks.ColorFrameSource.CreateFrameDescription(ColorImageFormat.Bgra);
uint frameSize = fd.BytesPerPixel * fd.LengthInPixels;
colorData = new byte[frameSize];
format = ColorImageFormat.Bgra;
imageSerial = 0;
cfr = ks.ColorFrameSource.OpenReader();
cfr.FrameArrived += cfr_FrameArrived;
}
void cfr_FrameArrived(object sender, ColorFrameArrivedEventArgs e)
{
if (e.FrameReference == null) return;
using (ColorFrame cf = e.FrameReference.AcquireFrame())
{
if (cf == null) return;
cf.CopyConvertedFrameDataToArray(colorData, format);
var fd = cf.FrameDescription;
// Creating BitmapSource
var bytesPerPixel = (PixelFormats.Bgr32.BitsPerPixel) / 8;
var stride = bytesPerPixel * cf.FrameDescription.Width;
bmpSource = BitmapSource.Create(fd.Width, fd.Height, 96.0, 96.0, PixelFormats.Bgr32, null, colorData, stride);
// WritableBitmap to show on UI
wbmp = new WriteableBitmap(bmpSource);
FacePhoto.Source = wbmp;
}
}
private void SaveImage(BitmapSource image)
{
try
{
FileStream stream = new System.IO.FileStream(#"Frames\frame.jpg", System.IO.FileMode.OpenOrCreate);
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.FlipHorizontal = true;
encoder.FlipVertical = false;
encoder.QualityLevel = 30;
encoder.Frames.Add(BitmapFrame.Create(image));
encoder.Save(stream);
stream.Close();
}
catch (Exception)
{
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
timer.Tick += Timer_Tick;
timer.Start();
timer2 = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
timer2.Tick += Timer2_Tick;
timer2.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
SaveImage(bmpSource);
}
private async void Timer2_Tick(object sender, EventArgs e)
{
Title = "Detecting...";
FaceRectangle[] faceRects = await UploadAndDetectFaces(streamF);
Face[] faceAttributes = await UploadAndDetectFaceAttributes(streamF);
Title = String.Format("Detection Finished. {0} face(s) detected", faceRects.Length);
if (faceRects.Length > 0)
{
DrawingVisual visual = new DrawingVisual();
DrawingContext drawingContext = visual.RenderOpen();
drawingContext.DrawImage(bmpSource,
new Rect(0, 0, bmpSource.Width, bmpSource.Height));
double dpi = bmpSource.DpiX;
double resizeFactor = 96 / dpi;
foreach (var faceRect in faceRects)
{
drawingContext.DrawRectangle(
Brushes.Transparent,
new Pen(Brushes.Red, 2),
new Rect(
faceRect.Left * resizeFactor,
faceRect.Top * resizeFactor,
faceRect.Width * resizeFactor,
faceRect.Height * resizeFactor
)
);
}
drawingContext.Close();
RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap(
(int)(bmpSource.PixelWidth * resizeFactor),
(int)(bmpSource.PixelHeight * resizeFactor),
96,
96,
PixelFormats.Pbgra32);
faceWithRectBitmap.Render(visual);
FacePhoto.Source = faceWithRectBitmap;
}
if (faceAttributes.Length > 0)
{
foreach (var faceAttr in faceAttributes)
{
Label lb = new Label();
//Canvas.SetLeft(lb, lb.Width);
lb.Content = faceAttr.FaceAttributes.Gender;// + " " + faceAttr.Gender + " " + faceAttr.FacialHair + " " + faceAttr.Glasses + " " + faceAttr.HeadPose + " " + faceAttr.Smile;
lb.FontSize = 50;
lb.Width = 200;
lb.Height = 100;
stack.Children.Add(lb);
}
}
}
private async Task<FaceRectangle[]> UploadAndDetectFaces(string imageFilePath)
{
try
{
using (Stream imageFileStream = File.OpenRead(imageFilePath))
{
var faces = await faceServiceClient.DetectAsync(imageFilePath);
var faceRects = faces.Select(face => face.FaceRectangle);
var faceAttrib = faces.Select(face => face.FaceAttributes);
return faceRects.ToArray();
}
}
catch (Exception)
{
return new FaceRectangle[0];
}
}
private async Task<Face[]> UploadAndDetectFaceAttributes(string imageFilePath)
{
try
{
using (Stream imageFileStream = File.Open(imageFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var faces = await faceServiceClient.DetectAsync(imageFileStream, true, true, new FaceAttributeType[] { FaceAttributeType.Gender, FaceAttributeType.Age, FaceAttributeType.Smile, FaceAttributeType.Glasses, FaceAttributeType.HeadPose, FaceAttributeType.FacialHair });
return faces.ToArray();
}
}
catch (Exception)
{
return new Face[0];
}
}
}
Above code worked well. But, I want to convert each frame of Kinect Color Feed directly to Stream and I have no idea how to do it though I searched but nothing worked for me. If Somebody can help me then it'll be great. Thanks!
Instead of persisting the frame to a file in SaveImage, you can persist it to a MemoryStream, rewind it (by calling Position = 0), and send that stream to DetectAsync().
Also note that in UploadAndDetectFaces, you should send imageFileStream, not imageFilePath, to DetectAsync(). You probably don't want to call both UploadAndDetectFaces and UploadAndDetectFaceAttributes anyway, since you're just doubling your work (and quota/rate-limit hit.)
I have the codes below
fName =E:\Csharp\NewMacaron\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\\data00.txt"
From a method within my program I create, into application folder, a series of datas as fName above
After lunching the printing form I have the printcontroller preview on screen with Previous Next and some other buttons for printing and zooming.
On form_load I have ShowPage();
PrintPageEventHandler does not work and nothing is displayed.
However when I click the print_button correct page is printed:
What is wrong with the printpreviewcontroller ?
I'am using .net 3.5 and c# 2008
private void ShowPage()
{
try
{
streamToPrint = new StreamReader(fName, Encoding.UTF8);
pd = new PrintDocument();
pd.DocumentName = fName;
PrinterSettings ps = new PrinterSettings();
printFont = new Font("Courier", 10);
pd.PrinterSettings.PrinterName = prnName; // GetDefaultPrinter returns prName
pd.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("PaperA4", 840, 1180);
ppc = new PrintPreviewControl();
ppc.Document = pd;
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
}
catch (Exception es)
{
MessageBox.Show(es.Message.ToString());
}
}
private void print_button(object sender, EventArgs e)
{
streamToPrint = new StreamReader(fName, Encoding.UTF8);
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
try
{
pd.Print();
}
catch (Win32Exception es)
{
MessageBox.Show(es.Message.ToString());
streamToPrint.Close();
}
streamToPrint.Close();
PublicVariables.PrintFormStat = false;
PublicVariables.PrintData = 0;
this.Hide();
I have a CRIMINAL BUG in the program the printform was named ppc and the printpreviewcontroller also.
I don't know how assembly has accepted that.
After the correction of that tI can only use one time printpreviewcontroller
The second page is not displayed.
I am trying to print a variable with a specified font, but the string is null so nothing is visible in the output. please go through the code and help me to find the error
class BasicClass
{
public string str;
public Font fnt;
}
class BasicMethod:BasicClass
{
public void changevalues(string newstr,Font newfnt)
{
str = newstr;
fnt = newfnt;
}
}
class PrintClass:BasicClass
{
public void print()
{
PrintDialog pd = new PrintDialog();
PrintDocument pdoc = new PrintDocument();
PrinterSettings ps = new PrinterSettings();
PaperSize psize = new PaperSize();
pdoc.DefaultPageSettings.Landscape = true;
pd.Document = pdoc;
pd.Document.DefaultPageSettings.PaperSize = psize;
pdoc.PrintPage += new PrintPageEventHandler(pdoc_PrintPage);
DialogResult result = pd.ShowDialog();
if (result == DialogResult.OK)
{
PrintPreviewDialog ppd = new PrintPreviewDialog();
ppd.Document = pdoc;
ppd.PrintPreviewControl.Zoom = 1.5;
((Form)ppd).WindowState = FormWindowState.Maximized;
DialogResult ppdResult = ppd.ShowDialog();
}
}
void pdoc_PrintPage(object sender, PrintPageEventArgs e)
{
Graphics g = e.Graphics;
//string str1 = "XYZ";
//Font fnt1 = new Font("Arial", 12.5f);
g.DrawString(str, fnt, new SolidBrush(Color.Black), 10, 10);
}
}
Button Click event
private void button1_Click(object sender, EventArgs e)
{
BasicMethod bm = new BasicMethod();
PrintClass pc = new PrintClass();
Font ft = new System.Drawing.Font("Arial", 12.5f);
bm.changevalues("Hello", ft);
pc.print();
}
i need to get the output Hello
You are setting the values you want in a completely different object from the one where you try to use them.
One way to fix this:
Change the PrintClass so that it inherits the BasicMethod class instead of BasicClass
class PrintClass : BasicMethod
Then change your click handler:
private void button1_Click(object sender, EventArgs e)
{
PrintClass pc = new PrintClass();
Font ft = new System.Drawing.Font("Arial", 12.5f);
pc.changevalues("Hello", ft);
pc.print();
}
i want to create PDF, from a currently running .aspx page and i successfully done this. But problem is that when i login through a login page and go for to create a PDF of a report_page(i can access this report_page only when i successfully login) and click on button to generate a PDF of currently running report_page then here PDF is generating of a login page rather than report_page.
And here i have another report_page which need not to login to generate report when i am generating report through this report_page(not need to login) and try to convert it to PDF then it is working correctly means here PDF is generated of report_page.
here i paste my code please check it and give me solution for this:
protected void btn_print_Click(object sender, EventArgs e)
{
try
{
string url = HttpContext.Current.Request.Url.AbsoluteUri;
int width = 850;
int height = 550;
Thumbnail1 thumbnail = new Thumbnail1(url, 990, 1000, width, height);
Bitmap image = thumbnail.GenerateThumbnail();
image.Save(Server.MapPath("~") + "/Dwnld/Thumbnail.bmp");
imagepath = Server.MapPath("~").ToString() + "\\Dwnld\\" + "Thumbnail.bmp";
imagepath1 = Server.MapPath("~").ToString() + "\\Dwnld\\" + "Thumbnail.pdf";
convetToPdf();
}
catch (Exception)
{
throw;
}
}
string imagepath = null;
string imagepath1 = null;
public void convetToPdf()
{
PdfDocument doc = new PdfDocument();
System.Drawing.Size size = PageSizeConverter.ToSize(PdfSharp.PageSize.A4);
PdfPage pdfPage = new PdfPage();
pdfPage.Orientation = PageOrientation.Landscape;
doc.Pages.Add(pdfPage);
// XSize size = PageSizeConverter.ToSize(PdfSharp.PageSize.A4)
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]);
XImage img = XImage.FromFile(imagepath);
xgr.DrawImage(img, 0, 0);
doc.Save(imagepath1);
xgr.Dispose();
img.Dispose();
doc.Close();
Response.ContentType = "Application/pdf";
//Get the physical path to the file.
string FilePath = imagepath1;
//Write the file directly to the HTTP content output stream.
Response.WriteFile(FilePath);
Response.End();
}
public class Thumbnail1
{
public string Url { get; set; }
public Bitmap ThumbnailImage { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int BrowserWidth { get; set; }
public int BrowserHeight { get; set; }
public Thumbnail1(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
{
this.Url = Url;
this.BrowserWidth = BrowserWidth;
this.BrowserHeight = BrowserHeight;
this.Height = ThumbnailHeight;
this.Width = ThumbnailWidth;
}
public Bitmap GenerateThumbnail()
{
Thread thread = new Thread(new ThreadStart(GenerateThumbnailInteral));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
return ThumbnailImage;
}
private void GenerateThumbnailInteral()
{
WebBrowser webBrowser = new WebBrowser();
webBrowser.ScrollBarsEnabled = false;
webBrowser.Navigate(this.Url);
webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
while (webBrowser.ReadyState != WebBrowserReadyState.Complete) System.Windows.Forms.Application.DoEvents();
webBrowser.Dispose();
}
private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser webBrowser = (WebBrowser)sender;
webBrowser.ClientSize = new Size(this.BrowserWidth, this.BrowserHeight);
webBrowser.ScrollBarsEnabled = false;
this.ThumbnailImage = new Bitmap(webBrowser.Bounds.Width, webBrowser.Bounds.Height);
webBrowser.BringToFront();
webBrowser.DrawToBitmap(ThumbnailImage, webBrowser.Bounds);
this.ThumbnailImage = (Bitmap)ThumbnailImage.GetThumbnailImage(Width, Height, null, IntPtr.Zero);
}
}
protected void CreateThumbnailImage(object sender, EventArgs e)
{
}
The issue is that you are requesting the page-to-be-generated in a separate request which does not include your login cookie/session. It is requesting it as though it was a completely separate browser would.
The only way I can think is that if you have basic authentication turned on in IIS you can change the url to be: http://myThumbnailUser:myThumbnailPassw0rd#www.mydomain.com/path/to/page/to/be/rendered.aspx.
You could try and attach the method that does all the generation to the page unload event to allow you to get the response stream, pump it into the WebBrowser control and thenuse that to generate your PDF.
protected void btn_print_Click(object sender, EventArgs e)
{
try
{
int width = 850;
int height = 550;
this.Page.Unload += delegate {
Thumbnail1 thumbnail = new Thumbnail1(this.Page, 990, 1000, width, height);
Bitmap image = thumbnail.GenerateThumbnail();
image.Save(Server.MapPath("~") + "/Dwnld/Thumbnail.bmp");
imagepath = Server.MapPath("~").ToString() + "\\Dwnld\\" + "Thumbnail.bmp";
imagepath1 = Server.MapPath("~").ToString() + "\\Dwnld\\" + "Thumbnail.pdf";
convetToPdf();
}
}
catch (Exception)
{
throw;
}
}
...
public Thumbnail1(Page page, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
{
this.Page = page;
this.BrowserWidth = BrowserWidth;
this.BrowserHeight = BrowserHeight;
this.Height = ThumbnailHeight;
this.Width = ThumbnailWidth;
}
...
private void GenerateThumbnailInteral()
{
WebBrowser webBrowser = new WebBrowser();
webBrowser.ScrollBarsEnabled = false;
webBrowser.Navigate(this.Url);
webBrowser.DocumentStream = this.Page.Response.GetResponseStream()
webBrowser.ClientSize = new Size(this.BrowserWidth, this.BrowserHeight);
webBrowser.ScrollBarsEnabled = false;
this.ThumbnailImage = new Bitmap(webBrowser.Bounds.Width, webBrowser.Bounds.Height);
webBrowser.BringToFront();
webBrowser.DrawToBitmap(ThumbnailImage, webBrowser.Bounds);
this.ThumbnailImage = (Bitmap)ThumbnailImage.GetThumbnailImage(Width, Height, null, IntPtr.Zero);
}
That also might work..
Cross-thread operation not valid: Control 'ocrTB' accessed from a thread other than the thread it was created on.
This is the error i have. And below is my coding.
#region OCR(Tab5_Component)
//When user is selecting, RegionSelect = true
private bool RegionSelect = false;
private int x0, x1, y0, y1;
private Bitmap bmpImage;
private void loadImageBT_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = #"C:\Users\Shen\Desktop";
open.Filter = "Image Files(*.jpg; *.jpeg)|*.jpg; *.jpeg";
if (open.ShowDialog() == DialogResult.OK)
{
singleFileInfo = new FileInfo(open.FileName);
string dirName = System.IO.Path.GetDirectoryName(open.FileName);
loadTB.Text = open.FileName;
pictureBox1.Image = new Bitmap(open.FileName);
bmpImage = new Bitmap(pictureBox1.Image);
}
}
catch (Exception)
{
throw new ApplicationException("Failed loading image");
}
}
//User image selection Start Point
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
RegionSelect = true;
//Save the start point.
x0 = e.X;
y0 = e.Y;
}
//User select image progress
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
//Do nothing it we're not selecting an area.
if (!RegionSelect) return;
//Save the new point.
x1 = e.X;
y1 = e.Y;
//Make a Bitmap to display the selection rectangle.
Bitmap bm = new Bitmap(bmpImage);
//Draw the rectangle in the image.
using (Graphics g = Graphics.FromImage(bm))
{
g.DrawRectangle(Pens.Red, Math.Min(x0, x1), Math.Min(y0, y1), Math.Abs(x1 - x0), Math.Abs(y1 - y0));
}
//Temporary display the image.
pictureBox1.Image = bm;
}
//Image Selection End Point
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
// Do nothing it we're not selecting an area.
if (!RegionSelect) return;
RegionSelect = false;
//Display the original image.
pictureBox1.Image = bmpImage;
// Copy the selected part of the image.
int wid = Math.Abs(x0 - x1);
int hgt = Math.Abs(y0 - y1);
if ((wid < 1) || (hgt < 1)) return;
Bitmap area = new Bitmap(wid, hgt);
using (Graphics g = Graphics.FromImage(area))
{
Rectangle source_rectangle = new Rectangle(Math.Min(x0, x1), Math.Min(y0, y1), wid, hgt);
Rectangle dest_rectangle = new Rectangle(0, 0, wid, hgt);
g.DrawImage(bmpImage, dest_rectangle, source_rectangle, GraphicsUnit.Pixel);
}
// Display the result.
pictureBox3.Image = area;
pictureBox3.Image.Save(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg");
}
/*private void loadFolderBT_Click(object sender, EventArgs e)
{
folderBrowserDialog.ShowDialog();
folderLocation.Text = folderBrowserDialog.SelectedPath;
}*/
private void ScanBT_Click(object sender, EventArgs e)
{
var folder = #"C:\Users\Shen\Desktop\LenzOCR\LenzOCR\WindowsFormsApplication1\ImageFile";
DirectoryInfo directoryInfo;
FileInfo[] files;
directoryInfo = new DirectoryInfo(folder);
files = directoryInfo.GetFiles("*.jpg", SearchOption.AllDirectories);
exit = false;
var processImagesDelegate = new ProcessImagesDelegate(ProcessImages2);
processImagesDelegate.BeginInvoke(files, null, null);
System.IO.File.Delete(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg");
}
private void ProcessImages2(FileInfo[] files)
{
var comparableImages = new List<ComparableImage>();
//Invoke(setMaximumDelegate, new object[] { workingProgressBar, files.Length });
var index = 0x0;
var operationStartTime = DateTime.Now;
foreach (var file in files)
{
if (exit)
{
return;
}
var comparableImage = new ComparableImage(file);
comparableImages.Add(comparableImage);
index++;
//Invoke(updateOperationStatusDelegate, new object[] { "Processed images", workingLabel, workingProgressBar, index, operationStartTime });
}
//Invoke(setMaximumDelegate, new object[] { workingProgressBar, comparableImages.Count });
index = 0;
similarityImagesSorted = new List<SimilarityImages>();
operationStartTime = DateTime.Now;
var fileImage = new ComparableImage(singleFileInfo);
for (var i = 0; i < comparableImages.Count; i++)
{
if (exit)
return;
var destination = comparableImages[i];
var similarity = fileImage.CalculateSimilarity(destination);
var sim = new SimilarityImages(fileImage, destination, similarity);
similarityImagesSorted.Add(sim);
index++;
//Invoke(updateOperationStatusDelegate, new object[] { "Compared images", workingLabel, workingProgressBar, index, operationStartTime });
}
similarityImagesSorted.Sort();
similarityImagesSorted.Reverse();
similarityImages = new BindingList<SimilarityImages>(similarityImagesSorted);
var buttons =
new List<Button>
{
ScanBT
};
if (similarityImages[0].Similarity > 85)
{
//MessageBox.Show("Similarity(%) : " + similarityImages[0].Similarity.ToString(), "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
//MessageBox.Show("Similarity(%) : " + similarityImages[0].Destination.ToString(), "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
//MessageBox.Show("Similarity(%) : " + similarityImages[0].Source.ToString(), "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=SHEN-PC\\SQLEXPRESS;Initial Catalog=CharacterImage;Integrated Security=True";
con.Open();
String getFile = "SELECT ImageName, Character FROM CharacterImage WHERE ImageName='" + similarityImages[0].Destination + "'";
SqlCommand cmd2 = new SqlCommand(getFile, con);
SqlDataReader rd2 = cmd2.ExecuteReader();
while (rd2.Read())
{
ocrTB.Text = rd2["Character"].ToString(); // <<<<<< error occur here
}
con.Close();
}
else
{
MessageBox.Show("No character found!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
Any solution for this?
var processImagesDelegate = new ProcessImagesDelegate(ProcessImages2);
processImagesDelegate.BeginInvoke(files, null, null);
You are executing this delegate asynchronously in a different thread - are you sure that's what you want? That being the case you can use Control.Invoke() to update a UI control from another thread (the one your ProcessImages2 method is executed under) :
string text = rd2["Character"].ToString();
Action updateText = () => ocrTB.Text = text;
ocrTB.Invoke(updateText);
In general it would be easier to use a background worker to process your data and update it in the Completed event handler.
You cannot modify the UI in any thread other than the UI thread, ProcessImages2 in this example attempts to do this, you need to use Dispatcher.Invoke or just run ProcessImages2 in the same thread (i.e. don't do processImagesDelegate.BeginInvoke.
Also, posting a big chunk of code can be good, but try to give details on which line is throwing the error!
You need to marshal back to the other thread when trying to access controls on the UI from a new thread.. You can use Control.Invoke like such:
someControl.Invoke((MethodInvoker)delegate
{
someControl.DoSomething();
});