My program generates a script for another application. How can I also make opening this script in that application? And is it possibly to be done without using an external file? My program is written in Xamarin and C# (due to use of one C# library), but obviously any Objective-C solution is appropriate.
I found that the only way is to write information to a file and to open this file programmatically with another application. Class NSWorkspace helps to do that:
NSString *data = #"Some data";
NSString *filename = #"Some filename";
[data writeToFile:path
atomically:NO
encoding:NSUTF8StringEncoding
error:nil];
[[NSWorkspace sharedWorkspace] openFile:filename
withApplication:#"Graphviz"];
And the code for C#:
using AppKit;
using System.IO;
...
string data = "Some data";
string filename = "Some filename";
File.WriteAllText (filename, data);
NSWorkspace.SharedWorkspace.OpenFile (filename, "Graphviz");
Probably, to do that without using files external application must support AppleScript, but it doesn't.
Related
I'm new to programming so please be patient.
I am currently developing a small Program in Visual C# 2010 Express, .NET Framework 4.0, which starts a Script on a Linux Machine (what creates the File /tmp/logs.tgz), downloads the File and then I want to extract it. Running the Script and downloading the File via Renci.SshNet works flawlessly.
But when I want to extract it, it gives me an Error "NotSupportedException" my Filepath Format is incorrect (which is not the case, I think?).
I copy and pasted the Code directly from here (Simple full extract from a TGZ (.tar.gz)) and edited it for my Needs:
using System.IO;
using System.IO.Compression;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Tar;
//it executed the Script and created the file on the Linux Machine /tmp/logs.tgz
//now I want to download it
string myTime = DateTime.Now.ToString("yyyyMMdd");
var pathWithEnv = (#"%USERPROFILE%\Desktop\logs" + myTime + ".tgz");
var filePath = Environment.ExpandEnvironmentVariables(pathWithEnv);
string localFile = filePath;
//then downloads /tmp/logs.tgz to ..\Desktop\logs+ myTime +.tgz
//everything great until now. here I want to extract .TGZ:
var pathWithEnv2 = (#"%USERPROFILE%\Desktop\logs" + myTime);
var fileDir = Environment.ExpandEnvironmentVariables(pathWithEnv2);
string localDir = fileDir;
Stream inStream = File.OpenRead(localFile);
Stream gzipStream = new GZipInputStream(inStream);
TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream);
//ERROR OCCURS HERE:
tarArchive.ExtractContents(localDir);
tarArchive.Close();
gzipStream.Close();
inStream.Close();
I even tried to set the localFile and localDir string without the EnviromentVariable, but that didnt help. I tried:
- download and extract it directly on C:\ (or on a mapped Network Drive U:) to prevent too long filenames (which should not be the case as it should never get longer than 86 characters).
- string = #"C:..\logs", string = "C:\..\logs", string = #"C:..\logs\", etc.
- tried it without myTime
- using ICSharpCode.SharpZipLib.Core;
I did a MessageBox.Show(localDir); before the tarArchive.ExtractContents(localDir); and it showed "C:\Users\Baumann\Desktop\logs20140530" which is correct, thats the Directory I want to extract it to. Even creating the Directory before executing it doesn't help.
I also created a new Project with just one button which should start the Extraction and the same error occurs.
I tried, doing it separately, first extract the GZip and then the .tar, but it also gives me the same Error when extracting the GZip (using ICSharpCode.SharpZipLib.Core; of course).
What drives me even more crazy about it, is, that it starts to extract it, but not everything, before it fails. And always the same Files, whats not clear for me why these and why not the others.
I'm on Windows 8.1, using SharpZipLib 0.86.0.518, downloaded directly from the Website.
Thanks in advance.
well, I finally fixed the Problem. The Linux machine is creating a file which includes the MAC-Adress and since Windows can't handle ":" in a Filename, it crashes.
I am now extracting file by file and checking each file for ":" and replacing it with "_", works flawlessly.
How in C# may I read a named attribute e.g. Title from a WMA file on Win XP or later?
One method to read (and modify/write) WMA metadata attributes is to use the Windows Media Format SDK. In particular the IWMHeaderInfo interface has the functions you want: GetAttributeByName, GetAttributeCount and GetAttributeByIndex. You will have to write P/Invoke code in C# in order to use this COM-based API.
Another option which may be easier would be to use a library such as NAudio which has a WindowsMediaFormat assembly for reading and writing WMA files. With NAudio the task of reading attributes becomes pretty simple.
using (var wmaStream = new NAudio.WindowsMediaFormat.WmaStream(fileName))
{
titleAttribute = wmaStream["Title"];
authorAttribute = wmaStream["Author"];
// ...
// read other meta tag attributes
}
You can find some more details about reading and writing WMA meta tags using NAudio in a post I wrote.
There is a simple solution without any strange frameworks using.
So I propose just to read the file bytewise using pure native .Net:
using System.IO;
...
string metaStr = string.Empty;
using (FileStream fs = File.OpenRead(wmaUrl))
{
byte[] b = new byte[3000];
fs.Read(b, 0, b.Length);
metaStr = Encoding.UTF8.GetString(b, 0, 3000);
metaStr = metaStr.Replace("\0", "");
int metaStart = metaStr.IndexOf("<?xml version");
metaStr = metaStr.Substring(metaStart);
int metaEnd = metaStr.IndexOf("</recordingDetails>");
metaStr = metaStr.Substring(0, metaEnd) + "</recordingDetails>";
}
Now metaStr contains the Comments field of WMA file description, which is usually called an Audio file MetaData.
Just remember, that this Comment field can be updated by other users and can contain other tags (not "recordingDetails" as shown above), so you should use your own custom substrings to define necessary MetaData borders.
Within c#, i can put data to seperate strings.
For example the current date i put to a string called line1 and some info i put to a string called line2.
What i want to do now, is sent these 2 strings to a web adress that handles these lines, and write them into a simple text file. (or can i write to a text file on a website directly from C# ?)
My knowlage of php is very low, but so far i found this code to be working:
<?php
$File = "name.txt";
$Handle = fopen($File, 'a');
$Data = "line1\n";
fwrite($Handle, $Data);
$Data = "line2\n";
fwrite($Handle, $Data);
print "Data Added";
fclose($Handle);
?>
The C# application is running on a computer, not the website (WPF window).
But now it only has the content of the $Data written to the "name.txt" file.
Does anyone know how i could link the text that is binded to the stings in C3, to the datafields defined in the PHP, so that the text from the strings gets written to the text file on the website? Or would it be possible to write directly to a text file without the php in between ?
So, you have a C# app that you want to use to send 2 bits of data to a PHP based website, and have the website write the data into a file? If that's what you want, you'll need to do something like the following...
On the website, create a receiving PHP file. The bones of it would be something like :
<?php
$File = "name.txt";
$Handle = fopen($File, 'a');
$line1 = $_GET["line1"] . "\n";
fwrite($Handle, $line1);
$line2 = $_GET["line2"];
fwrite($Handle, $line2);
print "Data Added";
fclose($Handle);
echo "Completed writing data to the file";
?>
and to submit that data from the C# app to the website, do something as simple as
WebClient wc = new WebClient();
Console.WriteLine(wc.DownloadString("http://example.com/Receiver.php?line1=this is the first line&line2=and this is the second"));
(
NOTE : No error handling is included in this code, and anyone who knows the URL for the receiver will be able to overwrite your file with whatever they like. Take care when actually implementing this.
ALSO NOTE : It is years since I did much with PHP, so you will probably need to tweak the code.
AND ANOTHER THING : the WebClient.DownloadString approach is as basic as it gets. You may want to look at HttpWebRequests if you need more control
)
You can write to a text file on a website directly from C#.
System.IO.StreamWriter file = new System.IO.StreamWriter(Server.MapPath("/file.txt"););
file.WriteLine("First line.");
file.WriteLine("Secondline.");
file.Close();
It will create a file in the root of your website (the user running the site has to have write permissions in this directory)
My text file named test.txt contains
Fixing the type manager error during checkin of the elements and supporting issues during Checkin/Checkout & merge related problems.
Now i want to remove the text "supporting issues" using c#.
Please anybody let me know.
Thanks in advance,
Naveenkumar.T
if the file is fairly small you can do this:
using System.IO; // at the top of the file
string file = "path.txt"; // change to the path
// read the whole file into a string, make a replacement, then write all string to a file
File.WriteAllText(file, File.ReadAllText(file).Replace("supporting issues ",""));
Hope that helps.
I've got 100's (maybe 1000's) of products with 10-30 images of each product coming to an online store I've put together. I need to optimize the images' file sizes as much as possible without loosing image quality.
I haven't used jpegtran, jpegoptim, or any other jpeg optimizer directly but I have noticed that punypng shrinks file sizes down about 4-6% on the larger jpeg images LOSSLESSLY.
Meta data is already stripped from the images during upload (via jumpoader) so that is not an option/problem anymore.
Is there any way to get one of the jpeg optimizers to run from C# code?
Note: I'm using shared Godaddy hosting with IIS7 and .Net 3.5
It might be 7 years too late, but I came across this question while trying to solve this problem. I eventually managed to do it and this is the solution.
For PNG you first need to install nQuant using NuGet.
include:
using System.Web.Hosting;
using System.IO;
using System.Diagnostics;
using nQuant;
using System.Drawing;
using System.Drawing.Imaging;
Methods:
public void optimizeImages()
{
string folder =
Path.Combine(HostingEnvironment.ApplicationPhysicalPath, #"assets\temp");
var files = Directory.EnumerateFiles(folder);
foreach (var file in files)
{
switch (Path.GetExtension(file).ToLower())
{
case ".jpg":
case ".jpeg":
optimizeJPEG(file);
break;
case ".png":
optimizePNG(file);
break;
}
}
}
private void optimizeJPEG(string file)
{
string pathToExe = HostingEnvironment.MapPath("~\\adminassets\\exe\\") + "jpegtran.exe";
var proc = new Process
{
StartInfo =
{
Arguments = "-optimize \"" + file + "\" \"" + file + "\"",
FileName = pathToExe,
UseShellExecute = false,
CreateNoWindow = false,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardError = true,
RedirectStandardOutput = true
}
};
Process jpegTranProcess = proc;
jpegTranProcess.Start();
jpegTranProcess.WaitForExit();
}
private void optimizePNG(string file)
{
string tempFile = Path.GetDirectoryName(file) + #"\temp-" + Path.GetFileName(file);
int alphaTransparency = 10;
int alphaFader = 70;
var quantizer = new WuQuantizer();
using (var bitmap = new Bitmap(file))
{
using (var quantized = quantizer.QuantizeImage(bitmap, alphaTransparency, alphaFader))
{
quantized.Save(tempFile, ImageFormat.Png);
}
}
System.IO.File.Delete(file);
System.IO.File.Move(tempFile, file);
}
It will take all files from /assets/temp folder and optimize jpegs and PNG.
I followed this question for the png part. The jpeg part I scraped from several sources. Including PicJam and Image Optimizer. The way I use it is by uploading all files from the user to the temp folder, running this method, uploading the files to azure blob storage, and deleting the local files. I downloaded jpegtran here.
If you don't like to mess with temporary files, I'd advise to use C++/CLI.
Create a C++/CLI dll project in visual studio. Create one static managed class, and define the functions as you want to use them from C#:
public ref class JpegTools
{
public:
static array<byte>^ Optimize(array<byte>^ input)
};
These functions you define can be directly called from C#, and you can implement them with all that C++ offers.
array^ corresponds to a C# byte array. You'll need to use pin_ptr<> to pin the byte array in memory, so you can pass on the data to the unmanaged Jpeg helper function of your choice. C++/CLI has ample support for marshalling managed types to native types. You can also allocate new array with gc_new, to return CLI compatible types. If you have to marshall strings from C# to C++ as part of this excercise, use Mfc/Atl's CString type.
You can statically link all the jpeg code into the dll. A C++ dll can be mixed pure native and C++/CLI code. In our C++/CLI projects, typically only the interface source files know about CLI types, all the rest work with with C++ types.
There's some overhead work to get going this way, but the upside is that your code is compile-time typechecked, and all the dealings with unmanged code and memory are dealt with on the C++ side. It actually works so well that I used C++/CLI to unit test native C++ code almost directly with NUnit.
Good luck!
I would batch process the images before uploading them to your web server, rather then try to process them while serving them. This will lead to less load on the web server and let you use any match image processing tools you wish.
I'm sure that I'm totally late to answer this question, but recently I have faced on lossless jpeg optimization problem and haven't found any suitable C# implementation of jpegtran utility. So, I have decided to implement by myself routines for lossless jpeg size reducing based on C wrapper of modified jpegtran, which you can find here. It comes, that similar realization with use of pure .Net LibJpeg.NET is far more slower than C wrapped solution, so, I haven't included it to the repo. Using of wrapper is quite simple,
if (JpegTools.Transform(jpeg, out byte[] optimized, copy: false, optimize: true))
{
//do smth useful
}
else
{
//report on error or use original jpeg
}
Hope, someone will find it useful.
Why not call punypng.com with Process.Start()? There is no reason why you .net code can't run external programs, provided the processing is done at the time of uploading (rather then when serving the images)
E.g.
upload into a "upload" folder,
have a windows services that watches for new files in the “upload” folder
when you get a new file, start punypng.com to process it and put the output into the correct image folder.