MS Project get name current project - c#

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);
}

Related

How does this log method work in a .NET application?

I am working on a .NET project using C# and I have the following doubt.
I have this method that write some error information into a .log file in a specific directory on my file system:
private static void writeErrorLog(string error)
{
string date = DateTime.Now.ToString("yyyyMMdd_HHmmss");
string currDir = Directory.GetCurrentDirectory();
System.IO.File.AppendAllText(currDir + "\\FILE\\LOG\\Error_" + date + ".txt", error);
}
Ok this writeErrorLog() method will be called into some try catch block of my code, something like this:
try
{
currentAttachmentFileData = currentAttachmentFile.OpenBinary();
currentAttachementModel = new AttachmentModel(currentAttachment, currentAttachmentFileData);
attachmentsModelList.Add(currentAttachementModel);
}
catch (Exception ex)
{
//writeLog(2, String.Format("Unable to read the attachment, it may be corrupted {0} - {1}", fileName, ex.Message));
writeErrorLog("Errore inserimento attachment. Numero protocollo: " + recNumber
+ " Data protocollo: " + recDate
+ " Nome attachment: " + currentAttachmentFile
+ " INFO: " + ex.ToString() + " | " + ex.Message + " | " + ex.StackTrace);
}
It happens in different places of my code.
My doubt is: the file is the same, so it means that it will be added a new line to this file every time that an error occours.
Is it my reasnong correct?
The file name is string date = DateTime.Now.ToString("yyyyMMdd_HHmmss"); so it changes every second.
You should definitely add some abstraction here and hide writeErrorLog behind an interface. Behind the interface you could have your own implementation of writeErrorLog, but as others suggested I would strongly recommend using libs over your custom solution.
More on available libraries:
benchmarking-5-popular-net-logging-libraries
dotnetlogging.com

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

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".

UnauthorizedAccessException was unhandled

I'm trying to take input and convert that to a .csv file then create a directory for the folder and save that file within the directory. Once I run my code, I'm able to create the directory and file. However, this is supposed to happen after I click the button and does so before. The exception is thrown right after I click the button. I'm using WPF and coding in C#. What would cause this exception?
Here is a snippet
private void updateBANKEevent(object sender, RoutedEventArgs e)
{
//Convert input to CSV format
string userInput = tellerID.Text + "," + vaultSerial.Text + "," + QR.Text;
var bnkDir = #"C:\Program Files\Bank_Data";
//generate headers for CSV file
if (!Directory.Exists(bnkDir))
{
string bnkHeader = "tellerID" + "," + "Vault Serial Number" + "," + "QR Code" + Environment.NewLine;
Directory.CreateDirectory(bnkDir); <--Exception is thrown here
File.WriteAllText(System.IO.Path.Combine(bnkDir,"Bank_Data.csv"), bnkHeader + userInput);
}
// Append new input to existing file
File.AppendAllText(System.IO.Path.Combine(bnkDir),userInput + Environment.NewLine);
}
The exception is quite clear. The user is not authorised to create the specified directory.
Given that the folder is "C:\Program Files\Bank_Data" it will be the case that a regular user won't have the rights to create files or directories whereas an admin user (which you probably are) will.
You need to choose a folder that all users have rights to to store your data, which by default will be %APPDATA%\<your app>.

SharpSVN Repo-Browser

Viewing the repository data of TortoiseSVN is done by right click on a file -> TortiseSVN -> Repo-Browser.
I would like to get this data using SharpSVN, in order to retrieve the name of lock owner.
Is it possible? How? Where does this data being saved?
I've tried to get a lock owner name using the following code, however, I get the lock infirmation just in case I'm on the machine where the lock was done from. If I'm another user, I cannot get the lock information.
using (SvnClient client = new SvnClient())
{
client.GetInfo(#"path\to\working\copy\file.xml", out info);
SvnLockInfo lc = info.Lock;
if (lc != null)
{
MessageBox.Show("Owner: " + lc.Owner + "\n" +
"Creation time: " + lc.CreationTime + "\n" +
"Comment: " + lc.Comment + "\n" +
"Expiration time: " + lc.ExpirationTime);
}
}
Even when I set the target as the repository URI- instead of path to the local working copy I get the same result:
Uri target = client.GetUriFromWorkingCopy(#"path\to\working\copy\file.xml");
client.GetInfo(target, out info);
The way I can see the lock owner name from another working copy is, as mentioned, by right click on file -> repo-browser.
Any ideas how to perform it programmatically?

read hidden file

Is it possible to read file with attribute hidden in program? I know the path to file.
For example, if I copy a file to some place and set the attribute hidden:
File.Copy("sender.exe", path+"system.exe");
File.SetAttributes(path + "sender.exe", FileAttributes.Hidden);
Can I run the hidden .EXE file with this code (if I know path)?
function Run(path, lang, city) {
var shell = new ActiveXObject("WScript.Shell");
shell.run(path + " " + city + " " + lang);
}
Yes; that's perfectly possible.

Categories

Resources