I have a class that Read/Write from registry. But how can i use this class from dynamically compiled form. I can execute function and even get var valuables from dynamically compiled form, but how can i execute my program function or get var valuable from my dynamically compiled form.
RegistryHelper class
using Microsoft.Win32;
namespace myForm
{
class RegistryHelper
{
public void WriteKey(string k, string value)
{
RegistryKey key = Registry.CurrentUser.CreateSubKey("rGO");
key.SetValue(k, value);
key.Close();
}
public string ReadKey(string k)
{
RegistryKey op = Registry.CurrentUser.OpenSubKey("rGO");
return (string)op.GetValue(k);
}
}
}
Example where i execute test function inside Form1 class
using System;
using System.CodeDom.Compiler;
using System.IO;
using Microsoft.CSharp;
namespace myForm
{
class Program
{
static void Main(string[] args)
{
using (var foo = new CSharpCodeProvider())
{
var parameters = new CompilerParameters
{
GenerateInMemory = true,
GenerateExecutable = false
};
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("System.Core.dll");
parameters.ReferencedAssemblies.Add("System.Drawing.dll");
parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
var source = File.ReadAllText("form.txt");
CompilerResults results = foo.CompileAssemblyFromSource(parameters, source);
Type type = results.CompiledAssembly.GetType("myForm.Form1");
object compiledObject = Activator.CreateInstance(type);
// Execure test function from dynamically compiled form
type.GetMethod("test").Invoke(compiledObject, new object[] { });
}
}
}
}
form.txt source
using System.Windows.Forms;
namespace myForm
{
public partial class Form1 : Form
{
public static int _testVar = 0; // how can i get this var value?
public Form1()
{
InitializeComponent();
}
public void test()
{
MessageBox.Show("test");
}
}
}
namespace myForm
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(12, 12);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(260, 204);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 222);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(260, 40);
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 274);
this.Controls.Add(this.button1);
this.Controls.Add(this.richTextBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.Button button1;
}
}
To do this, you just need to add a reference to itself in the references compiled code:
using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using Microsoft.CSharp;
namespace ConsoleApplication212
{
class Program
{
static void Main(string[] args)
{
//dynamic code
var source = #"
static class Program
{
public static void Start()
{
//We call the Test method of the class Console Application 212.Helper
ConsoleApplication212.Helper.Test();
}
}";
//compile and run
Run(source);
Console.ReadLine();
}
static void Run(string source)
{
using (var provider = new CSharpCodeProvider())
{
var parameters = new CompilerParameters { GenerateInMemory = true };
parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
//link your self
parameters.ReferencedAssemblies.Add(Path.GetFileName(Assembly.GetExecutingAssembly().CodeBase));
//compile
var result = provider.CompileAssemblyFromSource(parameters, source);
if (result.Errors.Count > 0)
throw new Exception(result.Errors[0].ErrorText);
//Find class Program
var type = result.CompiledAssembly.GetType("Program");
//вызыаем метод Start
type.GetMethod("Start").Invoke(null, null);
}
}
}
/// <summary>
/// Public class that will be used in dynamically compiled code
/// </summary>
public static class Helper
{
public static void Test()
{
MessageBox.Show("Hi from Helper");
}
}
}
Related
i'm building a quick and dirty program to basically turn on a light in my room from a website as a code kata. during the programming i decided i would temporarily use a winform to test instead of hooking the physical light up (and having all sorts of possible problems there). but when i run my program the winform doesn't show, I've tried to run the executable but still nothing. when debugging i can see all the code works fine it's just that the winform doesn't show up. here is all the code:
form1.cs:
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows.Forms;
namespace alarm_light_test
{
public partial class Form1 : Form
{
WebClient client = new WebClient();
public Form1()
{
InitializeComponent();
while (true)
{
if (CheckData())
{
TurnSirenOn();
client.DownloadString("**link to .php file to reset the .txt file**");
Thread.Sleep(5000);
TurnSirenOff();
}
else
{
Thread.Sleep(1000);
}
}
}
public bool CheckData()
{
bool retval = false;
Stream stream = client.OpenRead("**link to online .txt file**");
StreamReader reader = new StreamReader(stream);
String content = reader.ReadToEnd();
if(content == "1")
{
retval = true;
}
return retval;
}
public void TurnSirenOn()
{
pictureBox1.BackColor = Color.Green;
}
public void TurnSirenOff()
{
pictureBox1.BackColor = Color.Red;
}
}
}
program.cs:
using System;
using System.Windows.Forms;
namespace alarm_light_test
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Form1.Designer.cs
namespace alarm_light_test
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.pictureBox1 = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// pictureBox1
//
this.pictureBox1.Location = new System.Drawing.Point(13, 13);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(235, 235);
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(260, 260);
this.Controls.Add(this.pictureBox1);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.PictureBox pictureBox1;
}
}
In your constructor public Form1(), you have a loop for-ever (a.k.a an infinite loop).
The while(true) will prevent the constructor from finishing the construction of the form object, and therefore will not be able to display anything.
public Form1()
{
InitializeComponent();
while (true) // This loop will never exit, and will run forever
{
...
}
}
Edit: Sample of how to run your code Asynchronously, therefore allowing the form to fully initialise and display as expected.
public Form1()
{
InitializeComponent();
DoWorkAsynchronously();
}
private async Task DoWorkAsynchronously()
{
await Task.Run(() =>
{
while (true)
{
if (CheckData())
{
TurnSirenOn();
client.DownloadString("**link to .php file to reset the .txt file**");
Thread.Sleep(5000);
TurnSirenOff();
}
else
{
Thread.Sleep(1000);
}
}
});
}
I am creating a pos app that cannot communicate with my fiscal printer. So I have decided to store a receipt in a text file as Json object and make Windows Service app with FileSystemWatch to check for file updates and forward it to printer. I am using third party library to communicate with the printer. Here is a code of the service:
Program.cs
static void Main(string[] args)
{
var program = new Watcher();
if (Environment.UserInteractive)
{
program.Start();
}
else
{
ServiceBase.Run(new ServiceBase[]
{
program
});
}
//ServiceBase[] ServicesToRun;
//ServicesToRun = new ServiceBase[]
//{
// new Watcher()
//};
//ServiceBase.Run(ServicesToRun);
}
Watcher.cs
public partial class Watcher : ServiceBase
{
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool SetServiceStatus(IntPtr handle, ref ServiceStatus serviceStatus);
public static OICFiscalPrinter printer { get; set; }
[StructLayout(LayoutKind.Sequential)]
public struct ServiceStatus
{
public long dwServiceType;
public ServiceState dwCurrentState;
public long dwControlsAccepted;
public long dwWin32ExitCode;
public long dwServiceSpecificExitCode;
public long dwCheckPoint;
public long dwWaitHint;
};
public enum ServiceState
{
SERVICE_STOPPED = 0x00000001,
SERVICE_START_PENDING = 0x00000002,
SERVICE_STOP_PENDING = 0x00000003,
SERVICE_RUNNING = 0x00000004,
SERVICE_CONTINUE_PENDING = 0x00000005,
SERVICE_PAUSE_PENDING = 0x00000006,
SERVICE_PAUSED = 0x00000007,
}
public Watcher()
{
InitializeComponent();
}
public void CheckReceipt(object e, FileSystemEventArgs args)
{
printer = new OICFiscalPrinter();
var name = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string text = null;
try
{
text = System.IO.File.ReadAllText(name + "\\Pictures\\test.txt");
var BasketList = JsonConvert.DeserializeObject<List<ItemsOnFacture>>(text);
printer.PortConfigString = "PortName=COM4;DataBits=8;Speed=9600;" +
"Parity = N; StopBits = 1; FlowControl = X;" +
"ReadTimeout = 6000;" +
"WriteTimeout = 500; UseReadBuffer = 1";
printer.Active = true;
var t = printer.Open();
if (!t) return;
printer.OpenReceipt();
foreach (var item in BasketList)
{
printer.ReceiptItem(item.ItemName, item.VatFee == 5 ? "B" : item.VatFee == 8 ? "A" : "D",
(decimal)item.PriceBrutto,
item.Amount, "unit", (decimal)item.PriceBruttoSum);
}
printer.CloseReceipt((decimal)BasketList.Sum(w => w.PriceBruttoSum),
(decimal)BasketList.Sum(w => w.PriceBruttoSum));
printer.Close();
File.Delete(name + "\\Pictures\\test.txt");
}
catch
{
}
}
public void Start()
{
//Start Logic here
var serviceStatus = new ServiceStatus
{
dwCurrentState = ServiceState.SERVICE_START_PENDING,
dwWaitHint = 100000
};
this.fileSystemWatcher1 = new System.IO.FileSystemWatcher();
((System.ComponentModel.ISupportInitialize)(this.fileSystemWatcher1)).BeginInit();
//
// fileSystemWatcher1
//
this.fileSystemWatcher1.EnableRaisingEvents = true;
var name = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
fileSystemWatcher1 = new FileSystemWatcher(name + "\\Pictures", "test.txt")
{
EnableRaisingEvents = true,
IncludeSubdirectories = false,
NotifyFilter = NotifyFilters.DirectoryName
};
SetServiceStatus(this.ServiceHandle, ref serviceStatus);
this.fileSystemWatcher1.Changed += new System.IO.FileSystemEventHandler(this.CheckReceipt);
((System.ComponentModel.ISupportInitialize)(this.fileSystemWatcher1)).EndInit();
// Update the service state to Running.
serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
SetServiceStatus(this.ServiceHandle, ref serviceStatus);
}
protected override void OnStart(string[] args)
{
Start();
}
protected override void OnContinue()
{
}
protected override void OnStop()
{
}
private FileSystemWatcher fileSystemWatcher1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
//
// Watcher
//
components = new System.ComponentModel.Container();
this.ServiceName = "WATTOFP";
}
#endregion
}
ProjectInstaller.cs
[RunInstaller(true)]
public class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent();
}
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
//
// serviceProcessInstaller1
//
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
//
// serviceInstaller1
//
this.serviceInstaller1.Description = "WATTO Fiscal Printer";
this.serviceInstaller1.DisplayName = "WATTO Fiscal Printer";
this.serviceInstaller1.ServiceName = "WATTOFP";
this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
//
// ProjectInstaller
//
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1,
this.serviceInstaller1});
}
#endregion
private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
private System.ServiceProcess.ServiceInstaller serviceInstaller1;
}
The problem is the fact that after installation when I try to run the service it starts and immediately stops as the warning appears. How can I make the service run and the watch the file for the changes?
The problem might be that service by default is running under system account. Thus user folder is not what you're expecting and there is no file there.
Usually when service cannot be started, there should be a error with exception in event log. Please post it here for further assistance.
I am getting three errors that are preventing my program from running and I cant figure out what they mean? I must be stupid because I even have my C# book next to me and it still doesn't make sense. Any help would be great. The errors are:
Projects\WindowsFormsApplication1\obj\x86\Release\WindowsFormsApplication1.exe' has more than one entry point defined: 'WindowsFormsApplication1.Program.Main()'. Compile with /main to specify the type that contains the entry point.
'WindowsFormsApplication1.Form1.Dispose(bool)': no suitable method found to override
Projects\WindowsFormsApplication1\obj\x86\Release\WindowsFormsApplication1.exe' has more than one entry point defined: 'Text.Main()'. Compile with /main to specify the type that contains the entry point.
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
public class Text : Form
{
private Font arialBold24 = new Font("Arial", 24, FontStyle.Bold);
private Font timesItalic14 = new Font("Times New Roman", 14, FontStyle.Italic);
private Font courierPlain18 = new Font("Courier New", 18, FontStyle.Strikeout);
private Font genericSerifBI20 = new Font(FontFamily.GenericSerif, 20, FontStyle.Bold | FontStyle.Italic);
private Font verdanaPlain18 = new Font("Verdana", 18, FontStyle.Regular | FontStyle.Underline);
public Text()
{
Size = new Size(400, 200);
Text = "Text";
BackColor = Color.White;
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
int w = (int)g.MeasureString(arialBold24.Name, arialBold24).Width;
int arialStart = (Width - w) / 2;
int otherStart = Width / 4;
int h = DisplayRectangle.Height;
g.DrawString(arialBold24.Name, arialBold24, Brushes.Blue, arialStart, 0);
g.DrawString(timesItalic14.Name, timesItalic14, Brushes.Blue, otherStart, h / 5);
g.DrawString(courierPlain18.Name, courierPlain18, Brushes.Blue, otherStart, 2 * h / 5);
g.DrawString(genericSerifBI20.Name, genericSerifBI20, Brushes.Blue, otherStart, 3 * h / 5);
g.DrawString(verdanaPlain18.Name, verdanaPlain18, Brushes.Blue, otherStart, 4 * h / 5);
base.OnPaint(e);
}
public static void Main()
{
Application.Run(new Text());
}
}
The program.cs code is:
namespace WindowsFormsApplication1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Updated Code of Form1:
namespace WindowsFormsApplication1
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
}
}
Program.CS code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Text());
}
}
}
First of all, you don't need another Main method in class Text, as it is already defined in the Program.cs file if you use the built-in template to create a WinForms app.
I hope removing the redundant Main method from class Text may be enough to run the app successfully.
EDIT
In the Program.cs file, instantiate the Text class instead of Form1 like below:
namespace WindowsFormsApplication1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Text());
}
}
}
Also you need to enclose the class Text with the following namespace:
namespace WindowsFormsApplication1
{
public class Text : Form
{
// ...
}
}
EDIT 2:
Please override the Dispose() method inside class Form1 like below:
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
real problem:
Mainform read routine more than twice. and all components and objects inside of MainForm empty
Example:
button first run of excellent
add my code:
namespace CheckNet
{
/// <summary>
/// Description of MainForm.
/// </summary>
delegate void Function();
public partial class MainForm : Form
{
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
Btn_Inicio.Click += new EventHandler (Btn_InicioClick);
// VerificationForm += new EventHandler (VerificationForm);
//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
private DPFP.Template Template;
private DPFP.Template myTemplate;
//
void Btn_InicioClick(object sender, EventArgs e)
{
// call rutine ejecutar boton primera vez
//
if (this.panelContenedor.Controls.Count > 0)
this.panelContenedor.Controls.RemoveAt(0);
VerificationForm hijos = new VerificationForm();
hijos.TopLevel = false;
hijos.FormBorderStyle = FormBorderStyle.None;
hijos.Dock = DockStyle.Fill;
this.panelContenedor.Controls.Add(hijos);
this.panelContenedor.Tag = hijos;
hijos.Show();
}
void Button7Click(object sender, EventArgs e)
{
AddFormInPanel(new Hijo2());
}
private void AddFormInPanel(object formHijo)
{
if (this.panelContenedor.Controls.Count > 0)
this.panelContenedor.Controls.RemoveAt(0);
Form fh = formHijo as Form;
fh.TopLevel = false;
fh.FormBorderStyle = FormBorderStyle.None;
fh.Dock = DockStyle.Fill;
this.panelContenedor.Controls.Add(fh);
this.panelContenedor.Tag = fh;
fh.Show();
}
void Close_bottonClick(object sender, EventArgs e)
{
Close();
}
}
}
////////// call Form VerificationForm
namespace CheckNet
{
/* NOTE: This form is inherited from the CaptureForm,
so the VisualStudio Form Designer may not load it properly
(at least until you build the project).
If you want to make changes in the form layout - do it in the base CaptureForm.
All changes in the CaptureForm will be reflected in all derived forms
(i.e. in the EnrollmentForm and in the VerificationForm)
*/
public class VerificationForm : CaptureForm
{
public void Verify(DPFP.Template template)
{
Template = template;
ShowDialog();
}
protected override void Init()
{
base.Init();
base.Text = "Fingerprint Verification ";
Verificator = new DPFP.Verification.Verification(); // Create a fingerprint template verificator
UpdateStatus(0);
}
protected override void Process(DPFP.Sample Sample)
{
base.Process(Sample);
// Process the sample and create a feature set for the enrollment purpose.
DPFP.FeatureSet features = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Verification);
// Check quality of the sample and start verification if it's good
// TODO: move to a separate task
template= TomarHuellaBd();
Template=template;
if (features != null)
{
// Compare the feature set with our template
DPFP.Verification.Verification.Result result = new DPFP.Verification.Verification.Result();
Verificator.Verify(features, Template, ref result);
UpdateStatus(result.FARAchieved);
if (result.Verified)
{
MakeReport2(" ");
}
else
MakeReport("Huella no Identificado.");
}
}
private void UpdateStatus(int FAR)
{
// Show "False accept rate" value
SetStatus(String.Format("False Accept Rate (FAR) = {0}", FAR));
}
private DPFP.Template TomarHuellaBd()
{
// Verifica la Huella desde una base de Datos
bool Bandera=true;
try { // Validar Numero
int idEmpleado =int.Parse(Global_ip.Globalip.ToString());
} catch {
MessageBox.Show("Error Numero de Empleado ", Global_ip.Globalip.ToString());
Bandera=false;
//
return null;
//
}
try
{
int NumEmpleado=int.Parse(Global_ip.Globalip.ToString());
enlacedb db = new enlacedb();
FbConnection conexion2 = new FbConnection(db.connectionString);
conexion2.Open();
FbCommand Frda = new FbCommand("SELECT * FROM REGHUMAN WHERE ID_EMPLEADO=#ID_EMPLEADO", conexion2);
Frda.Parameters.Add("#ID_EMPLEADO",SqlDbType.VarChar).Value = NumEmpleado;
FbDataReader leerF = Frda.ExecuteReader();
bool fseek= leerF.Read();
if (fseek) {
Global_Nombre.GlobalNombre= leerF.GetValue(4).ToString();
Byte[] imageF = new Byte[Convert.ToInt32 ((leerF.GetBytes(2, 0,null, 0, Int32.MaxValue)))];
leerF.GetBytes(2, 0, imageF, 0, imageF.Length);
MemoryStream memfpt = new MemoryStream(imageF);
DPFP.Template template = new DPFP.Template(memfpt);
return template;
}
else
{
return null;
}
}
catch (Exception err2) {
MessageBox.Show(err2.ToString());
}
return null;
}
private DPFP.Template Template;
private DPFP.Template template;
private DPFP.Verification.Verification Verificator;
}
}
if the user requests running second time the same button
VerificationForm routines and residents are CaptureForm Digital Persona device and can not read the fingerprint
how to empty or reset the procedure or routine (MainForm, VerificationForm and CaptureForm)
Thank.
The Solution is:
modify the program.cs
private static void Main (string [] args)
{
Application.EnableVisualStyles ();
Application.SetCompatibleTextRenderingDefault (false);
Fm1 MainForm = new MainForm ();
Application.Run (fm1);
if (fm1.ToRestart)
Application.Restart ();
}
start
ToRestart public bool = false;
void Btn_InicioClick (object sender, EventArgs e)
{
ToRestart = true;
this.Close ();
}
to reset the fingerprint reader and winform controls
Thank
I've created a user control (windows form application) to get an instance of Word (either active or new), and provide a button to open documents into that instance using a file dialog picker.
The form contains 2 buttons, 1 for getting the word instance and another for opening a document. It also contains a list box for displaying the open documents, and an openfiledialog control to provide the means for selecting documents to open.
I am handling the Application.DocumentOpen event in order to populate the listbox...
m_wordApp.DocumentOpen += new msoWord.ApplicationEvents4_DocumentOpenEventHandler(m_wordApp_DocumentOpen);
I am determining when i need to reinvoke my method that populates the listbox to ensure that access to the control is on the same thread that created it....
private void AddDocument(string name)
{
try
{
if (m_documentsListBox.InvokeRequired && m_documentsListBox.IsHandleCreated&&!m_documentsListBox.IsDisposed)
{
this.Invoke(m_AddDocument, new object[] { name });
return;
}
if (!m_documentsListBox.Items.Contains(name))
m_documentsListBox.Items.Add(name);
}
catch (Exception ex)
{
}
}
Im not using 2 dots, and i believe i am releasing any COM objects correctly.
Why does the application hang on either the line of code that opens the document ...
WordDoc = m_wordDocs.Open(ref fileName);
or the line that reinvokes the AddDocument() method...
this.Invoke(m_AddDocument, new object[] { name });
somewhere along the line i think i must be having a thread issue, because the hang only happens if i choose to open a document using the button, rather than from within the Word application directly.
full code below...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
// use these for the core office & word references
using msoWord = Microsoft.Office.Interop.Word;
namespace MCDevNET.Office.Word.TestUIControls
{
public partial class OpenWordDocument : Form
{
public OpenWordDocument()
{
InitializeComponent();
m_openWordButton.Click += new EventHandler(buttonOpenWordApp_Click);
m_openDocumentButton.Click += new EventHandler(buttonOpenDocument_Click);
m_AddDocument = new UpdateListControl(AddDocument);
}
#region Form: control eventHandlers
void buttonOpenWordApp_Click(object sender, EventArgs e)
{
try
{
if (!IsValid(m_wordApp))
WordApp = GetInstance();
AddAllDocuments();
}
catch (Exception ex)
{
}
}
void buttonOpenDocument_Click(object sender, EventArgs e)
{
OpenWordDoc();
}
public delegate void UpdateListControl(string name);
private UpdateListControl m_AddDocument;
private void AddDocument(string name)
{
try
{
if (m_documentsListBox.InvokeRequired && m_documentsListBox.IsHandleCreated&&!m_documentsListBox.IsDisposed)
{
this.Invoke(m_AddDocument, new object[] { name });
return;
}
if (!m_documentsListBox.Items.Contains(name))
m_documentsListBox.Items.Add(name);
}
catch (Exception ex)
{
}
}
private void AddAllDocuments()
{
try
{
m_documentsListBox.Items.Clear();
if (m_wordDocs != null)
{
for (int i = 1; i <= m_wordDocs.Count; i++)
AddDocument(m_wordDocs[i].Name);
}
}
catch (Exception ex)
{
}
}
#endregion
#region Word: properties & eventhandlers
private msoWord.Document m_wordDoc;
public msoWord.Document WordDoc
{
get { return m_wordDoc; }
private set
{
try
{
if (m_wordDoc != value)
{
ReleaseCOMObject(m_wordDoc);
m_wordDoc = value;
}
}
catch (Exception ex)
{
}
}
}
private msoWord.Documents m_wordDocs;
public msoWord.Documents WordDocs
{
get { return m_wordDocs; }
private set
{
try
{
if (m_wordDocs != value)
{
ReleaseCOMObject(m_wordDocs);
m_wordDocs = value;
}
}
catch (Exception ex)
{
}
}
}
private msoWord.Application m_wordApp;
public msoWord.Application WordApp
{
get { return m_wordApp; }
set
{
try
{
if (m_wordApp != value)
{
if (m_wordApp != null)
{
m_wordApp.DocumentOpen -= new msoWord.ApplicationEvents4_DocumentOpenEventHandler(m_wordApp_DocumentOpen);
ReleaseCOMObject(m_wordApp);
}
m_wordApp = value;
if (IsValid(m_wordApp))
{
m_wordApp.DocumentOpen += new msoWord.ApplicationEvents4_DocumentOpenEventHandler(m_wordApp_DocumentOpen);
WordDocs = m_wordApp.Documents;
}
}
}
catch (Exception ex)
{
}
}
}
void m_wordApp_DocumentOpen(msoWord.Document doc)
{
try
{
string name = doc.Name;
AddDocument(name);
}
catch (Exception ex)
{
}
finally
{
ReleaseCOMObject(doc);
doc = null;
}
}
private msoWord.Application GetInstance()
{
msoWord.Application app = null;
try
{
app = (msoWord.Application)Marshal.GetActiveObject("Word.Application");
}
catch (Exception ex)
{
if (app == null)
app = new msoWord.Application();
}
finally
{
if (IsValid(app))
{
app.Visible = true;
app.Activate();
}
}
return app;
}
private void OpenWordDoc()
{
try
{
m_openFileDialog.AddExtension = true;
m_openFileDialog.Filter = "All Word (*.docx; *.docm; *.doc; *.dotx; *.dotm; *.dot)|*.docx;*.docm;*.doc;*.dotx;*.dotm;*.dot|Word Documents (*.docx)|*.docx|Word Macro-Enabled Documents (*.docm)|*.docm|Word 97-2003 Documents (*.doc)|*.doc|All Word Templates (*.dotx; *.dotm; *.dot)|*.dotx;*.dotm;*.dot|Word Templates (*.dotx)|*.dotx|Word Macro-Enabled Templates (*.dotm)|*.dotm)";
m_openFileDialog.FilterIndex = 1;
m_openFileDialog.Multiselect = false;
m_openFileDialog.Title = "Open Word Document";
if (m_openFileDialog.ShowDialog() == DialogResult.OK)
{
object fileName = m_openFileDialog.FileName;
WordDoc = m_wordDocs.Open(ref fileName);
}
}
catch (Exception ex)
{
}
}
private bool IsValid(msoWord.Application app)
{
try
{
if (app != null)
{
string name = app.Caption;
return true;
}
}
catch (Exception ex)
{
}
return false;
}
#endregion
private void ReleaseCOMObject(object comObject)
{
try
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
if (comObject != null && Marshal.IsComObject(comObject))
Marshal.ReleaseComObject(comObject);
}
catch (Exception ex)
{
}
}
}
}
namespace MCDevNET.Office.Word.TestUIControls
{
partial class OpenWordDocument
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.m_documentsListBox = new System.Windows.Forms.ListBox();
this.m_openDocumentButton = new System.Windows.Forms.Button();
this.m_openWordButton = new System.Windows.Forms.Button();
this.m_openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.SuspendLayout();
//
// lb_Documents
//
this.m_documentsListBox.FormattingEnabled = true;
this.m_documentsListBox.Location = new System.Drawing.Point(12, 41);
this.m_documentsListBox.Name = "lb_Documents";
this.m_documentsListBox.Size = new System.Drawing.Size(156, 134);
this.m_documentsListBox.TabIndex = 8;
//
// m_openDocumentButton
//
this.m_openDocumentButton.Location = new System.Drawing.Point(93, 12);
this.m_openDocumentButton.Name = "m_openDocumentButton";
this.m_openDocumentButton.Size = new System.Drawing.Size(75, 23);
this.m_openDocumentButton.TabIndex = 7;
this.m_openDocumentButton.Text = "Doc";
this.m_openDocumentButton.UseVisualStyleBackColor = true;
//
// m_openWordButton
//
this.m_openWordButton.Location = new System.Drawing.Point(12, 12);
this.m_openWordButton.Name = "m_openWordButton";
this.m_openWordButton.Size = new System.Drawing.Size(75, 23);
this.m_openWordButton.TabIndex = 6;
this.m_openWordButton.Text = "Word";
this.m_openWordButton.UseVisualStyleBackColor = true;
//
// m_openFileDialog
//
this.m_openFileDialog.FileName = "openFileDialog1";
//
// OpenWordDocument
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(182, 184);
this.Controls.Add(this.m_documentsListBox);
this.Controls.Add(this.m_openDocumentButton);
this.Controls.Add(this.m_openWordButton);
this.Name = "OpenWordDocument";
this.Text = "OpenWordDocument";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ListBox m_documentsListBox;
private System.Windows.Forms.Button m_openDocumentButton;
private System.Windows.Forms.Button m_openWordButton;
private System.Windows.Forms.OpenFileDialog m_openFileDialog;
}
}
The hang happens on the call to Documents.Open(fileName)
You have an event handler wired up for the Application.DocumentOpen event. On removing this event handler the hang no longer occurs.
I presume the reason for the problem is that you are getting deadlocked as Word tries to fire that event before the Documents.Open call returns. Meaning the thread that handles the event is still busy.
Replacing
WordDoc = m_wordDocs.Open(ref fileName)
with
new System.Threading.Tasks.Task(() => WordDoc = m_wordDocs.Open(ref fileName))
.Start();
To open the document on a different thread seems to resolve the issue.