I am trying to run the following example from MSDN:
using System.Printing;
public class PrintTest {
public static void Main(string[] args)
{
// Create the printer server and print queue objects
LocalPrintServer localPrintServer = new LocalPrintServer();
PrintQueue defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue();
// Call AddJob
PrintSystemJobInfo myPrintJob = defaultPrintQueue.AddJob();
// Write a Byte buffer to the JobStream and close the stream
Stream myStream = myPrintJob.JobStream;
Byte[] myByteBuffer = UnicodeEncoding.Unicode.GetBytes("This is a test string for the print job stream.");
myStream.Write(myByteBuffer, 0, myByteBuffer.Length);
myStream.Close();
}
}
but the compiler is complaining
The type or namespace Printing does not exist in the namespace
System(are you missing an assembly reference) ?
How do I solve this issue ?
EDIT: How do I add a reference for command line compiled application ( Not Visual Studio)
From the command line something like csc /reference:lib\System.Printing.dll
Original Answer
Project > Add Reference, then under 'Assemblies > Framework'.
Choose System.Printing.
You can find out which Assembly you need to add a reference to by Googling the namespace followed by the word 'assembly'. In your case:
System.Printing assembly
The second result is from MSDN and indicates which assembly System.Printing can be found in.
From Command prompt
Create a public reference
/reference:[alias=]filename
/reference:filename
Where
Arguments
filename
The name of a file that contains an assembly manifest. To import more than one file, include a separate /reference option for each file.
alias
A valid C# identifier that will represent a root namespace that will contain all namespaces in the assembly.
Microsoft documentation page for cmd
From Visual Studio Community 2013 (Free version)
Right click References folder in your solution and browse for it there.
You are missing an assembly reference. Add a reference to System.Printing.dll.
You need to add the System.Printing assembly to your project.
You can find this by right clicking on your project and clicking "Add Reference". (You can search for it in the Assemblies > Framework tab)
Additionally, you must add using System.IO; in order to use Stream.
In your Solution Explorer right click on References click on Add Reference click on the .NET tab and scroll to System.Drawing. It should work.
Original answer found here:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/0648fdc4-f67b-476e-b434-998efec14b89/class-systemprintingprintcapabilities-not-found?forum=wpf
However, you'll need to add the Assembly called ReachFramework
Related
New to C# and VS
All I am trying is to get details/properties of an msi file programmatically (eg. "Comments" in the details tab when you get file properties)
I am using the following code (using someone's code of internet) , VS is complaining about missing reference for below and also suggesting not to use "using"
using WindowsInstaller;//msi.dll
ERROR
The type or namespace name 'type/namespace' could not be found (are you missing a using directive or an assembly reference?)
And also within the function it cannot resolve any reference for the following
WindowsInstaller.Installer installer = (WindowsInstaller.Installer)Activator.CreateInstance(installerType);
Here is the code:
using System.Configuration.Install;//System.Configuration.Install.dll
using WindowsInstaller;//msi.dll
static void get_msi_details(string path)
{
// Get the type of the Windows Installer object
Type installerType = Type.GetTypeFromProgID("WindowsInstaller.Installer");
// Create the Windows Installer object
WindowsInstaller.Installer installer = (WindowsInstaller.Installer)Activator.CreateInstance(installerType);
// Open the MSI database in the input file
Database database = installer.OpenDatabase(path, MsiOpenDatabaseMode.msiOpenDatabaseModeReadOnly);
// Open a view on the Property table for the version property
View view = database.OpenView("SELECT * FROM Property WHERE Property = 'Comments'");
// Execute the view query
view.Execute(null);
// Get the record from the view
Record record = view.Fetch();
// Get the version from the data
string version = record.get_StringData(2);
}
VS studio isnt offering anything in "Potential Fixes" to resolve the reference.
In Visual Studio go to References > Add Reference... > COM > Browse... > %WINDIR%\system32\msi.dll.
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.
I have a Visual Studio Solution with two projects inside.
The first project is a windows service, and this project contains one XML file inside a folder (called Configurations). This XML file is called Databases.xml. I have changed Databases.xml Build Action from content to embedded resource, and now I want to access this XML file from my other project in my solution, which is a WPF application.
I have therefore added an reference to my windows service project inside my WPF project, and would now like to access my XML file from my WPF project.
My problem is that when I am trying to access the embedded resource then I can't find out which type to use and what the path/namespace to my assembly and XML file should be. When I am using the
string[] names = this.GetType().Assembly.GetManifestResourceNames();
my names array is filled out with some resources from my WPF project. What I want is to access the ResourceNames and of course my Databases.xml file from my Windows Service project.
Please help me since this problem is driving me nuts.
If you need any additional information, please let me know.
My Solution Update 26-07-2013
I found out that the real problem occured when I couldn't use my first windows Service projects namespace as a type for my assembly. my Windows Service consists of a service class (with OnStart() and OnStop() method inside), and in order to use this class as my namespace type, I needed to add another reference to my WPF project. I needed to add a reference to System.ServiceProcess namespace, in order to use my Windows Service Class as a type for my assembly in my WPF Project.
In Order to access my Databases.xml file, I have come up with this solution. Remember to insert your own projects name and class name instead of my placeholders (<Windows Service Project Name> etc).
//Remember to add a reference to System.ServiceProcess in order to be able to use your WIndows Service Project as an assembly type.
using (Stream stream = typeof(<Windows Service Project Name>.<Windows Service Class Name>).Assembly.GetManifestResourceStream("<Windows Service Project Name>.<Folder Name>.Databases.xml"))
{
//Load XML File here, for instance with XmlDocument Class
XmlDocument doc = new XmlDocument();
doc.Load(stream);
}
So my real problem was that I didn't include the System.ServiceProcess reference to my second project.
You've to refer to Windows Service project Assembly to make it work
The problem with your code is This.GetType().Assesmbly gives current Assembly In your case WPF Assembly and obviously you'll not find what you need there.
Try this
Assembly windowsServiceAssembly = typeof(SomeTypeFromThatAssembly).Assembly;
string[] names = windowsServiceAssembly.GetManifestResourceNames();
Hope this helps.
If your class is static class then use this methods:
internal static string GetFromResources(string resourceName)
{
var asm = Assembly.GetExecutingAssembly();
var resource = asm.GetManifestResourceNames().First(res => res.EndsWith(resourceName, StringComparison.OrdinalIgnoreCase));
using (var stream = asm.GetManifestResourceStream(resource))
{
if (stream == null) return string.Empty;
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
For example if your embedded resource file names on the this project is 'MyFile.txt' then use this static method same this code:
var myFileData = GetFromResources("MyFile.txt");
I can't use "Zipfile" class in the name space "System.IO.Compression" my code is :
using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string startPath = #"c:\example\start";
string zipPath = #"c:\example\result.zip";
string extractPath = #"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath, CompressionLevel.Fastest,true);
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
}
}
the error is :
The name 'zipfile' does not exist in the current context
How I can solve it ?
You need an extra reference for this; the most convenient way to do this is via the NuGet package System.IO.Compression.ZipFile
<!-- Version here correct at time of writing, but please check for latest -->
<PackageReference Include="System.IO.Compression.ZipFile" Version="4.3.0" />
If you are working on .NET Framework without NuGet, you need to add a dll reference to the assembly, "System.IO.Compression.FileSystem.dll" - and ensure you are using at least .NET 4.5 (since it doesn't exist in earlier frameworks).
For info, you can find the assembly and .NET version(s) from MSDN
For those who are green programmers in .NET, to add the DLL reference as MarcGravell noted, you follow these steps:
To add a reference in Visual C#
In Solution Explorer, right-click the project node and click Add Reference.
In the Add Reference dialog box, select the tab indicating the type of component you want to reference.
Select the components you want to reference, and then click OK.
From the MSDN Article, How to: Add or Remove References By Using the Add Reference Dialog Box.
you can use an external package if you cant upgrade to 4.5. One such is Ionic.Zip.dll from DotNetZipLib.
using Ionic.Zip;
you can download it here, its free. http://dotnetzip.codeplex.com/
Just go to References and add "System.IO.Compression.FileSystem".
In solution explorer, right-click References, then click to expand assemblies, find System.IO.Compression.FileSystem and make sure it's checked. Then you can use it in your class - using System.IO.Compression;
Add Reference Assembly Screenshot
A solution that helped me:
Go to Tools > NuGet Package Manager > Manage NuGet Packaged for Solution... > Browse >
Search for System.IO.Compression.ZipFile and install it
System.IO.Compression is now available as a nuget package maintained by Microsoft.
To use ZipFile you need to download System.IO.Compression.ZipFile nuget package.
I know this is an old thread, but I just cannot steer away from posting some useful info on this. I see the Zip question come up a lot and this answers nearlly most of the common questions.
To get around framework issues of using 4.5+... Their is a ZipStorer class created by jaime-olivares: https://github.com/jaime-olivares/zipstorer, he also has added an example of how to use this class as well and has also added an example of how to search for a specific filename as well.
And for reference on how to use this and iterate through for a certain file extension as example you could do this:
#region
/// <summary>
/// Custom Method - Check if 'string' has '.png' or '.PNG' extension.
/// </summary>
static bool HasPNGExtension(string filename)
{
return Path.GetExtension(filename).Equals(".png", StringComparison.InvariantCultureIgnoreCase)
|| Path.GetExtension(filename).Equals(".PNG", StringComparison.InvariantCultureIgnoreCase);
}
#endregion
private void button1_Click(object sender, EventArgs e)
{
//NOTE: I recommend you add path checking first here, added the below as example ONLY.
string ZIPfileLocationHere = #"C:\Users\Name\Desktop\test.zip";
string EXTRACTIONLocationHere = #"C:\Users\Name\Desktop";
//Opens existing zip file.
ZipStorer zip = ZipStorer.Open(ZIPfileLocationHere, FileAccess.Read);
//Read all directory contents.
List<ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();
foreach (ZipStorer.ZipFileEntry entry in dir)
{
try
{
//If the files in the zip are "*.png or *.PNG" extract them.
string path = Path.Combine(EXTRACTIONLocationHere, (entry.FilenameInZip));
if (HasPNGExtension(path))
{
//Extract the file.
zip.ExtractFile(entry, path);
}
}
catch (InvalidDataException)
{
MessageBox.Show("Error: The ZIP file is invalid or corrupted");
continue;
}
catch
{
MessageBox.Show("Error: An unknown error ocurred while processing the ZIP file.");
continue;
}
}
zip.Close();
}
Add System.IO.Compression.ZipFile as nuget reference it is working
The issue here is that you just Added the reference to System.IO.Compression it is missing the reference to System.IO.Compression.Filesystem.dll
And you need to do it on .net 4.5 or later (because it doesn't exist on older versions).
I just posted a script on TechNet Maybe somebody would find it useful it requires .net 4.5 or 4.7
https://gallery.technet.microsoft.com/scriptcenter/Create-a-Zip-file-from-a-b23a7530
Is there a way to find out the assembly name at design-time (i.e. not using reflection or runtime APIs such as System.Reflection.Assembly.GetEntryAssembly) from within Visual Studio?
The scenario requires a tool to get the assembly name that a Visual Studio project will eventually compile into.
This is like parsing the AssemblyName property of the .csproj - I am wondering if there are any APIs that can give this information reliably.
Please do not respond back with runtime APIs that use reflection - there is no assembly file present at the time I need the assembly name - just the metadata of the assembly in the csproj file.
if you are calling the tool via a post/pre-build event, this data is very easy to access.
Just go to the "project properties->Build Events" tab, then select either "edit pre-build" or "edit post-build", depending on when you want the tool to run. This should bring up an edit window with the ever helpful "Macros >>" button. Press this and you will be given a heap of macros to use and should be pretty much everything you need.
The "API" you could use is LINQ to XML after all the .csproj file is just xml. (and you can get the location of the .csproj file if you need from the solution file which for some reason is not XML but can be easily parsed)
You can use "TargetName" available in Macros for Post-build events. It will give you the assembly name for your project.
After a quick run through MSDN I found this article which might be a good start for some further research:
Accessing Project Type Specific Project, Project Item, and Configuration Properties
I think you will need to write some regular expression that will give you the value of "AssemblyTitle" attribute in AssemblyInfo.cs file.
Something like this:
public class Assembly
{
public static string GetTitle (string fileFullName) {
var contents = File.ReadAllText (fileFullName); //may raise exception if file doesn't exist
//regex string is: AssemblyTitle\x20*\(\x20*"(?<Title>.*)"\x20*\)
//loading from settings because it is annoying to type it in editor
var reg = new Regex (Settings.Default.Expression);
var match = reg.Match (contents);
var titleGroup = match.Groups["Title"];
return (match.Success && titleGroup.Success) ? titleGroup.Value : String.Empty;
}
}