I am trying to create an application that can both serialise and deserialise data, i can serialise the information however when i try to read the information i am left with an empty list and i do not know why.
My Serialization class
[Serializable()]
public class FileSerilizeObject
{
public static string FileName { get; set; }
public static string Extension { get; set; }
public static string Base64 { get; set; }
public FileSerilizeObject(string filename, string extension, string base64vaulue)
{
FileName = filename;
Extension = extension;
Base64 = base64vaulue;
}
}
}
My serialization/deserialization methods
public void Serialize(List<FileSerilizeObject> List)
{
using (Stream stream = File.Open(savepath, FileMode.OpenOrCreate))
{
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(stream, List);
stream.Close();
}
}
public List<FileSerilizeObject> Deserialised(string OpenPath)
{
List<FileSerilizeObject> defo;
using(Stream stream = File.Open(OpenPath, FileMode.Open))
{
BinaryFormatter bin = new BinaryFormatter();
defo = (List<FileSerilizeObject>)bin.Deserialize(stream);
}
return defo;
}
I have checked to insure that the file paths are correct and that the file itself is not empty.Everything is fine however the "defo" list is always empty so i can only assume the issue is with the defo = (List<FileSerilizeObject>)bin.Deserialize(stream);Line however i do not know why.
You need to remove the static from your properties
[Serializable]
public class FileSerializeObject
{
public string FileName { get; set; }
public string Extension { get; set; }
public string Base64 { get; set; }
public FileSerializeObject(string filename, string extension, string base64vaulue)
{
FileName = filename;
Extension = extension;
Base64 = base64vaulue;
}
}
Try to set the [Serializable()] attribute for each property.
So it would look like this:
[Serializable()]
public class FileSerilizeObject
{
[Serializable()]
public string FileName { get; set; }
[Serializable()]
public string Extension { get; set; }
[Serializable()]
public string Base64 { get; set; }
public FileSerilizeObject(string filename, string extension, string base64vaulue)
{
FileName = filename;
Extension = extension;
Base64 = base64vaulue;
}
}
}
EDIT: Removed static keyword from properties.
I tested your code into a console application and it is working for me, I tested with VS 2013 but I used the same code that you wrote above.
Some details:
1. I removed the word static form the "FileSerilizeObject"
The class FileSerilizeObject
[Serializable()]
public class FileSerilizeObject
{
public string FileName { get; set; }
public string Extension { get; set; }
public string Base64 { get; set; }
public FileSerilizeObject(string filename, string extension, string base64vaulue)
{
FileName = filename;
Extension = extension;
Base64 = base64vaulue;
}
}
Functions
public static void Serialize(List<FileSerilizeObject> List)
{
using (Stream stream = File.Open(#"C:\Users\ttest\Desktop\folder1\data.bin", FileMode.OpenOrCreate))
{
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(stream, List);
stream.Close();
}
}
public static List<FileSerilizeObject> Deserialised(string OpenPath)
{
List<FileSerilizeObject> defo;
using (Stream stream = File.Open(OpenPath, FileMode.Open))
{
BinaryFormatter bin = new BinaryFormatter();
defo = (List<FileSerilizeObject>)bin.Deserialize(stream);
}
return defo;
}
Main
var bytes = Encoding.UTF8.GetBytes("dffesdbcdef==");
var base64 = Convert.ToBase64String(bytes);
FileSerilizeObject f1 = new FileSerilizeObject("test", "jpg", base64);
bytes = Encoding.UTF8.GetBytes("ggasddbcdef==");
base64 = Convert.ToBase64String(bytes);
FileSerilizeObject f2 = new FileSerilizeObject("test2", "png", base64);
bytes = Encoding.UTF8.GetBytes("asddffasdasdasdesdbcdef==");
base64 = Convert.ToBase64String(bytes);
FileSerilizeObject f3 = new FileSerilizeObject("test3", "doc", base64);
List<FileSerilizeObject> lFiles = new List<FileSerilizeObject>();
lFiles.Add(f1);
lFiles.Add(f2);
lFiles.Add(f3);
Serialize(lFiles);
Deserialised(#"C:\Users\rjimen4x\Desktop\tutoriales\data.bin");
Related
I am trying to make webapi which returns image
[HttpGet("[action]")]
public IActionResult GetCheckInPhoto(int checkInId, string dealerNr, int photoIndex, int photoType)
{
var stream = _checkinService.GetCheckInPhoto(checkInId, dealerNr, photoIndex, photoType);
return new MultipartResult(){
new MultipartContent()
{
ContentType = System.Net.Mime.MediaTypeNames.Image.Jpeg,
Name = "xxx",
FileName = "dsada",
Stream = stream
}
};
}
My method GetCheckInPhoto returns MemoryStream where is photo.
how to get FileInfo like Filename or FileType from MemoryStream?
Your "CheckinService" should return something like
public class MyFile
{
public string FileName { get; set; }
public string ContentType { get; set; }
public Stream ReadStream { get; set; }
}
I need to export into a binary file an observable collection. This file will be parsed by an embeded software.
This is my class of Led configuration :
[XmlRoot("ConfLed")]
public class LedVals
{
#region Properties
[XmlAttribute]
public int ID { get; set; }
[XmlAttribute]
public string Type { get; set; } = "Trigger";
[XmlAttribute]
public string Binding { get; set; } = "OFF";
[XmlAttribute]
public int Trigger1 { get; set; } = 0;
[XmlAttribute]
public int Trigger2 { get; set; } = 0;
[XmlAttribute]
public string ColorT0 { get; set; } = "#000000";
[XmlAttribute]
public string ColorT1 { get; set; } = "#000000";
[XmlAttribute]
public string ColorT2 { get; set; } = "#000000";
#endregion
public LedVals()
{
}
public LedVals(int idParam, string typeParam, string bindingParam, int trig1Param, int trig2Param, string c0Param, string c1Param, string c2Param)
{
this.ID = idParam;
this.Type = typeParam;
this.Binding = bindingParam;
this.Trigger1 = trig1Param;
this.Trigger2 = trig2Param;
this.ColorT0 = c0Param;
this.ColorT1 = c1Param;
this.ColorT2 = c2Param;
}
}
And this is my serialize function for the observable collection of LedVals class (ListeLedTable) that I need to export:
public void SerializeLedTable(string filePathParam)
{
try
{
using (Stream mstream = File.Open(filePathParam + ".bin", FileMode.Create))
{
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(mstream, ListeLedTable);
}
}
}
The result is a file with binary values of the class properties and text description of the observable collection structure.
Is there a way to export properties values of a class like this ?
I can use a binaryWriter to write each property of my class in a loop, but I thought there might a simpler solution.
Thank you !
Use Marshal Techniques :
class Program
{
static void Main(string[] args)
{
LedVals ledVals = new LedVals();
int size = Marshal.SizeOf(ledVals); ;
IntPtr ptr = Marshal.AllocHGlobal(size);
byte[] buffer = new byte[Marshal.SizeOf(ledVals)];
Marshal.StructureToPtr(ledVals, ptr, true);
Marshal.Copy(ptr, buffer, 0, Marshal.SizeOf(ledVals));
Marshal.FreeHGlobal(ptr);
FileStream stream = File.OpenWrite("FILENAME");
BinaryWriter bWriter = new BinaryWriter(stream, Encoding.UTF8);
bWriter.Write(buffer);
}
}
[StructLayout(LayoutKind.Sequential)]
public class LedVals
{
public int ID { get; set; }
}
Using .NET binary serialization for any interop is a bad idea.
XML might be a better choice, but embedded devices usually lack the required horsepower to do any XML processing. I don't know what your embedded platform is, but there's a chance you could use Protocol Buffers (Protocol Buffers) to transfer binary data back and forth.
I have two programs: one is test that students take and second is for teachers(teachers create some variants of test and add questions to it); Teacher program creates .bin files with tests and then student's open and take those tests. Data structure(class Question) are similiar in both programs;
Teacher's program class code:
[Serializable]
public class Question
{
public Question(string q_text, Dictionary<string, bool> ans, Image img)
{
text = q_text;
answers = ans;
image = img;
isAnswered = false;
}
public string text { get; set; }
public Dictionary<string, bool> answers { get; set; }
public Image image { get; set; }
public bool isAnswered;
public static void PersistObject(Dictionary<int, Question> q, Stream stream)
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, q);
stream.Close();
}
public static Dictionary<int, Question> LoadObject(Stream stream)
{
try
{
BinaryFormatter formatter = new BinaryFormatter();
Dictionary<int, Question> deserializedObject = (Dictionary<int, Question>)formatter.Deserialize(stream);
stream.Close();
return deserializedObject;
}
catch
{
return null;
}
}
}
}
and student's program class code:
[Serializable]
class Question
{
public Question(string text, Image img, Dictionary<string, bool> ans)
{
question_text = text;
image = img;
answers = ans;
isAnswered = false;
}
public string question_text { get; set; }
public Dictionary<string, bool> answers { get; set; }
public Image image { get; set; }
public bool isAnswered;
public static Dictionary<int, Question> LoadObject(Stream stream)
{
try
{
BinaryFormatter formatter = new BinaryFormatter();
Dictionary<int, Question> deserializedObject = (Dictionary<int, Question>)formatter.Deserialize(stream);
stream.Close();
return deserializedObject;
}
catch
{
return null;
}
}
}
But when I try to read some test in student program:
string file = path + test_number + ".bin";
Stream myStream = File.Open(file, FileMode.Open);
questions = Question.LoadObject(myStream);
it sets questions to null. But when I read those files in teachers program then it's OK.(perhaps, it's OK, because I create those files in teachers mode too). Type of questions is Dictionary<int,Question> .What's the problem?
I want to deserialize following string:
YAHOO.Finance.SymbolSuggest.ssCallback({"ResultSet":{"Query":"google","Result":[{"symbol":"GOOG","name": "Google Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"GGQ1.DE","name": "GOOGLE-A","exch": "GER","type": "S","exchDisp":"XETRA","typeDisp":"Equity"}]}})
Which I download with a WebClient. But before I can deserialize, I need to remove "YAHOO.Finance.SymbolSuggest.ssCallback(" and the ")" at the end:
// get response
WebResponse response = request.EndGetResponse(result);
Stream stream = response.GetResponseStream();
// convert to string
StreamReader reader = new StreamReader(stream);
string output = reader.ReadToEnd();
// cut string
output = output.Substring(39, output.Length - 40);
// convert back to stream
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(output));
So, the response I get is a stream. I convert that stream to a string, change the string and then convert the string back to a stream. Next, I try to deserialize:
// parse json
System.Runtime.Serialization.Json.DataContractJsonSerializer rootSer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(RootObject));
// get root object
RootObject root = (RootObject)rootSer.ReadObject(ms);
// add to listbox
foreach (Result res in root.ResultSet.Result)
{
Dispatcher.BeginInvoke(() => ResultList.Add(res));
}
The problem is I get a nullpointexeption in the foreach...
My classes are like so:
public class Result
{
public string symbol { get; set; }
public string name { get; set; }
public string exch { get; set; }
public string type { get; set; }
public string exchDisp { get; set; }
public string typeDisp { get; set; }
}
public class ResultSet
{
public string Query { get; set; }
public List<Result> Result { get; set; }
}
public class RootObject
{
public ResultSet ResultSet { get; set; }
}
You can use Regex to extract the json from jsonp
output = Regex.Match(output, #".+?\((.+?)\)").Groups[1].Value
I have a console application which needs to connect to SQL Reporting Services on SQL Server Express 2012.
All the exporting logic should be implemented in a separate dll, and the paths should be dynamic (I have loop through various settings for various servers/reports and export them to Excel one by one).
I tried to follow these tutorials:
http://www.aspose.com/docs/display/wordsreportingservices/Rendering+Reports+Programmatically
http://blogs.msdn.com/b/selvar/archive/2010/12/13/accessing-the-reportexecutionservice-render-method-when-reporting-service-2008-r2-is-in-forms-based-authentication.aspx
Basically, I added web references:
http://localhost:80/ReportServer_SQLEXPRESS12/ReportExecution2005.asmx
and
http://localhost:80/ReportServer_SQLEXPRESS12/ReportService2010.asmx
to my dll. Looks good so far, except those nasty app.config settings (I'll have to adjust them dynamically later).
Then I tried to do as in the example:
// Create Web service proxies.
ReportingService2010.ReportingService2010 rs = new ReportingService2010.ReportingService2010();
ReportExecutionService.ReportExecutionService rsExec = new ReportExecutionService.ReportExecutionService();
and got some troubles:
Error 76 The type or namespace name 'ReportExecutionService' does not exist in the namespace 'MyDllNamespace.ReportExecutionService' (are you missing an assembly reference?)
Error 74 The type or namespace name 'ReportingService2010' does not exist in the namespace 'MyDllNamespace.ReportingService2010' (are you missing an assembly reference?)
Now where do I go next, how do I use the Reporting Services API, if I cannot even create a proxy object? Or should I better use ServerReport class form the Winforms ReportViewer instead of these web references?
Even one of Microsoft examples is using ReportViewer in a console application, but it seems a bit awkward to import Winforms in a console app.
I hope the following will help (extract of pertinent parts of code)
using (ZUtilities.SSRS.Report report = new ZUtilities.SSRS.Report {
ReportServerPath = VParameter.GetValue("SSRS_WebServiceUrl", _repo.Parameters).ToString(),
Format = rformat,
ReportPath = "some_path_on_ssrs_server"
}) {
report.Params.Add("Id", id.ToString());
report.Credentials = nwc;
MemoryStream ms = new MemoryStream();
report.Render().CopyTo(ms);
FileContentResult fsr = new FileContentResult(ms.ToArray(), rctype);
fsr.FileDownloadName = String.Format("EPV-{0}-{1:yyyyMMdd}.{2}", epv.ExternalReference, DateTime.Now, fext);
ms.Close();
return fsr;
}
with the following (be carefull to the stream management)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace ZUtilities.SSRS {
public enum ReportFormats {
Html = 1,
MHtml,
Pdf,
Xlsx,
Docx
}
public class ReportFormat {
static ReportFormat() {
Html = new ReportFormat { Code = ReportFormats.Html, Instruction = "HTML4.0" };
MHtml = new ReportFormat { Code = ReportFormats.MHtml, Instruction = "MHTML" };
Pdf = new ReportFormat { Code = ReportFormats.Pdf, Instruction = "PDF" };
Xlsx = new ReportFormat { Code = ReportFormats.Xlsx, Instruction = "EXCELOPENXML" };
Docx = new ReportFormat { Code = ReportFormats.Docx, Instruction = "WORDOPENXML" };
}
private ReportFormat() {
}
public ReportFormats Code { get; set; }
public String Instruction { get; set; }
public static ReportFormat Html { get; private set; }
public static ReportFormat MHtml { get; private set; }
public static ReportFormat Pdf { get; private set; }
public static ReportFormat Xlsx { get; private set; }
public static ReportFormat Docx { get; private set; }
public static ReportFormat ByCode(ReportFormats code) {
switch (code) {
case ReportFormats.Html: return Html;
case ReportFormats.MHtml: return Html; //<<======================
case ReportFormats.Pdf: return Pdf;
case ReportFormats.Xlsx: return Xlsx;
case ReportFormats.Docx: return Docx;
default : return null;
}
}
}
public class Report : IDisposable {
private HttpWebRequest _httpWReq;
private WebResponse _httpWResp;
public Report() {
_httpWReq = null;
_httpWResp = null;
Format = ReportFormats.Html;
Params = new Dictionary<String, String>();
}
public Dictionary<String, String> Params { get; set; }
public String ReportServerPath { get; set; }
public String ReportPath { get; set; }
public ReportFormats Format { get; set; }
public NetworkCredential Credentials { get; set; }
//public String PostData { get { return String.Format("rs:Command=Render&rs:Format={0}", ReportFormat.ByCode(Format).Instruction); } }
public String PostData { get {
StringBuilder sb = new StringBuilder(1024);
sb.AppendFormat("rs:Command=Render&rs:Format={0}", ReportFormat.ByCode(Format).Instruction);
if (Format == ReportFormats.Html) {
sb.Append("&rc:Toolbar=false");
}
foreach (var kv in Params) {
sb.AppendFormat("&{0}={1}", kv.Key, kv.Value);
}
return sb.ToString();
} }
public String ReportFullPath { get { return ReportServerPath + "?/" + ReportPath; } }
public Stream Render() {
_httpWReq = (HttpWebRequest)HttpWebRequest.Create(ReportFullPath);
_httpWReq.Method = "POST";
if (Credentials != null)
_httpWReq.Credentials = Credentials;
byte[] byteArray = Encoding.UTF8.GetBytes(PostData);
_httpWReq.ContentType = "application/x-www-form-urlencoded";
_httpWReq.ContentLength = byteArray.Length;
Stream dataStream = _httpWReq.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
if (_httpWResp != null )
_httpWResp.Close();
_httpWResp = _httpWReq.GetResponse();
return _httpWResp.GetResponseStream();
}
public void RenderTo(String fileName) {
Stream receiveStream = Render();
Stream ds = File.Open(fileName, FileMode.Create);
receiveStream.CopyTo(ds);
ds.Close();
receiveStream.Close();
}
public void Dispose() {
if (_httpWResp != null) {
_httpWResp.Close();
_httpWResp = null;
}
if (_httpWReq != null) {
_httpWReq = null;
}
}
}
}