Let's say a create an (executable) assembly in memory by
compiling a code string. Then I want to serialize this assembly
object into a byte array and then store it in a database. Then later
on I want to retrieve the byte array from the database and deserialize
the byte array back into an assembly object, then invoke the entry
point of the assembly.
At first I just tried to do this serialization like I would any other simple object in .net, however apparently that won't work with an assembly object. The assembly object contains a method called GetObjectData which gets serialization data necessary to reinstantiate the assembly. So I'm somewhat confused as to how I piece all this together for my scenario.
The answer only needs to show how to take an assembly object, convert it into a byte array, convert that back into an assembly, then execute the entry method on the deserialized assembly.
A dirty trick to get the assembly bytes using reflection:
MethodInfo methodGetRawBytes = assembly.GetType().GetMethod("GetRawBytes", BindingFlags.Instance | BindingFlags.NonPublic);
object o = methodGetRawBytes.Invoke(assembly, null);
byte[] assemblyBytes = (byte[])o;
Explanation: at least in my sample (assembly was loaded from byte array) the assembly instance was of type "System.Reflection.RuntimeAssembly". This is an internal class, so it can be accessed only using reflection. "RuntimeAssembly" has a method "GetRawBytes", which return the assembly bytes.
An assembly is more conveniently represented simply as a binary dll file. If you think of it like that, the rest of the problems evaporate. In particlar, look at Assembly.Load(byte[]) for loading an Assembly from binary. To write it as binary, use CompileAssemblyFromSource and look at the result's PathToAssembly - then File.ReadAllBytes(path) to obtain the binary from the file.
System.Reflection.Assembly is ISerializable and can simply be serialized like so:
Assembly asm = Assembly.GetExecutingAssembly();
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, asm);
and deserialization is just as simple but call BinaryFormatter.Deserialize instead.
Here is my example:
public static byte[] SerializeAssembly()
{
var compilerOptions = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } };
CSharpCodeProvider provider = new CSharpCodeProvider(compilerOptions);
CompilerParameters parameters = new CompilerParameters()
{
GenerateExecutable = false,
GenerateInMemory = false,
OutputAssembly = "Examples.dll",
IncludeDebugInformation = false,
};
parameters.ReferencedAssemblies.Add("System.dll");
ICodeCompiler compiler = provider.CreateCompiler();
CompilerResults results = compiler.CompileAssemblyFromSource(parameters, StringClassFile());
return File.ReadAllBytes(results.CompiledAssembly.Location);
}
private static Assembly DeserializeAssembyl(object fromDataReader)
{
byte[] arr = (byte[])fromDataReader;
return Assembly.Load(arr);
}
private string StringClassFile()
{
return "using System;" +
"using System.IO;" +
"using System.Threading;" +
"namespace Examples" +
"{" +
" public class FileCreator" +
" {" +
" private string FolderPath { get; set; }" +
" public FileCreator(string folderPath)" +
" {" +
" this.FolderPath = folderPath;" +
" }" +
" public void CreateFile(Guid name)" +
" {" +
" string fileName = string.Format(\"{0}.txt\", name.ToString());" +
" string path = Path.Combine(this.FolderPath, fileName);" +
" if (!File.Exists(path))" +
" {" +
" using (StreamWriter sw = File.CreateText(path))" +
" {" +
" sw.WriteLine(\"file: {0}\", fileName);" +
" sw.WriteLine(\"Created from thread id: {0}\", Thread.CurrentThread.ManagedThreadId);" +
" }" +
" }" +
" else" +
" {" +
" throw new Exception(string.Format(\"duplicated file found {0}\", fileName));" +
" }" +
" }" +
" }" +
"}";
}
Related
Good Day,
i am trying to write an R code in .net to run as a WCF function. this function is suppose to import a csv file to MSSQL using R using .net code.
I am getting a stackoverflow error when i try to reference the odbc library over wcf, however if i try to run the function using debug instance it passes that point.
public string R_to_MSSQL_Server(string data, string Server, string Database,string Tablename)
{
StartupParameter rinit = new StartupParameter();
rinit.Quiet = true;
rinit.RHome = #"C:\Program Files\R\R-3.4.4\";
rinit.Home = #"C:\R";
REngine.SetEnvironmentVariables();
REngine engine = REngine.GetInstance(null, true, rinit);
StringBuilder Data = new StringBuilder();
Data.Append(data);
string filepath = Path.Combine(Path.GetTempPath(), "RTable.csv");
//"UID= Tester;" +
//"PWD= rstudioapi::askForPassword(\"password\"); " +
try
{
UploadCSV(Data);
filepath = PathCleaning(filepath);
engine.Evaluate("Data <- read.csv(file<- '" + filepath + "', heade= TRUE, sep=',')");
engine.Evaluate("Table <- data.frame(Data)");
engine.Evaluate("connectionString <- ' " +
"driver={SQL Server}; " +
"server= "+ Server + "; " +
"database=" + Database + ";" +
"UID= Tester;" +
"PWD= rstudioapi::askForPassword(\"password\"); " +
"'");
engine.Evaluate("library(odbc)");
engine.Evaluate("library(healthcareai)");
engine.Evaluate("con<- DBI::dbConnect(odbc::odbc(),.connection_string=connectionString)");
engine.Evaluate("DBI::dbwriteTable(conn=con," + Tablename + " , Table)");
return "Completed successfully";
}
catch( Exception x)
{
return "Fail to complete" + x;
}
}
the error when i run it through WCF hits at "engine.evaluate("library(odbc)");"
This is where its being called by another machine accessing it through wcf.
static void Main(string[] args)
{
MainServiceClient client = new MainServiceClient();
string tablename = "Test Table";
string Table = "";
string Pkey ="Name";
Table=File.ReadAllText(#"\\lonvmfs02\Home\kr.williams\TestTable2.csv");
string query = client.R_to_MSSQL_Server(Table, "stage04", "CWDataSets", "Tester");
this is the error thats being thrown inside the WCF Machine ( W3wp debugging ).
System.StackOverflowException
HResult=0x800703E9
Source=
StackTrace:
this is all the exception details give.
how do it increase the size of the stack / get around this problem?
Thanks
The process cannot access the file 'file path' because it is being used by another process.
i have found these 2 question
File being used by another process after using File.Create()
and
Does File.AppendAllText close the file after the operation
this is an API that i have and need to save every request that comes in and the result that goes out,
there might be more than one request that a give time
my code
public static void SaveTheRequestAndResponse(string type, SearchRequest searchRequest = null, dynamic result = null)
{
var FilePath = AppDomain.CurrentDomain.BaseDirectory + #"SearchRequest";
bool exists = Directory.Exists(FilePath);
if (!exists)
{
var stream = Directory.CreateDirectory(FilePath);
}
if (type == "request")
{
string Space = ", ";
StringBuilder request = new StringBuilder();
request.Append("Search Id : " + searchRequest.ID);
request.Append(Space + "Company Name : " + searchRequest.CompanyName);
request.Append(Space + "Country Code : " + searchRequest.CountryCode);
request.Append(Space + "Search Type : " + searchRequest.SeacrhType);
request.Append(Space + "Request Time : " + DateTime.Now + Environment.NewLine);
var DataToBeSave = request.ToString();
System.IO.File.AppendAllText(FilePath + #"\" + "FileNAme" + DateTime.Now.ToString("dd-MM-yyyy") + ".txt", DataToBeSave + Environment.NewLine);
}
else
{
string Space = ", ";
StringBuilder SearchResult = new StringBuilder();
SearchResult.Append("The result for Request" + Space);
SearchResult.Append("Search Id : " + searchRequest.ID + Space);
SearchResult.Append("States Code : " + result.StatusCode + Space);
SearchResult.Append("Result Time : " + DateTime.Now + Environment.NewLine);
var DataToBeSave = SearchResult.ToString();
System.IO.File.AppendAllText(FilePath + #"\" + "FileNAme" + DateTime.Now.ToString("dd-MM-yyyy") + ".txt", DataToBeSave + Environment.NewLine);
}
}
my understanding is that the File.AppendAllText will close after the Operation so why do i get the this error
my code is having an race condition, and this is because the API is being call by more than one user at each given time, even that
System.IO.File.AppendAllText(FilePath + #"\" + "FileNAme" + DateTime.Now.ToString("dd-MM-yyyy") + ".txt", DataToBeSave + Environment.NewLine);
will close after the Operation, it still need time do its work and only one connection can be open at each give time so the thread need to be lock and that can be done by
private static Object thisLock = new Object();
lock (thisLock)
{
System.IO.File.AppendAllText(FilePath + #"\" + "DandB" + DateTime.Now.ToString("dd-MM-yyyy") + ".txt", DataToBeSave + Environment.NewLine);
}
Thanks to Abydal
I am sending audio to GCS, via "https://speech.googleapis.com/v1/speech:recognize?key=<my key>", the following way:
byte[] audioBytes = g_NPCAudioListener.GetAudioClipMonoData16(88200);
string jsonData = "{" +
"\"config\": {" +
"\"encoding\": \"LINEAR16\"," +
"\"sampleRateHertz\": 48000," +
"\"languageCode\": \"en-US\"" +
"}," +
"\"audio\": {" +
"\"content\" : \"" + Convert.ToBase64String(audioBytes) + "\"" +
"}" +
"}";
byte[] postData = System.Text.Encoding.UTF8.GetBytes(jsonData);
g_NPCController.Debug("Sending to google: " + jsonData);
using (WWW req = new WWW(g_Google_Speech_URL, postData, g_JSONHeaders)) {
yield return req;
if (req.error == null) {
g_NPCController.Debug(req.text.Replace("\n", "").Replace(" ", ""));
} else {
string msg = Convert.ToString(req.bytes);
g_NPCController.Debug("Google Speech Error: " + req.error + "\n - error: " + req.text);
}
}
Everything is up to specification, however, I keep getting nothing but an error flag with an empty body.
While working on the main JSON impl, I was getting "Invalid parameter" and such... but now that I am streaming 88200 chunks of 16-bit uncompressed audio bytes, I keep getting an error with no text attached to it - not even a code. Did anyone come across a similar situation?
If relevant, the audio I get it from an AudioClip in Unity, then convert the 32-bit float[] to a byte[originalAudio.Length * sizeof(float)] and then to base64 as required.
Thanks.
Below is my code,
List<string> modified_listofstrings = new List<string>();
string sJSON = "";
System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
resulted_value = final_resulted_series_name + ":" + period_name + ":" + period_final_value;
modified_listofstrings.Add(resulted_value);
json_resultedvalue = JsonConvert.SerializeObject(resulted_value);
modified_listofstrings.Add(json_resultedvalue);
sJSON = jSearializer.Serialize(modified_listofstrings);
return sJSON;
But on following line ,
sJSON = jSearializer.Serialize(modified_listofstrings);
I am getting an error as Cannot implicitly convert type string to system.collection.generic.list
Let me fix your approach - instead of building JSON strings using your data, and then putting them into a list and trying again to serialize that, what you should do is build your data structure and then serialize it in one go.
Since I couldn't figure out the structure of the data in your post, here is an example with a different format:
public struct Person
{
public string Name;
public int Age;
public List<string> FavoriteBands;
}
The easiest way to serialize it is to use Newtonsoft JSON. If you have an object called person, then you would serialize it using
string json = JsonConvert.SerializeObject(person);
Now suppose you have a list of these objects i.e. List<Person> people = GetTheListFromSomewhere();, then you would serialize it using
string json = Newtonsoft.Json.JsonConvert.SerializeObject(people);
Go ahead and try it!
resulted_value = final_resulted_series_name + ":" + period_name + ":" + period_final_value;
This is not a valid JSON. It must have key, value format separated by comma. I guess it should be:
resulted_value = "{series_name : \"" + final_resulted_series_name + "\",period_name: \"" + period_name + "\",period_final_value: \"" + period_final_value + "\"}";
so the result should be something like this:
{series_name: "whatever_series_name_is", period_name:
"whatever_period_name_is",period_final_value:
"whatever_period_final_value_is"}
I am generating HTML files on the fly, and I would like to create a PDF from the final file. I am using the following to generate the HTML file:
public static void WriteHTML(string cFile, List<Movie> mList)
{
int lineID = 0;
string strHeader, strMovie, strGenre, tmpGenre = null;
string strPDF = null;
// initiates streamwriter for catalog output file
FileStream fs = new FileStream(cFile, FileMode.Create);
StreamWriter catalog = new StreamWriter(fs);
strHeader = "<style type=\"text/css\">\r\n" + "<!--\r\n" + "tr#odd {\r\n" + " background-color:#e2e2e2;\r\n" + " vertical-align:top;\r\n" + "}\r\n" + "\r\n" + "tr#even {\r\n" + " vertical-align:top;\r\n" + "}\r\n" + "div#title {\r\n" + " font-size:16px;\r\n" + " font-weight:bold;\r\n" + "}\r\n" + "\r\n" + "div#mpaa {\r\n" + " font-size:10px;\r\n" + "}\r\n" + "\r\n" + "div#genre {\r\n" + " font-size:12px;\r\n" + " font-style:italic;\r\n" + "}\r\n" + "\r\n" + "div#plot {\r\n" + " height: 63px;\r\n" + " font-size:12px;\r\n" + " overflow:hidden;\r\n" + "}\r\n" + "-->\r\n" + "</style>\r\n" + "\r\n" + "<html>\r\n" + " <body>\r\n" + " <table>\r\n";
catalog.WriteLine(strHeader);
strPDF = strHeader;
foreach (Movie m in mList)
{
tmpGenre = null;
strMovie = lineID == 0 ? " <tr id=\"odd\" style=\"page-break-inside:avoid\">\r\n" : " <tr id=\"even\" style=\"page-break-inside:avoid\">\r\n";
catalog.WriteLine(strMovie);
strPDF += strMovie;
foreach (string genre in m.Genres)
tmpGenre += ", " + genre + "";
strGenre = tmpGenre != null ? tmpGenre.Substring(2) : null;
strMovie = " <td>\r\n" + " <img src=\".\\images\\" + m.ImageFile + "\" width=\"75\" height=\"110\">\r\n" + " </td>\r\n" + " <td>\r\n" + " <div id=\"title\">" + m.Title + "</div>\r\n" + " <div id=\"mpaa\">" + m.Certification + " " + m.MPAA + "</div>\r\n" + " <div id=\"genre\">" + strGenre + "</div>\r\n" + " <div id=\"plot\">" + m.Plot + "</div>\r\n" + " </td>\r\n" + " </tr>\r\n";
catalog.WriteLine(strMovie);
strPDF += strMovie;
lineID = lineID == 0 ? 1 : 0;
}
string closingHTML = " </table>\r\n" + " </body>\r\n" + "</html>";
catalog.WriteLine(closingHTML);
strPDF += closingHTML;
WritePDF(strPDF, cFile + ".PDF");
catalog.Close();
}
Once completed, I want to call the following function to generate the PDF file:
public static void WritePDF(string cFile, string pdfFile)
{
WkHtmlToPdfConverter w = new WkHtmlToPdfConverter();
byte[] strHTML = w.Convert(cFile);
File.WriteAllBytes(pdfFile, strHTML);
w.Dispose();
}
I've discovered that the .Convert function will convert HTML code to PDF, not a file. Secondly, when I pass in the HTML code directly, the images are not appearing in the PDF. I know there is an issue with .GIF files, but these are all .JPG files.
I've read a lot about how good wkhtmltopdf is, and the guy who wrote WkHTMLToSharp posted his project all over SO, but I've been disappointed by the lack of documentation for it.
I WANT to be able to pass in a file to convert, change the margins (I know this is possible, I just need to figure out the correct settings), have it convert images correctly, and most importantly, to not break up my items across multiple pages (support "page-break-inside:avoid" or something similar).
I'd love to see how others are using this!
I have coded an example about how to create a PDF from HTML. I just updated it to also print images.
https://github.com/hmadrigal/playground-dotnet/tree/master/MsDotNet.PdfGeneration
(In my blog post I explain most of the project https://hmadrigal.wordpress.com/2015/10/16/creating-pdf-reports-from-html-using-dotliquid-markup-for-templates-and-wkhtmltoxsharp-for-printing-pdf/ )
Pretty much you have two options:
1: Using file:// and the fullpath to the file.
<img alt="profile" src="{{ employee.PorfileFileName | Prepend: "Assets\ProfileImage\" | ToLocalPath }}" />
2: Using URL Data (https://en.wikipedia.org/wiki/Data_URI_scheme)
<img alt="profile" src="data:image/png;base64,{{ employee.PorfileFileName | Prepend: "Assets\ProfileImage\" | ToLocalPath | ToBase64 }}" />
Cheers,
Herb
Use WkHtmlToXSharp.
Download the latest DLL from Github
public static string ConvertHTMLtoPDF(string htmlFullPath, string pageSize, string orientation)
{
string pdfUrl = htmlFullPath.Replace(".html", ".pdf");
try
{
#region USING WkHtmlToXSharp.dll
//IHtmlToPdfConverter converter = new WkHtmlToPdfConverter();
IHtmlToPdfConverter converter = new MultiplexingConverter();
converter.GlobalSettings.Margin.Top = "0cm";
converter.GlobalSettings.Margin.Bottom = "0cm";
converter.GlobalSettings.Margin.Left = "0cm";
converter.GlobalSettings.Margin.Right = "0cm";
converter.GlobalSettings.Orientation = (PdfOrientation)Enum.Parse(typeof(PdfOrientation), orientation);
if (!string.IsNullOrEmpty(pageSize))
converter.GlobalSettings.Size.PageSize = (PdfPageSize)Enum.Parse(typeof(PdfPageSize), pageSize);
converter.ObjectSettings.Page = htmlFullPath;
converter.ObjectSettings.Web.EnablePlugins = true;
converter.ObjectSettings.Web.EnableJavascript = true;
converter.ObjectSettings.Web.Background = true;
converter.ObjectSettings.Web.LoadImages = true;
converter.ObjectSettings.Load.LoadErrorHandling = LoadErrorHandlingType.ignore;
Byte[] bufferPDF = converter.Convert();
System.IO.File.WriteAllBytes(pdfUrl, bufferPDF);
converter.Dispose();
#endregion
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
return pdfUrl;
}
You can use Spire.Pdf to do so.
This component could convert html to pdf.
PdfDocument pdfdoc = new PdfDocument();
pdfdoc.LoadFromHTML(fileFullName, true, true, true);
//String url = "http://www.e-iceblue.com/";
//pdfdoc.LoadFromHTML(url, false, true, true);
pdfdoc.SaveToFile("FromHTML.pdf");
We're also using wkhtmltopdf and are able to render images correctly. However, by default the rendering of images is disabled.
You have to specify those options on your converter instance:
var wk = _GetConverter()
wk.GlobalSettings.Margin.Top = "20mm";
wk.GlobalSettings.Margin.Bottom = "10mm";
wk.GlobalSettings.Margin.Left = "10mm";
wk.GlobalSettings.Margin.Right = "10mm";
wk.GlobalSettings.Size.PaperSize = PdfPaperSize.A4;
wk.ObjectSettings.Web.PrintMediaType = true;
wk.ObjectSettings.Web.LoadImages = true;
wk.ObjectSettings.Web.EnablePlugins = false;
wk.ObjectSettings.Web.EnableJavascript = true;
result = wk.Convert(htmlContent);