Showing posts with label File. Show all posts
Showing posts with label File. Show all posts

Tuesday, April 29, 2008

ReferencesManager 1.0.2 : Utility to check .NET assembly references.

    New build of ReferencesManager (v1.0.2) is released.

    The build include new command line switch:

-path=<customer path>

which allows to define additional folders to search referenced assemblies. For example:

ReferencesManager.exe Main.dll -path=D:\0;D:\1

Downloading ReferencesManager 1.0.2

Sources can be downloaded from "C# tips samples" project.

References:

Utility to check .NET assembly references

Tuesday, April 15, 2008

Utility to check .NET assembly references

Sometimes, when a complex project (many source solutions, dlls, references) is built and run, then we receive a problem with references (here we don't speak about signed assemblies). For example, all dlls has a reference to basic .dll, but a specific .dll has a reference to obsolete version of the basic .dll.

Sample:

MainUtils has a reference to Utils1 (v2.0.0.0) and Utils2 (v2.0.0.0), but Utils2 (v2.0.0.0) has a reference to obsolete version of Utils1 (v1.0.0.0). See folders TestData4References in solution csharp-samples.

referenceDiagram

When a MainUtils will be run, then a error can be shown.

Utility ReferencesManager.exe helps to show all references and output list of all assemblies full names. This information helps to see same assemblies with different versions.

To start the utility it is necessary to type name of initial executable (or .dll) file:

ReferencesManager.exe MainUtils.exe > MainUtils.log

Content of MainUtils.log:

mainUtilsLog

Received log allows to find Utils1 with different versions 1.0.0.0 and 2.0.0.0 and Utils2, which references to Utils1 version 1.0.0.0.

Limitations of version 1.0.1:

  • The utility finds assemblies in GAC and in folder of initial assembly only.
  • The utility doesn't find referenced (in c# source project), but actually not used assemblies.
  • The utility doesn't output list of problematic assemblies.

Downloading ReferencesManager.exe.

References:

Reflector for .NET

Create and Share Flow Charts, Diagrams and More

Sunday, April 6, 2008

How to listen file change notification.

        When we want to receive a notifications about file system changes, we can use class FileSystemWatcher.

Code sample:

string testFolder = Path.GetTempPath();
string testFilePath = Path.Combine(testFolder, "test.tst");
File.Delete(testFilePath);

using (FileSystemWatcher watcher = new FileSystemWatcher(testFolder, "*.tst"))
{
watcher.NotifyFilter =
NotifyFilters.LastAccess | NotifyFilters.LastWrite |
NotifyFilters.FileName | NotifyFilters.DirectoryName |
NotifyFilters.CreationTime | NotifyFilters.Attributes |
NotifyFilters.Size | NotifyFilters.Security;
watcher.Created += OnFileChanged;
watcher.Changed += OnFileChanged;
watcher.Deleted += OnFileChanged;
watcher.EnableRaisingEvents = true;

File.WriteAllText(testFilePath, "text");
File.AppendAllText(testFilePath, "additional text");
File.Delete(testFilePath);
}




Output window content:



FileSystemWatcherOutputContent



Notes:



Unfortunately, my experience shows, that FilesystemWatcher doesn't work absolutely correct. In many cases, it doesn't catch a file changing.



Reference:



FileSystemWatcher Class

Thursday, April 3, 2008

How to create unique temporary file name and folder.

        As we investigated, it is possible to get temporary Windows folder by method Path.GetTempPath and create temporary file by method Path.GetTempFileName().

Unfortunately, these methods cannot help us to create unique temporary folder or temporary file (method Path.GetTempFileName() can generate only 65 536 unique file names at the same time).

It is suggested to generate unique path and name to use a globally unique identifier (GUID) with help of method Guid.NewGuid(). "Such an identifier has a very low probability of being duplicated." by MSDN.

Method, which can generate unique temporary folder:

static string GetUniquePath()
{
string uniquePath;
do
{
Guid guid = Guid.NewGuid();
string uniqueSubFolderName = guid.ToString();
uniquePath = Path.GetTempPath() + uniqueSubFolderName;
} while (Directory.Exists(uniquePath));
Directory.CreateDirectory(uniquePath);
return uniquePath;
}


The method generated and created such paths:



C:\Documents and Settings\name-f\Local Settings\Temp\b0dc9b66-a32c-586c-815b-dfed844df58c



C:\Documents and Settings\name-f\Local Settings\Temp\18a09210-9107-4a19-ab11-a246c36fec54



By the same way, can be generated and created temporary file path.



Important notes:



1. Don't forget to delete created temporary folder and files after usage.



2. Published method GetUniquePath is not protected for multi-threaded usage.



Reference:



Guid Structure



Guid.NewGuid Method

How to redirect Trace output.

As we know, for tracing we can use method Trace.WriteLine(). But usually, we want to avoid a creating of detailed log file in production mode and to enable the tracing for testing and debugging purposes only by a configuration changing. So, we should find a way to redirect output of Trace.WriteLine() from standard output to a log file and configures the redirection without rebuilding of application.

Let's write next c# code:

Trace.WriteLine("messageTrace");
Trace.WriteLine("messageError", "Error");
Trace.TraceError("traceErrorMessage");

and define .config file:

redirectTrace_va_ConfigFile

Thus, we delete "Default" Trace Listener and add our "myListener' of type TextWriterTraceListener with parameter (log file name) c:\myListener.log.

Additionally, attribute "autoflush" is set in True and method Trace.WriteLine() will store input messages to log file immediately.

Content of file myListener.log:

myListenerLogFileContent

Reference:

How to configure Trace listener

Tuesday, April 1, 2008

How to receive temporary path and file name (c#).

    To receive standard Windows temporary path we can use c# method Path.GetTempPath().

To receive uniquely temporary file we can use method Path.GetTempFileName(). The method creates a zero-byte in temporary folder and returns a full path of that file. Path of the file is created by format: <temporary folder>\tmp<4 hex symbols>.tmp (for example, <temporary folder>\tmpF1FB.tmp).

   Let's investigate how a method GetTempFileName creates a uniquely temp file:

string tempFolder = Path.GetTempPath();
string uniqueTempFileName = Path.GetTempFileName();
string tempFolder_via_Environment = Environment.GetEnvironmentVariable("TEMP");

Debug.WriteLine("tempFolder: " + tempFolder);
Debug.WriteLine("tempFolder_via_Environment: " + tempFolder_via_Environment);
Debug.WriteLine("uniqTempFileName: " + uniqueTempFileName);

for (int i = 0; i < 0xFFFF; i++)
{
uniqueTempFileName = Path.GetTempFileName();
Debug.WriteLine("uniqTempFileName: " + uniqueTempFileName);
Debug.WriteLine(String.Format("File {0} exists: {1}", uniqueTempFileName, File.Exists(uniqueTempFileName)));
}
Output Window:



output1



So, we can see rule, how GetTempFileName builds file name: "tmp" + counter + ".tmp". If a  file with next temporary file name exists, then GetTempFileName will generate next temporary file name.



File with name tmp3DBA.tmp was created manually and see result (tmp3D9, tmp3DBB) in Output Window



output2



When all temporary names will be created, that exception IOException will be raised:



exceptionQuickWatch



Reference:



Path.GetTempPath Method



Path.GetTempFileName Method

Sunday, March 30, 2008

Sample of StackTrace usage.

       Sometimes we want to store in log file error (warning or trace) message and stack trace, from where the message is stored. To solve the problem it is suggested to use class StackTrace.

public class StackTraceSampleClass
{
const string LOG_FILE_NAME = "stackTraceSample.log";
public void Execute()
{
File.Delete(LOG_FILE_NAME);
F1(-10);
F2(-10);
}
void F1(int arg)
{
F(arg);
}
void F2(int arg)
{
F(arg);
}
double F(int arg)
{
if (arg < 0)
{
StackTrace stackTrace = new StackTrace(true);
string logContent = String.Format("unexpected value of arg: {0}, stack: {1}", arg, stackTrace);
File.AppendAllText(LOG_FILE_NAME, logContent);
return 0;
}
return Math.Sqrt(arg);
}
}
File stackTraceSample.log in Debug mode:


stackTraceInDebugMode 


File stackTraceSample.log in Release mode:


stackTraceInReleaseMode 


Reference:



StackTrace Class



Sample of C# Trace.Fail() method.

Monday, March 3, 2008

Method File.AppendAllText

     To add any text to test file, can be used method

File.AppendAllText(String path, String contents)

   1: string fileName = Path.GetTempFileName();


   2: string fileContent = "sample of method File.WriteAllText";


   3: File.WriteAllText(fileName, fileContent);




Additional Links:



File..::.AppendAllText Method (String, String)



File..::.AppendAllText Method (String, String, Encoding)