Visual Studio deleting files it needs to debug - c#

I started running into a small problem regarding debugging my program. It would start off showing no errors, then I would press debug to test it. It would throw me an error saying
"Could not copy the file "obj\x86\Debug[programName].exe" because it was not found."
I have proceeded to tamper with various things, and came to the conclusion that it was a class that I am using to read ini files by importing a dll. The two most likely lines in that class are these:
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
To test this, I removed the class and all references from the project, and it would build the project successfully. Then, I could look at the path and find the executable that was previously missing. Thinking the problem fixed, I put the class back in and as you would expect, it broke with the same error. It actually deleted the executable file before building, so in my head, it is obvious why it couldn't be found.
However, the not so obvious part is: The program was building and executing with this class in it up until this morning with no changes performed on it. Plus, the class works perfectly inside of my Unity3D game where it is reading the ini file this c# program creates.
Can anyone tell me why this is happening, and if there is a fix to it? I already tried creating a new project and re-importing everything, and it produces the same errors.
EDIT
After commenting and uncommenting each line, I found that the three commented lines in this are causing the problem:
public bool SaveToIni()
{
IniFile file = new IniFile("/LoadUpSettings.ini");
try
{
file.IniWriteValue("Screen", "Screen Height", cbbScreenHeight.SelectedItem.ToString());
file.IniWriteValue("Screen", "Screen Width", cbbScreenWidth.SelectedItem.ToString());
//file.IniWriteValue("Controllers", "Razer Hydra", ckbRazerHydra.Checked.ToString());
//file.IniWriteValue("Controllers", "Oculus Rift", ckbOculusRift.Checked.ToString());
//file.IniWriteValue("Screen", "Fullscreen", ckbFullscreen.Checked.ToString());
return true;
}
catch
{
MessageBox.Show("Please fill out all values");
return false;
}
}
This is the IniWriteValue function inside the IniFile class.
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
public string IniReadValue(string Section, string Key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.path);
return temp.ToString();
}
Oddly enough, if i remove the ckbRazerHydra.Checked.ToString(), and put in a standard string such as "True", it still doesn't work, although with those 3 lines commented out, the project builds completely.
EDIT
I managed to fix this problem to an extent. I just have to run my program in release version. If I run it in debug mode, I will always get the error saying the exe couldn't be copied because it wasn't found. However, Release mode seems to almost always work.

The bin and obj folders are meant for output only. When you tell Visual Studio to do a clean or a rebuild it will delete all files in these folders. You can safely delete these folders at any time and you shouldn't lose anything in the process.
You are never meant to place any files in these folders. If you want to add an external assembly (EXE or DLL) to your project you should add it to your project using the Add->Existing Item command on a project. Then you can tell your project to reference that file and it will use the local relative path.
For example, if you create a "lib" folder in your project root and place some.dll inside it, you can then add a reference to the file located in your project and it will use the relative path ..\lib\some.dll.

The problem is with files in your current project that you have set to
Copy to output directory=copy always/copy if newer
When you add a file this way VS will delete all other previous files that other projects dumped into your current project bin/.
In order to avoid this situation add the files and leave them with Copy to output directory=Do not copy option and then use MSBuild Copy task to dump your files.
If you are using docker you can simple put a COPY command - the same thing but not with MSBuild.
I believe this is the default behavior of some this MSBuild internal task and a workaround is the only option.

Related

Check if a <PackageReference/> tag is added to .csproj file

I have a .csproj file as follows:
If a <PackageReference/> tag is added to this csproj file, the build should fail. How do I do that? Is there any setting or a test I can add?
For example,
On my phone at the moment, however you can do the following or rather follow this (unable to test for you):
In Pre-Build Events (Right click on your project, go to Properties) of the project, add the following command:
CD $(SolutionDir)
CALL CheckProj.ps1
Then on the root of your solution, create a bat file called "CheckProj.ps1"
The contents of your script should be along the lines of:
$xml = new-object System.Xml.XmlDocument;
$xml.LoadXml( (get-content 'MyProject.csproj') );
$node = $xml.SelectNodes('//Project/ItemGroup/PackageReference');
exit $node.Count;
Then on the rebuild of the project, if exit isn't equal to 0, it'll fail the build as 0 is expected to simulate success in a build event, anything higher will end up being marked as an error and should fail the whole build process.
I'm not entirely sure why you'd want to do this, but you could do this in a test fairly easily.
Using XUnit:
[Fact]
public void NoPackageReferences()
{
string myCsproj = File.ReadAllText("path/to/my.csproj");
Assert.DoesNotContain("PackageReference", myCsproj);
}
Now, if you wanted to be more thorough, you could parse the XML... But that's probably overkill for this.

Does the Visual Studio OneClick publisher change the byte array needed for RSA encryption?

I'm trying to publish a COM add-in for Word and need to have a license file. I'm using Rhino Licensing and the file has no issues during debugging, but when using OneClick to publish the add-in the license is reported as no longer valid. Here is the code for the class I'm using to check the license:
using System;
using System.IO;
using Rhino.Licensing;
namespace Services.Licensing
{
public class LicenseChecker
{
private static string PublicKeyPath;
private static string LicensePath;
public static bool LicenseIsValid(string licPath)
{
bool result = false;
Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
String Root = Directory.GetCurrentDirectory();
PublicKeyPath = Root + #"\Licensing\publicKey.xml";
LicensePath = Root + #"\Licensing\license.xml"; //licPath;
// not working on INSTALL, runs fine in debug
try
{
var publicKey = File.ReadAllText(PublicKeyPath);
//Throws an exception if license has been modified
LicenseValidator validator = new LicenseValidator(publicKey, LicensePath);
validator.AssertValidLicense();
if (validator.ExpirationDate > DateTime.Now)
{
result = true;
}
}
catch
{ }
return result;
}
}
}
I'm trying to bundle the license with the exe I'll be giving to a small testing group to save the testers unnecessary trouble managing the license and public key. Currently I have the (valid) license file and public key as embedded resources, set to "copy always."
I'm having the same issue when the license is not bundled with the published exe, but the public key is. When both files are left outside of the solution, there seems to be no problem. Could publishing the solution be changing the byte array of the public key or the license?
I'm using .Net Framework 4.7.2 and Visual Studio 2019.
After a lot of toying, the broad answer seems to be no, ClickOnce publishing does not affect the byte array.
The error seems to be occurring because the ClickOnce is not copying XML files into the Application Files folder it creates at all.
After pulling the licenses into a desktop folder and having the program call them from there, another class that uses XML files to load list items would not initialize, leading me to put Try{} around all functions that use pre-made XML files in my program. Each of these functions returned the Catch{}. I'm assuming that ClickOnce is too simplistic an installer to be used if you are trying to include many/any resource files, especially if they are XML.

C#: Compare whether 2 DLLs are equal binaries or not using C# code not TOOLS

My question is not same as below.
Compare Two DLL's
I am trying to compare whether 2 DLLs are equal binaries or not using C# code. If needed I can refer some third party DLL but the comparision must be done by C# code not manual opening tool.
This is my bigger task..
C# Common libraries same location for different WCF services
I have a dll called MyDll.dll at below locations
C:\Source\MyDll.dll
C:\Destination\MyDll.dll
I wrote a method which gets MyDll.dll from C:\Source and drop/replace into C:\Destination but I do not want to blindly replace MyDll.dll in C:\Destination. I want to check whether C:\Source\MyDll.dll and C:\Destination\MyDll.dll are same or not. If not then only replace.
Please remember everything needs to be happening in C# code since this method runs on a start event of windows service.
public void LoadAssembly()
{
string source = #"C:\Source\MyDll.dl"
string destination = #"C:\Destination\MyDll.dll"
// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(source, destination, true);
}
Looked at this not use
C# - comparing two .net dlls using reflection
UPDATE
I created below method and I feel it has performance issue depending on how big my dll is. Is there any way I can improve this.
public static bool AreFilesEqual()
{
string source = #"C:\Source\MyDll.dll";
string dest = #"C:\Destination\MyDll.dll";
byte[] sourceFileBytes = File.ReadAllBytes(source);
byte[] destinationFileBytes = File.ReadAllBytes(dest);
// if two files length are not same then they are not equal
if(sourceFileBytes.Length != destinationFileBytes.Length)
{
return false;
}
return sourceFileBytes.SequenceEqual(destinationFileBytes);
}

Assemblies refer to the same metadata but only one is a linked reference; consider removing one of the references

I am currently dealing with the error word for word:
Assemblies 'C:\Users\Jake\Desktop\AudioFileSorter\AudioFileSorter\obj\Debug\Interop.QTOControlLib.dll' and 'C:\Users\Jake\Desktop\AudioFileSorter\AudioFileSorter\libs\Interop.QTOControlLib.dll' refer to the same metadata but only one is a linked reference (specified using /link option); consider removing one of the references.
My references include several files:
AxInterop.QTOControlLib.dll
Interop.QTOControlLib.dll
Interop.QTOLibrary.dll
Interop.Shell32.dll
taglib-sharp.dll
These files are all located and referenced from a folder called libs within the base location for my project: AudioFileSorter\AudioFileSorter\libs\
An additional control reference was included as the Apple QuickTime Control 2.0 from the COM references. With the exception of this reference all other references were added by right clicking 'References' in the Solution Explorer and clicking 'Add Reference' and then browsing the libs folder to pull dll file.
Obviously, I have no idea what I am doing and I don't know how to solve it. The project worked fine yesterday and after trying to build the project to a release build everything got messed up and now I have this error. I have tried removing one of the duplicate references but then i end up just missing the reference when the app calls it during this code line:
private void SortM4PFiles(string[] files)
{
WriteLine("Begin compiling .m4p files...");
foreach (string file in files)
{
axQTControl1.URL = file;
// Create new movie object
QTOLibrary.QTMovie mov = new QTOLibrary.QTMovie();
mov = axQTControl1.Movie;
string title = mov.Annotation[(int)QTAnnotationsEnum.qtAnnotationFullName];
string artist = mov.Annotation[(int)QTAnnotationsEnum.qtAnnotationArtist];
string album = mov.Annotation[(int)QTAnnotationsEnum.qtAnnotationAlbum];
songs.Add(new Song(title, album, artist, file));
songs[songs.Count - 1].setType(".m4p");
WriteLine("Evaluated " + title);
}
// Make sure the previous .m4p is not in use
// This will prevent an IOException when the file is in use and cannot be moved
axQTControl1.URL = "";
}
Any help or explanation would be greatly appreciated. Thank you.
This was the tutorial for using the QuickTime control and reading m4p and m4a metadata.
I was trying to convert one project from packages.config to PackageReference... & I got this issue. After looking into it, I realized that, there are two references added for the same dll.
How? One from nuget & one from local COM dll. I had remove one reference to fix the issue.

Computed const value constantly one build behind

While updating our build incrementer program that runs during the pre-build event, I noticed a potential problem that can cause quite a bit of issues. Building the application the first time successfully updates BuildInfo.cs and calculates all of the const values. Each subsequent build and successful execution of the pre-build event updates the proper file (as provided below) but each computed const value is out of date from the last build.
// In externally modified file BuildInfo.cs which is updated by our pre-build
// tool to update the version information and produce new consts.
namespace ConstProblem.Properties {
static class BuildInfo {
internal const string AssemblyVersionString = "1.1.0.0";
internal const string BuildDate = "2012-11-07T08:52:32.5480259-07:00";
internal const string FileVersionString = "1.1.12312.852";
internal const string Full = "v1.1 (Build: 2012-11-07 08:52)";
internal const string Short = "1.1";
}
}
// Program.cs. Reproduces the problem for this question.
namespace ConstProblem {
class Program {
const string UserAgent = "ConstProblem/" + Properties.BuildInfo.Short;
static void Main() {
System.Console.WriteLine(UserAgent);
}
}
}
As an example, the application was originally built with the AssemblyVersionString at 1.0.0.0. The above program ran and compiled as expected. Increasing this to 1.1 and building/running the application a second time produced ConstProblem/1.0 as it's output and has this as it's values
// From the Immediate Window
Properties.BuildInfo
ConstProblem.Properties.BuildInfo
base {object}: object
AssemblyVersionString: "1.1.0.0"
BuildDate: "2012-11-07T08:51:46.8404556-07:00"
FileVersionString: "1.0.12312.851"
Full: "v1.0 (Build: 2012-11-07 08:51)"
Short: "1.0"
As you can see, the AssemblyVersionString was updated 1.1.0.0 properly but the rest of the computed values did not. If I were to build and execute a third time (and increase to 1.2) they would update to the information provided above.
I have confirmed that the output file by the pre-build event outputs all of the information correctly and exits with a status of 0 to allow the build to continue. I am at a loss as to why the const's are constantly one build behind. The build utility is also something I wrote and it just uses a template and replaces the contents of the BuildInfo.cs if the file is checked-out.
My environment is running Visual Studio 2010 Ultimate and compiling in .Net 4. I've reproduced this in both Console and Web applications. I got the idea for using const values from the comments in How to get the assembly version and file version of your own assembly?
It's reading the successful build increment from AssemblyInfo.cs
But that only increments by 1 after a successful build, hence why your always 1 behind.
add
[assembly: AssemblyVersion("1.star.star.star")] to AssemblyInfo.cs (in Solution/Properties)
^ star = * (editor limitation)

Categories

Resources