Process.GetCurrentProcess().MainWindowTitle of Revit retrieves empty string "" - c#

I am creating a plugin for Revit that registers several events within its application.
For every time an event happens, a line is writen on a txt file telling me about the event such as:
The user opened a document on Autodesk Revit 2019 (...)
I am obtaining the "Autodesk Revit 2019" (name of application) by getting the name of the MainWindowTitle of the application like so: Process.GetCurrentProcess().MainWindowTitle
public static string originalString = Process.GetCurrentProcess().MainWindowTitle;
(...)
Trace.WriteLine("O utilizador " + Environment.UserName + " abriu o " + originalString + " a " + DateTime.Now + " (ApplicationInitializedEventArgs)");
Which writes in the txt file:
O utilizador rita.aguiar abriu o a 20/09/2018 10:36:42 (ApplicationInitializedEventArgs)
As you can read, it did not write on the txt file "Autodesk Revit 2019 - [Home]" between the words "o" and "a" as I hoped for.
If I had writen Process.GetCurrentProcess().MainWindowTitle directly on the Trace.WriteLine I would have obtained "Autodesk Revit 2019 - [Home]", but I wish to write an assigned name instead.
How to successfully write "Autodesk Revit 2019 - [Home]" by assigning a name to Process.GetCurrentProcess().MainWindowTitle?
Later I would like to obtain this name by instead getting just Autodesk Revit 2019 like so:
public static string originalString = Process.GetCurrentProcess().MainWindowTitle;
public static string[] splittedString = originalString.Split("-".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
public static string AppName = splittedString[0];
Any help would be appretiated!

As I suggested answering your similar question on assigning a name to a string C# in the Revit API discussion forum, I would look at the code executing step by step in the debugger.
Then you can see for yourself exactly what is going on.
You could also add some more intermediate lines and variables for absolute clarity:
string originalString = Process
.GetCurrentProcess()
.MainWindowTitle;
string s2 = "O utilizador "
+ Environment.UserName
+ " abriu um documento no "
+ originalString + " a " + DateTime.Now;
//or use string interpolation:
//https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
string s3 = $"O utilizador {Environment.UserName} abriu um documento no {originalString} a {DateTime.Now}";
Trace.WriteLine( s2 );
Trace.WriteLine( s3 );
The debugger is good!
Invaluable, in fact.

Some of the comments on the discussion how to determine Revit demo mode show how you can access the Revit main window title.

To be able to store the Main Window Title in a name of type string I had to first declare each string outsite of the methods I am using:
string originalString;
string[] splittedString;
string AppName;
After declaring each string name I obtained the Application Name "Autodesk Revit 2019" by including each definition inside the first private method, which was created to register when the Revit application is opened. This had to be done inside a method because it is only after the application is launched that we can access the MainWindowTitle. This is the reason why I was getting an empty string "" when trying to obtain the MainWindowTitle the moment the application is starting to launch, but before it has completely launched and thus opened a Window with such Title.
private void DumpEventArgs(ApplicationInitializedEventArgs args_initialized)
{
originalString = Process.GetCurrentProcess().MainWindowTitle;
splittedString = originalString.Split(new[] { " -" }, StringSplitOptions.RemoveEmptyEntries);
AppName = splittedString[0];
//StreamWriter file = new StreamWriter("C://Users//" + Environment.UserName + "//AppData//Roaming//Autodesk//" + Environment.UserName + ".txt", append: true);
//MessageBox.Show($"O utilizador {Environment.UserName} iniciou o {AppName} a {DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")}");
file.WriteLine($"{Environment.UserName},{DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")},{AppName},iniciar");
}
And I could use this same string later when required because it has been declared outside the method, for example here I needed to write AppName again:
private void DumpEventArgs(DocumentSavedEventArgs args_saved)
{
//StreamWriter file = new StreamWriter("C://Users//" + Environment.UserName + "//AppData//Roaming//Autodesk//" + Environment.UserName + ".txt", append: true);
//MessageBox.Show($"O utilizador {Environment.UserName} guardou um documento no {AppName} a {DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")}");
file.WriteLine($"{Environment.UserName},{DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")},{AppName},guardar");
}
Finally AppName retrieves what I wanted: "Autodesk Revit 2019".

Related

"Given Path Format Is Not Supported"... Can you help me?

So, I made a speech recognizer and it was working fine, I'm not sure why is it giving me this error right now. Any ideas?
String res = e.Result.Text;
string yol = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
string settings = ("#" + yol + "\\" + "settings" + "\\");
if (res == "Hi Bot")
{
pictureBox1.Image = Image.FromFile(settings + "mybot.png"); -->That's where i get the error
say(greetings_random());
}
string yol = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
string settings = ("#" + yol + "\\" + "settings" + "\\");
This means that settings has the value "#C:\Path\To\Executable\settings\".
That's probably not what you want -- I'm not sure what the # is trying to achieve, but it's not valid at the beginning of a path like that.
For future, debugging this code and inspecting the settings variable would quickly have shown the problem.
That said, it's recommended to use Path.Join (.NET Core 2.1+) or Path.Combine instead of string concatenation to create paths like this.

MS Project get name current project

For my project, i need to get the name of my current active document file of my ms project. But i can't find the function for get the file name...
someone know how te get the file name ?
I Use this :
Microsoft.Office.Interop.MSProject;
From my VSTO add-in named thisAddIn, I accessed the project file information with this little example function (activated by a ribbon button)
private void showFileAndPath_Click(object sender, RibbonControlEventArgs e)
{
var name = Globals.ThisAddIn.Application.ActiveProject.Name;
var path = Globals.ThisAddIn.Application.ActiveProject.Path;
var fullName = Globals.ThisAddIn.Application.ActiveProject.FullName;
System.Windows.Forms.MessageBox.Show(
"name: " + name + Environment.NewLine +
"path: " + path + Environment.NewLine +
"fullName: " + fullName);
}

Creating a new directory in c#

I would like to first create a new dir and then save a file into the following location C:\Users\Paul\Documents + \newfolder\nameOffile.xml.
Can this be achieved in C#. I currently have the following code but i cant seem to get it to work
XDocument doc = new XDocument(rootNode);
var dateAndTime = DateTime.Now;
var date = dateAndTime.Date.ToString("dd-MM-yyyy");
var patWithoutExtension = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
string savedFilePah = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
var savedFile = savedFilePah + "/" + Directory.CreateDirectory("newFolder") + "/" + patWithoutExtension + "_" + date + ".xml";
//var savedFile = "C:/tmp/" + patWithoutExtension + "_" + date + ".xml";
doc.Save(savedFile);
lblFileUploaded.Text = "Success!";
it keeps failing on the doc.save with the following error
An unhandled exception of type 'System.IO.DirectoryNotFoundException'
occurred in System.Xml.dll
Additional information: Could not find a part of the path
'C:\Users\Paul\Documents\newFolder\test2_29-03-2015.xml'.
The problem seems to be with Directory.CreateDirectory("newFolder") which will create the folder under the working directory rather than under C:\Users\Paul\Documents.
Also, as a good practice I would advice to store the newly created folder in a dedicated folder. The advantages of this are twofold - you'll be able to watch this variable easily during debugging thus find out the exact location of the created folder and also, if an exception will be thrown you'll know the exact location of it.
Also, some Windows APIs might not accept a forward slash ('/') but will except a backslash ('\').
You must specify the full path to the directory you want to create, otherwise it's created at the working (running) folder:
string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var myDir = Path.Combine(myDocs, "newFolder");
Directory.CreateDirectory(myDir);
var savedFile = Path.Combine(myDir, patWithoutExtension + "_" + date + ".xml");
This Directory.CreateDirectory("newFolder") is not creating the directory inside your Users folder: you're just passing it "newFolder", so it doesn't know that's where you want the folder. It will be creating it in your current working folder (e.g. bin/Debug).
Try passing the entire path to CreateDirectory:
string savedFilePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"newFolder");
Directory.CreateDirectory(savedFilePath);

Tesseract OCR simple example

Hi Can you anyone give me a simple example of testing Tesseract OCR
preferably in C#.
I tried the demo found here.
I download the English dataset and unzipped in C drive. and modified the code as followings:
string path = #"C:\pic\mytext.jpg";
Bitmap image = new Bitmap(path);
Tesseract ocr = new Tesseract();
ocr.SetVariable("tessedit_char_whitelist", "0123456789"); // If digit only
ocr.Init(#"C:\tessdata\", "eng", false); // To use correct tessdata
List<tessnet2.Word> result = ocr.DoOCR(image, Rectangle.Empty);
foreach (tessnet2.Word word in result)
Console.WriteLine("{0} : {1}", word.Confidence, word.Text);
Unfortunately the code doesn't work. the program dies at "ocr.Init(..." line. I couldn't even get an exception even using try-catch.
I was able to run the vietocr! but that is a very large project for me to follow. i need a simple example like above.
Ok. I found the solution here
tessnet2 fails to load
the Ans given by Adam
Apparently i was using wrong version of tessdata. I was following the the source page instruction intuitively and that caused the problem.
it says
Quick Tessnet2 usage
Download binary here, add a reference of the assembly Tessnet2.dll to your .NET project.
Download language data definition file here and put it in tessdata directory. Tessdata directory and your exe must be in the
same directory.
After you download the binary, when you follow the link to download the language file, there are many language files. but none of them are right version. you need to select all version and go to next page for correct version (tesseract-2.00.eng)! They should either update download binary link to version 3 or put the the version 2 language file on the first page. Or at least bold mention the fact that this version issue is a big deal!
Anyway I found it.
Thanks everyone.
A simple example of testing Tesseract OCR in C#:
public static string GetText(Bitmap imgsource)
{
var ocrtext = string.Empty;
using (var engine = new TesseractEngine(#"./tessdata", "eng", EngineMode.Default))
{
using (var img = PixConverter.ToPix(imgsource))
{
using (var page = engine.Process(img))
{
ocrtext = page.GetText();
}
}
}
return ocrtext;
}
Info: The tessdata folder must exist in the repository: bin\Debug\
I was able to get it to work by following these instructions.
Download the sample code
Unzip it to a new location
Open ~\tesseract-samples-master\src\Tesseract.Samples.sln (I used Visual Studio 2017)
Install the Tesseract NuGet package for that project (or uninstall/reinstall as I had to)
Uncomment the last two meaningful lines in Tesseract.Samples.Program.cs:
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
Run (hit F5)
You should get this windows console output
Try updating the line to:
ocr.Init(#"C:\", "eng", false); // the path here should be the parent folder of tessdata
I had same problem, now its resolved. I have tesseract2, under this folders for 32 bit and 64 bit, I copied files 64 bit folder(as my system is 64 bit) to main folder ("Tesseract2") and under bin/Debug folder. Now my solution is working fine.
In my case I had all these worked except for the correct character recognition.
But you need to consider these few things:
Use correct tessnet2 library
use correct tessdata language version
tessdata should be somewhere out of your application folder where you can put in full path in the init parameter. use ocr.Init(#"c:\tessdata", "eng", true);
Debugging will cause you headache. Then you need to update your app.config
use this. (I can't put the xml code here. give me your email i will email it to you)
hope that this helps
Here's a great working example project; Tesseract OCR Sample (Visual Studio) with Leptonica Preprocessing
Tesseract OCR Sample (Visual Studio) with Leptonica Preprocessing
Tesseract OCR 3.02.02 API can be confusing, so this guides you through including the Tesseract and Leptonica dll into a Visual Studio C++ Project, and provides a sample file which takes an image path to preprocess and OCR. The preprocessing script in Leptonica converts the input image into black and white book-like text.
Setup
To include this in your own projects, you will need to reference the header files and lib and copy the tessdata folders and dlls.
Copy the tesseract-include folder to the root folder of your project. Now Click on your project in Visual Studio Solution Explorer, and go to Project>Properties.
VC++ Directories>Include Directories:
..\tesseract-include\tesseract;..\tesseract-include\leptonica;$(IncludePath)
C/C++>Preprocessor>Preprocessor Definitions:
_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)
C/C++>Linker>Input>Additional Dependencies:
..\tesseract-include\libtesseract302.lib;..\tesseract-include\liblept168.lib;%(AdditionalDependencies)
Now you can include headers in your project's file:
include
include
Now copy the two dll files in tesseract-include and the tessdata folder in Debug to the Output Directory of your project.
When you initialize tesseract, you need to specify the location of the parent folder (!important) of the tessdata folder if it is not already the current directory of your executable file. You can copy my script, which assumes tessdata is installed in the executable's folder.
tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
api->Init("D:\tessdataParentFolder\", ...
Sample
You can compile the provided sample, which takes one command line argument of the image path to use. The preprocess() function uses Leptonica to create a black and white book-like copy of the image which makes tesseract work with 90% accuracy. The ocr() function shows the functionality of the Tesseract API to return a string output. The toClipboard() can be used to save text to clipboard on Windows. You can copy these into your own projects.
This worked for me, I had 3-4 more PDF to Text extractor and if one doesnot work the other one will ... tesseract in particular this code can be used on Windows 7, 8, Server 2008 . Hope this is helpful to you
do
{
// Sleep or Pause the Thread for 1 sec, if service is running too fast...
Thread.Sleep(millisecondsTimeout: 1000);
Guid tempGuid = ToSeqGuid();
string newFileName = tempGuid.ToString().Split('-')[0];
string outputFileName = appPath + "\\pdf2png\\" + fileNameithoutExtension + "-" + newFileName +
".png";
extractor.SaveCurrentImageToFile(outputFileName, ImageFormat.Png);
// Create text file here using Tesseract
foreach (var file in Directory.GetFiles(appPath + "\\pdf2png"))
{
try
{
var pngFileName = Path.GetFileNameWithoutExtension(file);
string[] myArguments =
{
"/C tesseract ", file,
" " + appPath + "\\png2text\\" + pngFileName
}; // /C for closing process automatically whent completes
string strParam = String.Join(" ", myArguments);
var myCmdProcess = new Process();
var theProcess = new ProcessStartInfo("cmd.exe", strParam)
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
WindowStyle = ProcessWindowStyle.Minimized
}; // Keep the cmd.exe window minimized
myCmdProcess.StartInfo = theProcess;
myCmdProcess.Exited += myCmdProcess_Exited;
myCmdProcess.Start();
//if (process)
{
/*
MessageBox.Show("cmd.exe process started: " + Environment.NewLine +
"Process Name: " + myCmdProcess.ProcessName +
Environment.NewLine + " Process Id: " + myCmdProcess.Id
+ Environment.NewLine + "process.Handle: " +
myCmdProcess.Handle);
*/
Process.EnterDebugMode();
//ShowWindow(hWnd: process.Handle, nCmdShow: 2);
/*
MessageBox.Show("After EnterDebugMode() cmd.exe process Exited: " +
Environment.NewLine +
"Process Name: " + myCmdProcess.ProcessName +
Environment.NewLine + " Process Id: " + myCmdProcess.Id
+ Environment.NewLine + "process.Handle: " +
myCmdProcess.Handle);
*/
myCmdProcess.WaitForExit(60000);
/*
MessageBox.Show("After WaitForExit() cmd.exe process Exited: " +
Environment.NewLine +
"Process Name: " + myCmdProcess.ProcessName +
Environment.NewLine + " Process Id: " + myCmdProcess.Id
+ Environment.NewLine + "process.Handle: " +
myCmdProcess.Handle);
*/
myCmdProcess.Refresh();
Process.LeaveDebugMode();
//myCmdProcess.Dispose();
/*
MessageBox.Show("After LeaveDebugMode() cmd.exe process Exited: " +
Environment.NewLine);
*/
}
//process.Kill();
// Waits for the process to complete task and exites automatically
Thread.Sleep(millisecondsTimeout: 1000);
// This works fine in Windows 7 Environment, and not in Windows 8
// Try following code block
// Check, if process is not comletey exited
if (!myCmdProcess.HasExited)
{
//process.WaitForExit(2000); // Try to wait for exit 2 more seconds
/*
MessageBox.Show(" Process of cmd.exe was exited by WaitForExit(); Method " +
Environment.NewLine);
*/
try
{
// If not, then Kill the process
myCmdProcess.Kill();
//myCmdProcess.Dispose();
//if (!myCmdProcess.HasExited)
//{
// myCmdProcess.Kill();
//}
MessageBox.Show(" Process of cmd.exe exited ( Killed ) successfully " +
Environment.NewLine);
}
catch (System.ComponentModel.Win32Exception ex)
{
MessageBox.Show(
" Exception: System.ComponentModel.Win32Exception " +
ex.ErrorCode + Environment.NewLine);
}
catch (NotSupportedException notSupporEx)
{
MessageBox.Show(" Exception: NotSupportedException " +
notSupporEx.Message +
Environment.NewLine);
}
catch (InvalidOperationException invalidOperation)
{
MessageBox.Show(
" Exception: InvalidOperationException " +
invalidOperation.Message + Environment.NewLine);
foreach (
var textFile in Directory.GetFiles(appPath + "\\png2text", "*.txt",
SearchOption.AllDirectories))
{
loggingInfo += textFile +
" In Reading Text from generated text file by Tesseract " +
Environment.NewLine;
strBldr.Append(File.ReadAllText(textFile));
}
// Delete text file after reading text here
Directory.GetFiles(appPath + "\\pdf2png").ToList().ForEach(File.Delete);
Directory.GetFiles(appPath + "\\png2text").ToList().ForEach(File.Delete);
}
}
}
catch (Exception exception)
{
MessageBox.Show(
" Cought Exception in Generating image do{...}while{...} function " +
Environment.NewLine + exception.Message + Environment.NewLine);
}
}
// Delete png image here
Directory.GetFiles(appPath + "\\pdf2png").ToList().ForEach(File.Delete);
Thread.Sleep(millisecondsTimeout: 1000);
// Read text from text file here
foreach (var textFile in Directory.GetFiles(appPath + "\\png2text", "*.txt",
SearchOption.AllDirectories))
{
loggingInfo += textFile +
" In Reading Text from generated text file by Tesseract " +
Environment.NewLine;
strBldr.Append(File.ReadAllText(textFile));
}
// Delete text file after reading text here
Directory.GetFiles(appPath + "\\png2text").ToList().ForEach(File.Delete);
} while (extractor.GetNextImage()); // Advance image enumeration...
Admittedly this is an older question when Tesseract 3 was the version available, but it came up in my search results while looking for a related issue and the question, and other answers, highlight the still valid issue of the difficulty of actually getting Tesseract installed, let alone configuring it to work correctly.
There is a far simpler solution (and using the updated Tesseract 5 engine) which does all the work for you, in IronOcr.
(Disclaimer: I do work for Iron Software, though I feel that others can benefit from this information, particularly as it relates to the question of using Tesseract OCR in C# which IronOcr excels at).
using IronOcr;
var Ocr = new IronTesseract(); // nothing to configure
Ocr.Configuration.WhiteListCharacters = "0123456789"; // If digit only
using (var Input = new OcrInput(#"example.tiff"))
{
OcrResult Result = Ocr.Read(Input);
foreach (var Page in Result.Pages)
{
// Page object
int PageNumber = Page.PageNumber;
string PageText = Page.Text;
int PageWordCount = Page.WordCount;
// null if we dont set Ocr.Configuration.ReadBarCodes = true;
OcrResult.Barcode[] Barcodes = Page.Barcodes;
System.Drawing.Bitmap PageImage = Page.ToBitmap(Input);
int PageWidth = Page.Width;
int PageHeight = Page.Height;
foreach (var Paragraph in Page.Paragraphs)
{
// Pages -> Paragraphs
int ParagraphNumber = Paragraph.ParagraphNumber;
String ParagraphText = Paragraph.Text;
System.Drawing.Bitmap ParagraphImage = Paragraph.ToBitmap(Input);
int ParagraphX_location = Paragraph.X;
int ParagraphY_location = Paragraph.Y;
int ParagraphWidth = Paragraph.Width;
int ParagraphHeight = Paragraph.Height;
double ParagraphOcrAccuracy = Paragraph.Confidence;
OcrResult.TextFlow paragrapthText_direction = Paragraph.TextDirection;
foreach (var Line in Paragraph.Lines)
{
// Pages -> Paragraphs -> Lines
int LineNumber = Line.LineNumber;
String LineText = Line.Text;
System.Drawing.Bitmap LineImage = Line.ToBitmap(Input); ;
int LineX_location = Line.X;
int LineY_location = Line.Y;
int LineWidth = Line.Width;
int LineHeight = Line.Height;
double LineOcrAccuracy = Line.Confidence;
double LineSkew = Line.BaselineAngle;
double LineOffset = Line.BaselineOffset;
foreach (var Word in Line.Words)
{
// Pages -> Paragraphs -> Lines -> Words
int WordNumber = Word.WordNumber;
String WordText = Word.Text;
System.Drawing.Image WordImage = Word.ToBitmap(Input);
int WordX_location = Word.X;
int WordY_location = Word.Y;
int WordWidth = Word.Width;
int WordHeight = Word.Height;
double WordOcrAccuracy = Word.Confidence;
if (Word.Font != null)
{
// Word.Font is only set when using Tesseract Engine Modes rather than LTSM
String FontName = Word.Font.FontName;
double FontSize = Word.Font.FontSize;
bool IsBold = Word.Font.IsBold;
bool IsFixedWidth = Word.Font.IsFixedWidth;
bool IsItalic = Word.Font.IsItalic;
bool IsSerif = Word.Font.IsSerif;
bool IsUnderLined = Word.Font.IsUnderlined;
bool IsFancy = Word.Font.IsCaligraphic;
}
foreach (var Character in Word.Characters)
{
// Pages -> Paragraphs -> Lines -> Words -> Characters
int CharacterNumber = Character.CharacterNumber;
String CharacterText = Character.Text;
System.Drawing.Bitmap CharacterImage = Character.ToBitmap(Input);
int CharacterX_location = Character.X;
int CharacterY_location = Character.Y;
int CharacterWidth = Character.Width;
int CharacterHeight = Character.Height;
double CharacterOcrAccuracy = Character.Confidence;
// Output alternative symbols choices and their probability.
// Very useful for spellchecking
OcrResult.Choice[] Choices = Character.Choices;
}
}
}
}
}
}

C# / Webservice app on server throwing strange exception

We use ADP for employee information. I had to create a small app that called some web services that ADP has to pull employee information. The app is fairly procedural..not really object orientated in a sense. Basically I go through some web services to pull general information, work information, employee status, etc.
I have most of this data writing out to a text file as a log so I can ensure that everything is working correctly. Finally got it all done, and it works perfect on my local machine. Thought I'd just copy the entire structure onto a server and use windows scheduler to schedule the exe to run nightly (once a day). When it tries to run the app it looks like it is dying when it calls the first web service. The task scheduler log says:
""ADP.job" (ADP.exe)
Started 2/11/2010 2:14:34 PM
"ADP.job" (ADP.exe)
Finished 2/11/2010 2:14:38 PM
Result: The task completed with an exit code of (e0434f4d)."
So I checked the event viewer and it says this:
EventType clr20r3, P1 adp.exe, P2 1.0.0.0, P3 4b745bb9, P4 adp, P5 1.0.0.0, P6 4b745bb9, P7 289, P8 2d, P9 system.io.filenotfoundexception, P10 NIL.
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
I put in some console.writelines to see where it is failing...
Here is a simple example of main:
static void Main(string[] args)
{
OpenTextFile();
Console.WriteLine("About to process employee work information...");
tw.WriteLine("About to process employee work information...");
//work info service
EmpWorkInfo();
}
And inside of opentextfile:
public static void OpenTextFile()
{
//used to log data
String sLogName;
Console.WriteLine("Inside of opentextfile");
if (Directory.Exists(logPath))
{
//directory exists
}
else
{
Directory.CreateDirectory(logPath);
}
Console.WriteLine("Inside of opentextfile2");
sLogName = "log_" + DateTime.Today.ToString("MM_dd_yyyy") + ".txt";
tw = new StreamWriter(logPath + sLogName);
}
I see all the console.writelines on the server but as soon as it hits this line from main:
EmpWorkInfo();
Thats when all hell breaks lose (basically it doesn't work). The EmpWorkInfo() is simply a function to get work related information from a web service (as I said this works locally).
static void EmpWorkInfo()
{
Console.Writeline("THIS NEVER PRINTS!!!");
SQLClass s=null;
// Create the web service proxy client.
GetEmployeeWorkInfoService oService = new GetEmployeeWorkInfoService();
oService.Timeout = Int32.MaxValue;
// Serialize the UsernameToken into XML.
// Create the UsernameToken as defined in the WS-I secure profile.
UsernameToken oUsernameToken = new UsernameToken(USERNAME, SECRET);
System.Xml.XmlElement oSecurityHeaderXml =
oUsernameToken.GetXml(new System.Xml.XmlDocument());
ADP.GetEmployeeWorkInfoWebService.SecurityHeaderType oSecurityHeader = new ADP.GetEmployeeWorkInfoWebService.SecurityHeaderType();
oSecurityHeader.Any = new System.Xml.XmlElement[] { oSecurityHeaderXml };
oService.Security = oSecurityHeader;
GetEmployeeWorkInfoRequestFilter oFilter = new GetEmployeeWorkInfoRequestFilter();
//filter by thyssenkrupp company
oFilter.Companies = new String[] { COMPANY_IDENTIFIER };
GetEmployeeWorkInfoRequest oRequest = new GetEmployeeWorkInfoRequest();
oRequest.Filter = oFilter;
try
{
EmployeeWorkInfoType[] arPersonalInfo = oService.GetEmployeeWorkInfo(oRequest);
try
{
s = new SQLClass();
}
catch (Exception e)
{
throw new System.Exception(e.Message.ToString());
}
for (int i = 0; i < arPersonalInfo.Length; i++)
{
String stID = arPersonalInfo[i].EmployeeKey.Identifier.EmployeeId; //employee number
String stEmailAddress = arPersonalInfo[i].WorkInfo.EmailAddress; //employee email address (work)
String stFax = arPersonalInfo[i].WorkInfo.Fax; //employee fax number
DateTime dtHireDate = arPersonalInfo[i].WorkInfo.OriginalHireDate;
String stPhone = arPersonalInfo[i].WorkInfo.Phone; //employee phone number
String stWireless = arPersonalInfo[i].WorkInfo.Wireless; //employee wireless number
tw.WriteLine("Processing ID:" + stID + " Email Work: " + stEmailAddress + " Fax Work: " + stFax + " Hire Date: " + dtHireDate + " Phone Work: " + stPhone + " Wireless Work: " + stWireless + ".");
Console.WriteLine("Processing ID:" + stID + " Email Work: " + stEmailAddress + " Fax Work: " + stFax + " Hire Date: " + dtHireDate + " Phone Work: " + stPhone + " Wireless Work: " + stWireless + ".");
s.SetSQLCommand("dbo.ADP_uiEmployeeWorkInfo");
s.AddSQLCmdParameter("#EmployeeNumber", System.Data.SqlDbType.VarChar, stID);
s.AddSQLCmdParameter("#EmailAddress", System.Data.SqlDbType.VarChar, stEmailAddress);
s.AddSQLCmdParameter("#Fax", System.Data.SqlDbType.VarChar, stFax);
s.AddSQLCmdParameter("#HireDate", System.Data.SqlDbType.DateTime, dtHireDate);
s.AddSQLCmdParameter("#Telephone", System.Data.SqlDbType.VarChar, stPhone);
s.AddSQLCmdParameter("#Mobile", System.Data.SqlDbType.VarChar, stWireless);
s.SQLExecuteNonQuery();
Console.WriteLine("Processed ID:" + stID + " Email Work: " + stEmailAddress + " Fax Work: " + stFax + " Hire Date: " + dtHireDate + " Phone Work: " + stPhone + " Wireless Work: " + stWireless + ".");
Console.WriteLine(Environment.NewLine);
}
s.CloseSQLDB();
s.Dispose();
}
//catch any exception from adp side.
catch (Exception e)
{
throw new System.Exception(e.Message.ToString());
}
}
This functions code is irrelevant (its ugly but do not let that bother you, the code works...). My issue is I cannot even get to the first console.writeline of that function. Is there anything special I need to do when it comes to working with webservices?
Edit
Logpath is defined as simply a static string outside of main:
private static string logPath = Environment.CurrentDirectory + "\\log\\";
I suspect that your application is not able to load the types referenced in that function - EmpWorkInfo.
1) Can you run this application on the target server in a commannd window (cmd.exe) ?
2) Are you using any assemblies from ADP that are installed in the global assembly cache (GAC)? Run "gacutil -l" on your localmachine to see if you are using any assemblies from ADP that are installed in thr gac. If they are, you will need to install these into the machine on which you are running the app.
Does logPath have a trailing backslash? Either way, you ought to use Path.Combine, rather than the string catenation operator (+).
What happens if you comment out all the code in EmpWorkInfo() apart from the first Console.Writeline? Does it still not get written out?
Found out I need the Microsoft.Web.Services3 dll installed on the server.
Continuation on "feroze" answer;
If you want to figure out if the 'loading of dependencies' is causing you grief here, i suggest using the "FUSLOGVW.EXE" tool *(part of .Net). When you run this it will give you a little dialog window with a few options. Create a directory somewhere (like "c:\temp\fusion_logs"), set the mode of FUSLOGVW to "log bind failures only", "custom location->c:\temp\fusion_logs".
Now restart your application and check that it failed. Now look into your fusion_logs directory. This should give you sub directories with different (maybe only 1 for now) application names. Inside each directory you will find the log files. These log files contain the "failed assembly loads" and who (which calling assembly) caused them.
They might help your hunt for a working application,
Hope this helps,
Edit: Posted this after you found the cause. The fuslogvw.exe would have shown you the missing assembly.

Categories

Resources