My word blocks add-ins for some reason. Following line gives no result.
ActiveDocument.Application.Selection.TypeText("Some String");
It appears as executed when debugging, however takes no effect on ActiveDocument. Do you know any possible reason? Macros/Add-ins are allowed in Word settings.
Michael
Basic word plug which store file into database before closing file.
public partial class ThisAddIn
{
private string friendlyErrorMessage = "An error has occurred inside the Case Manager Word Addin";
//static string filePath = null;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
this.Application.DocumentBeforeClose += Application_DocumentBeforeClose;
}
//public static string dialogFilePath;
public static string dialogFileName;
public static Word.Document doc;
void Application_DocumentBeforeClose(Word.Document document, ref bool Cancel)
{
try
{
string filePath = this.Application.ActiveDocument.FullName.ToString();
string fileName = this.Application.ActiveDocument.Name;
//dialogFilePath = filePath;
dialogFileName = fileName;
doc = document;
string tempFile;
string tempPath;
//var form = new SaveFileDialog();
//form.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
//form.ShowDialog();
//System.Windows.Forms.MessageBox.Show(form.ToString());
//_T is for editing template and save file after saving.
//+ is for saving
//document.Save();
var iPersistFile = (IPersistFile)document;
iPersistFile.Save(tempPath, false);
if (filePath.Contains("_T"))
{
//Store file into DB
}
else
{
//Store file into DB
}
//object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
//document.Close(ref doNotSaveChanges, ref missing, ref missing);
Word._Document wDocument = Application.Documents[fileName] as Word._Document;
//wDocument.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
ThisAddIn.doc.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
}
catch (Exception exception)
{
}
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
}
Create a Ribbon designer :
public partial class TestRibbon
{
private string friendlyErrorMessage = "An error has occurred inside the Case Manager Outlook Addin";
private void TestRibbon_Load(object sender, RibbonUIEventArgs e)
{
}
public TestRibbon()
: base(Globals.Factory.GetRibbonFactory())
{
InitializeComponent();
try
{
System.Data.DataTable dt = new DBCall().GetData();//Get all menu in word tmenu tab and bind them using following code
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
RibbonButton Field = this.Factory.CreateRibbonButton();
Field.Label = dt.Rows[i][1].ToString();
Field.Tag = i;
Field.ControlSize =
Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge;
Field.Click += Field_Click;
menu1.Items.Add(Field);
}
}
else
{
System.Windows.Forms.MessageBox.Show("No Fields are available in database");
}
}
catch (Exception exception)
{
}
}
/// <summary>
/// Ribbon Button Click Event
/// </summary>
void Field_Click(object sender, RibbonControlEventArgs e)
{
try
{
Microsoft.Office.Interop.Word.Range currentRange = Globals.ThisAddIn.Application.Selection.Range;
currentRange.Text = (sender as RibbonButton).Label;
}
catch (Exception exception)
{
}
}
}
Related
So, I have a win form where I have to search for a string in a text file and display the line number and the entire line if I found the string. The search has to be multithreaded and all the line numbers and the lines must be on a listview. For example if the word "language" is in line number 60 , the listview must display:
60 "the line has the word language"
I have used the background worker in this regard but I am not being able to display the correct line number and the lines. Firstly, one line is being displayed multiple times and secondly, the line number is always coming to be 0. However, when I output the result in Console, the result is correct. I think I am making some error in putting the result into the listview.
Here' s my main form.cs
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// private bool start_cancel;
bool bln = true;
private void StartCancelbtn_Click(object sender, EventArgs e)
{
if (bln)
text2();
else
text1();
bln = !bln;
}
private void text1()
{
StartCancelbtn.Text = "Start";
this.backgroundWorker1.CancelAsync();
}
private void text2()
{
StartCancelbtn.Text = "Cancel";
StartThread();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
System.ComponentModel.BackgroundWorker worker;
worker = (System.ComponentModel.BackgroundWorker)sender;
// Get the Words object and call the main method.
main_work WC = (main_work)e.Argument;
WC.CountWords(worker, e);
if (worker.CancellationPending)
{
e.Cancel = true;
// break;
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
main_work.ReportState state =
(main_work.ReportState)e.UserState;
ListViewItem l1 = new ListViewItem();
l1.Text = state.LinesCounted.ToString();
l1.SubItems.Add(state.line);
listView1.Items.Add(l1);
}
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
MessageBox.Show("Error: " + e.Error.Message);
else if (e.Cancelled)
MessageBox.Show("Word counting canceled.");
else
MessageBox.Show("Finished counting words.");
}
private void StartThread()
{
main_work WC = new main_work();
WC.CompareString = this.searchtext.Text;
WC.SourceFile = this.filenametextbox.Text;
// Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync(WC);
}
private void browsebtn_Click(object sender, EventArgs e)
{
using (OpenFileDialog brw = new OpenFileDialog())
{
if (brw.ShowDialog() == DialogResult.OK)
{
using (StreamReader sr = new StreamReader(brw.FileName))
{
filenametextbox.Text = brw.FileName.ToString();
}
}
}
}
}
}
Here is my main_work class where the actual comparison is happening:
class main_work
{
public class ReportState
{
public int LinesCounted;
public string line;
}
Queue q = new Queue();
public string SourceFile;
public string CompareString;
public string line2 ;
public int linenumber=0;
public int linenumber1 = 0;
int LinesCounted1;
// public string line2;
public void CountWords(
System.ComponentModel.BackgroundWorker worker,
System.ComponentModel.DoWorkEventArgs e)
{
// Initialize the variables.
ReportState state = new ReportState();
string line1 = "";
int elapsedTime = 1;
DateTime lastReportDateTime = DateTime.Now;
if (CompareString == null ||
CompareString == System.String.Empty)
{
MessageBox.Show("Please Enter a string to be searched");
}
else
{
// Open a new stream.
using (System.IO.StreamReader myStream = new System.IO.StreamReader(SourceFile))
{
// Process lines while there are lines remaining in the file.
while (!myStream.EndOfStream)
{
if (worker.CancellationPending)
{
e.Cancel = true;
// break;
}
else
{
line1 = myStream.ReadLine();
line2 = (CountInString(line1, CompareString));
LinesCounted1 = (linenumbercount(line1, CompareString, linenumber1));
// Raise an event so the form can monitor progress.
int compare = DateTime.Compare(
DateTime.Now, lastReportDateTime.AddSeconds(elapsedTime));
if (compare > 0)
{
state.LinesCounted = LinesCounted1;
state.line = line2;
worker.ReportProgress(0, state);
lastReportDateTime = DateTime.Now;
}
System.Threading.Thread.Sleep(1);
}
}
// Report the final count values.
state.LinesCounted = LinesCounted1;
state.line = line1;
worker.ReportProgress(0, state);
lastReportDateTime = DateTime.Now;
}
}
}
private string CountInString(
string SourceString,
string CompareString)
{
if (SourceString.Contains(CompareString))
{
line2 = SourceString;
Console.WriteLine(SourceString);
}
return line2;
}
private int linenumbercount(
string SourceString,
string CompareString,
int linenumber)
{
// Lines = 0;
if (SourceString == null)
{
return 0;
}
if (SourceString.Contains(CompareString))
{
Console.WriteLine(linenumber);
}
linenumber++;
return linenumber;
}
}
Any feedback will be helpful. Please let me know what I am doing wrong and where is it that I am making a mistake as I am new to background worker and multithreading. Thanks.
Am creating a outlook add-in to track mail processing from mailbox. Am wrapping the folders and the items(adding some events into it ) and storing them in a local list to avoid GC clearing all the events after first execution. However still the folder add event only fires once. Not sure what is the problem.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using OutlookNS = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;
using System.Net;
using System.Windows.Forms;
namespace OutlookAuditor
{
public partial class ThisAddIn
{
#region private variables
OutlookNS._NameSpace outNS;
OutlookNS.Explorer explorer;
string profileName = string.Empty;
List<SuperMailFolder> wrappedFolders = new List<SuperMailFolder>();
Logger logger = new Logger();
SuperMailFolder folderToWrap;
#endregion
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
try
{
OutlookNS.Application application = this.Application;
//Get the MAPI namespace
outNS = application.GetNamespace("MAPI");
//Get UserName
string profileName = outNS.CurrentUser.Name;
//Create a new outlook application
//I had to do this because my systems default mail box was ost file other just the below commented line is enough
//OutlookNS.MAPIFolder inbox = outNS.GetDefaultFolder(OutlookNS.OlDefaultFolders.olFolderInbox) as OutlookNS.MAPIFolder;
OutlookNS.MAPIFolder inbox;
OutlookNS.Folders folders = outNS.Folders;
OutlookNS.MAPIFolder selectedFolder = null;
if (folders.Count > 1)
{
List<string> folderNames = new List<string>();
foreach (OutlookNS.Folder folder in folders)
{
folderNames.Add(folder.Name);
}
using (selectMailBox frmSelect = new selectMailBox(folderNames))
{
if (DialogResult.OK == frmSelect.ShowDialog())
{
selectedFolder = folders[frmSelect.SelectedFolder];
}
}
}
else
{
selectedFolder = folders[1];
}
logger.SaveLog("Folder Selected " + selectedFolder.Name);
inbox = selectedFolder.Folders["Inbox"];//as OutlookNS.MAPIFolder;
//Create a super mail folder
folderToWrap = new SuperMailFolder(inbox, profileName);
wrappedFolders.Add(folderToWrap);
wrappedFolders.AddRange(folderToWrap.wrappedSubFolders);
//System.Runtime.InteropServices.Marshal.ReleaseComObject(inbox);
}
catch (Exception ex)
{
logger.WriteException(ex);
}
finally
{
}
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
}
#region SuperMailItem object
class SuperMailItem
{
//local variable for avoiding GC invocation
OutlookNS.MailItem item;
string _profileName;
OutlookAuditor.Common.AuditItem auditItem;
string parentMailID;
string _folderName = string.Empty;
OutlookNS.MailItem replyItem;
Logger logger = new Logger();
//constructor that wraps mail item with required events
internal SuperMailItem(OutlookNS.MailItem MailItemToWrap, string profileName,string folderName)
{
try
{
item = MailItemToWrap as OutlookNS.MailItem;
_folderName = folderName;
if (item is OutlookNS.MailItem)
{
logger.SaveLog(item.Subject);
item.PropertyChange += MailItemToWrap_PropertyChange;
//item.PropertyChange += new OutlookNS.ItemEvents_10_PropertyChangeEventHandler(MailItemToWrap_PropertyChange);
((OutlookNS.ItemEvents_10_Event)item).Reply += SuperMailItem_Reply;
}
}
catch(Exception ex)
{
logger.WriteException(ex,"SuperMailItem Constructor");
}
}
void SuperMailItem_Reply(object Response, ref bool Cancel)
{
try
{
parentMailID = string.Empty;
replyItem = Response as OutlookNS.MailItem;
((OutlookNS.ItemEvents_10_Event)replyItem).Send += SuperMailItem_Send;
}
catch(Exception ex)
{
logger.WriteException(ex);
}
}
//this event is not firing
void SuperMailItem_Send(ref bool Cancel)
{
try
{
if (!Cancel)
{
createAuditItem();
auditItem.ActionDescription = "REPLY_SENT";
SaveLog();
}
}
catch(Exception ex)
{
logger.WriteException(ex);
}
}
//property change event- fires when any property of a mail item changes
void MailItemToWrap_PropertyChange(string Name)
{
try
{
createAuditItem();
//We are interested in UnRead property, if this property changes audit.
if (Name == "UnRead")
{
if (!item.UnRead)
{
auditItem.ActionDescription = "MAIL_READ";
}
else
{
auditItem.ActionDescription = "MAIL_UNREAD";
}
}
SaveLog();
}
catch(Exception ex)
{
logger.WriteException(ex);
}
}
void createAuditItem()
{
auditItem = new Common.AuditItem();
auditItem.ActionTimestamp = DateTime.Now;
auditItem.EntryID = item.EntryID;
auditItem.ProfileName = _profileName;
auditItem.ReceivedTimestamp = item.ReceivedTime;
auditItem.SystemIP = Helper.SystemIP();
auditItem.UserName = Helper.UserID();
auditItem.OriginalMailSentBy = item.Sender.Name;
auditItem.FolderName = _folderName;
auditItem.Subject = item.Subject;
}
void SaveLog()
{
Logger logger = new Logger();
logger.Save(auditItem);
}
}
#endregion
#region SuperMailFolder object
class SuperMailFolder
{
#region private variables
OutlookNS.MAPIFolder _wrappedFolder;
string _profileName;
List<SuperMailItem> wrappedItems = new List<SuperMailItem>();
public List<SuperMailFolder> wrappedSubFolders = new List<SuperMailFolder>();
string folderName = string.Empty;
Logger logger = new Logger();
#endregion
#region constructor
internal SuperMailFolder(OutlookNS.MAPIFolder folder, string profileName)
{
try
{
//assign it to local private master
_wrappedFolder = folder;
folderName = folder.Name;
_profileName = profileName;
//assign event handlers for the folder
_wrappedFolder.Items.ItemAdd +=Items_ItemAdd;
_wrappedFolder.Items.ItemRemove += Items_ItemRemove;
refreshItemList();
//Go through all the subfolders and wrap them as well
foreach (OutlookNS.MAPIFolder tmpFolder in _wrappedFolder.Folders)
{
logger.SaveLog("Wrapping folder " + tmpFolder.Name);
SuperMailFolder tmpWrapFolder = new SuperMailFolder(tmpFolder, _profileName);
wrappedSubFolders.Add(tmpWrapFolder);
wrappedSubFolders.AddRange(tmpWrapFolder.wrappedSubFolders);
}
}
catch(Exception ex)
{
logger.WriteException(ex);
}
}
#endregion
void Items_ItemRemove()
{
refreshItemList();
}
#region Handler of addition item into a folder
void Items_ItemAdd(object Item)
{
try
{
if (Item is OutlookNS.MailItem)
{
OutlookNS.MailItem item = Item as OutlookNS.MailItem;
wrappedItems.Add(new SuperMailItem(item, _profileName, folderName));
logger.SaveLog("Adding new item. New collection count:" + wrappedItems.Count.ToString());
OutlookAuditor.Common.AuditItem auditItem = new Common.AuditItem();
auditItem.ActionTimestamp = DateTime.Now;
auditItem.EntryID = item.EntryID;
auditItem.ProfileName = _profileName;
auditItem.ReceivedTimestamp = item.ReceivedTime;
auditItem.SystemIP = Helper.SystemIP();
auditItem.UserName = Helper.UserID();
auditItem.ActionDescription = "FOLDER_ADD";
auditItem.FolderName = folderName;
auditItem.OriginalMailSentBy = item.Sender.Name;
auditItem.Subject = item.Subject;
logger.Save(auditItem);
}
}
catch(Exception ex)
{
logger.WriteException(ex);
}
}
void refreshItemList()
{
try
{
wrappedItems.Clear();
wrappedItems = new List<SuperMailItem>();
logger.SaveLog("Wrapping items in " + folderName);
//Go through all the items and wrap it.
foreach (OutlookNS.MailItem item in _wrappedFolder.Items)
{
try
{
if (item is OutlookNS.MailItem)
{
OutlookNS.MailItem mailItem = item as OutlookNS.MailItem;
SuperMailItem wrappedItem = new SuperMailItem(mailItem, _profileName, folderName);
wrappedItems.Add(wrappedItem);
}
}
catch (Exception ex)
{
logger.WriteException(ex);
}
}
logger.SaveLog("Wrapped items in " + folderName + ":" + wrappedItems.Count.ToString());
}
catch(Exception ex)
{
logger.WriteException(ex);
}
}
#endregion
}
#endregion
static class Helper
{
public static string SystemIP()
{
string hostName = Dns.GetHostName();
string hostAddress = Dns.GetHostByName(hostName).AddressList[0].ToString();
return hostAddress;
}
public static string UserID()
{
return System.Security.Principal.WindowsIdentity.GetCurrent().Name;
}
}
}
The following code is the problem:
_wrappedFolder.Items.ItemAdd +=Items_ItemAdd;
_wrappedFolder.Items.ItemRemove += Items_ItemRemove;
The object that fires the events must be alive - in your case you set up an event handler on an implicit variable returned from the _wrappedFolder.Items property - as soon as the GC releases that implicit variable, no events will fire. Declare the Items object on the class level to make sure it stays referenced and alive.
C# .net 3.5 Winforms application.
So here is the situation. I have a form that runs some code to that opens another forms in another thread. When that form opens, it performs certain tasks and then needs to close if those conditions are met. Problem is, it keeps throwing this exception and I have NO idea why.
]1)
Here are my snippets of code used in all this.:
Here is the function that opens the form in another thread: Program.cs
public static void new_downloader_thread()
{
Thread t = new Thread(new ThreadStart(open_downloader));
t.SetApartmentState(ApartmentState.STA);
if (Open_Downloader)
{
t.Start();
}
}
public static void open_downloader()
{
try
{
Application.Run(new DownloadInstall());
}
catch (Exception e)
{
MessageBox.Show(Convert.ToString(e));
}
}
Here is the code from the form that opens the form giving me the trouble: Manager.cs
private void new_System_Click(object sender, EventArgs e)
{
if (Program.Open_Downloader == false)
{
Program.Current_Download = "newsys.exe";
Program.Open_Downloader = true;
Program.new_downloader_thread();
}
else
{
download_busy();
}
}
Here is the form that is opening: DownloadInstall.cs
public partial class DownloadInstall : Form
{
/// Opening Declarations
private static System.Net.WebClient web_client;
private static System.Diagnostics.Stopwatch stop_watch;
private static bool downloading { get; set; }
private static bool is_name_update { get; set; }
private static int download_state { get; set; }
private static int elapsed { get; set; }
private static int opening { get; set; }
//private static int counter;
/// --------------------
public DownloadInstall()
{
InitializeComponent();
is_name_update = false;
downloading = false;
opening = 0;
web_client = new System.Net.WebClient();
web_client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(Download_Progress);
web_client.DownloadFileCompleted += new AsyncCompletedEventHandler(Download_Complete);
stop_watch = new System.Diagnostics.Stopwatch();
/// Keypress event call and blanking out the box text.
this.name_update_field.Text = "";
this.name_update_field.KeyPress += new KeyPressEventHandler(no_period);
/// --------------------------------------------------
/// Changes the text to what file we are downloading.
this.file_name.Text = string.Format("Downloading {0}", Program.Current_Download);
/// -------------------------------------------------
/// Sets a forms closed event handler
this.FormClosing += new FormClosingEventHandler(Download_Window_Closing);
/// ---------------------------------
/// Creates folder where files are to be downloaded and deletes any residual files.
try
{
System.IO.Directory.CreateDirectory(#"C:\Downloads");
}
catch
{
}
if (System.IO.File.Exists(string.Format(#"C:\Downloads\{0}", Program.Current_Download)))
{
try
{
System.IO.File.Delete(string.Format(#"C:\Downloads\{0}", Program.Current_Download));
}
catch
{
if (Program.Disconnecting == false)
{
opening = 1;
}
}
}
/// -------------------------------------------------------------------------------
switch (opening)
{
/// Case 0 Starts the download or name update code normally.
case 0:
if (Program.Current_Download == "Name Update")
{
file_name.Text = "Name Update Downloader";
is_name_update = true;
this.restart_or_start.Text = "Start";
this.cid.Visible = true;
this.name_update_field.ReadOnly = false;
this.name_update_field.Visible = true;
}
else
{
Download_Begin();
}
break;
/// Case 1 will close the downloader.
case 1:
MessageBox.Show("It is possible this file was already downloaded and is already open on this computer.", "Hmmmmm...", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
this.Close();
break;
}
}
/// Function that is called when the window is closed.
private void Download_Window_Closing(object sender, FormClosingEventArgs e)
{
if (downloading)
{
web_client.CancelAsync();
}
Program.Current_Download = "";
Program.Open_Downloader = false;
}
/// --------------------------------------------------
Not sure why this is throwing the exception. It seems if I remove code that closes the form, it works, and I can close the form properly from other parts of the code. Any help would be great!
Solved!!! The problem is when trying to close the form before it has finished construction.
Changed:
this.Close();
to:
Load += (s, e) => Close();
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.