Can't import ore create X509Certificate2 object from byte array - x509certificate

So I encountered a weird issue while trying importing .pfx file into x509 object.
For some reason, I don't understand, trying opening, or generating new object, in this manner doesn't work.
cert = new X509Certificate2();
cert.Import(byte []);
cert = new X509Certificate2(byte []);
The error I'm getting is:'X509Certificate is immutable on this platform. Use the equivalent constructor instead.'
I saw this issue: https://github.com/jitbit/AspNetSaml/issues/9
the only way I could make it work is to give an explicit path to the .pfx path which worked.
That's not my intention, however.
Any idea?

What should work for you, is one of the constructor overload.
Use the other constructor of X509Certificate2 class which takes two params. First one is the byteArray and second one is the password string.
byte[] certData;
var memorystream = new MemoryStream();
MyMethodToPopluateMemoryStream(memorystream);
certData = memorystream.ToArray();
cert = new X509Certificate2(certData,"CERT_PASSWORD");
This way you can avoid the deprecated Import method.
After few hours of struggle above code worked fine for me. I've tested this code on .net6 .
Happy Coding.

Related

Progress while deserializing JSON

I'm deserializing a huge JSON (1.4 GB) via a stream, because I don't want to load the whole content into memory in advance just for parsing. That's working fine, but it takes ~80 seconds, so I want to display a progress.
public JObject DeserializeViaStream(string filename)
{
object obj;
var serializer = new JsonSerializer();
using (var sr = new StreamReader(new FileStream(filename, FileMode.Open)))
{
using (var jsonTextReader = new JsonTextReader(sr))
{
obj = serializer.Deserialize(jsonTextReader);
}
}
return (JObject) obj;
}
I have not yet tried but only one idea: I could implement my own stream reader which keep track of the bytes being read and comparing that to the file length.
Is there a built-in option or easier way to do this?
I ended up using the idea I had. Luckily there's already a ProgressStream available by Mel Green (archive.org). The original URL is no longer available.
Please note:
this approach may not work for all situations and with all libraries forever. This is due to the fact that the Seek() operation provides random access, and someone could read the file multiple times.
I can't post the source code here, because it was released under an unclear license.

ObjectUtil.copy won't copy any ArrayCollection

For a while now in my app I've used ObjectUtil.copy to copy array collections. Recently we've been making a lot of changes to the app and its started breaking on any of my copy commands. I originally thought it was due to custom classes in the arrays but ruled that out by testing empty or simple ArrayCollections.
Neither of these will work for me:
var a:ArrayCollection = ObjectUtil.copy(new ArrayCollection());
newWindow.months = ObjectUtil.copy(months) as ArrayCollection;
In the second line, newWindow is just a new canvas I'm going to show with a 'months' property and months is an ArrayCollection with only strings in it.
Inside the .copy() function it breaks on buffer.writeObject(value); and throws this error 'ArgumentError: Error #2004: One of the parameters is invalid.'
Copy source array
newWindow.months = new ArrayCollection(ObjectUtil.copy(months.source) as Array);

Read Request Body in ASP.NET

How does one read the request body in ASP.NET? I'm using the REST Client add-on for Firefox to form a GET request for a resource on a site I'm hosting locally, and in the Request Body I'm just putting the string "test" to try to read it on the server.
In the server code (which is a very simple MVC action) I have this:
var reader = new StreamReader(Request.InputStream);
var inputString = reader.ReadToEnd();
But when I debug into it, inputString is always empty. I'm not sure how else (such as in FireBug) to confirm that the request body is indeed being sent properly, I guess I'm just assuming that the add-on is doing that correctly. Maybe I'm reading the value incorrectly?
Maybe I'm misremembering my schooling, but I think GET requests don't actually have a body. This page states.
The HTML specifications technically define the difference between "GET" and "POST" so that former means that form data is to be encoded (by a browser) into a URL while the latter means that the form data is to appear within a message body.
So maybe you're doing things correctly, but you have to POST data in order to have a message body?
Update
In response to your comment, the most "correct" RESTful way would be to send each of the values as its own parameter:
site.com/MyController/MyAction?id=1&id=2&id=3...
Then your action will auto-bind these if you give it an array parameter by the same name:
public ActionResult MyAction(int[] id) {...}
Or if you're a masochist you can maybe try pulling the values out of Request.QueryString one at a time.
I was recently reminded of this old question, and wanted to add another answer for completeness based on more recent implementations in my own work.
For reference, I've blogged on the subject recently.
Essentially, the heart of this question was, "How can I pass larger and more complex search criteria to a resource to GET a filtered list of objects?" And it ended up boiling down to two choices:
A bunch of GET query string parameters
A POST with a DTO in the request body
The first option isn't ideal, because implementation is ugly and the URL will likely exceed a maximum length at some point. The second option, while functional, just didn't sit right with me in a "RESTful" sense. After all, I'm GETting data, right?
However, keep in mind that I'm not just GETting data. I'm creating a list of objects. Each object already exists, but the list itself doesn't. It's a brand new thing, created by issuing search/filter criteria to the complete repository of objects on the server. (After all, remember that a collection of objects is still, itself, an object.)
It's a purely semantic difference, but a decidedly important one. Because, at its simplest, it means I can comfortably use POST to issue these search criteria to the server. The response is data which I receive, so I'm "getting" data. But I'm not "GETting" data in the sense that I'm actually performing an act of creation, creating a new instance of a list of objects which happens to be composed of pre-existing elements.
I'll fully admit that the limitation was never technical, it was just semantic. It just never "sat right" with me. A non-technical problem demands a non-technical solution, in this case a semantic one. Looking at the problem from a slightly different semantic viewpoint resulted in a much cleaner solution, which happened to be the solution I ended up using in the first place.
Aside from the GET/POST issue, I did discover that you need to set the Request.InputStream position back to the start. Thanks to this answer I found.
Specifically the comment
Request.InputStream // make sure to reset the Position after reading or later reads may fail
Which I translated into
Request.InputStream.Seek(0,0)
I would try using the HttpClient (available via Nuget) for doing this type of thing. Its so much easier than the System.Net objects
Direct reading from the Request.InputStream dangerous because when re-reading will get null even if the data exists. This is verified in practice.
Reliable reading is performed as follows:
/*Returns a string representing the content of the body
of the HTTP-request.*/
public static string GetFromBodyString(this HttpRequestBase request)
{
string result = string.Empty;
if (request == null || request.InputStream == null)
return result;
request.InputStream.Position = 0;
/*create a new thread in the memory to save the original
source form as may be required to read many of the
body of the current HTTP- request*/
using (MemoryStream memoryStream = new MemoryStream())
{
request.InputStream.CopyToMemoryStream(memoryStream);
using (StreamReader streamReader = new StreamReader(memoryStream))
{
result = streamReader.ReadToEnd();
}
}
return result;
}
/*Copies bytes from the given stream MemoryStream and writes
them to another stream.*/
public static void CopyToMemoryStream(this Stream source, MemoryStream destination)
{
if (source.CanSeek)
{
int pos = (int)destination.Position;
int length = (int)(source.Length - source.Position) + pos;
destination.SetLength(length);
while (pos < length)
pos += source.Read(destination.GetBuffer(), pos, length - pos);
}
else
source.CopyTo((Stream)destination);
}

Is it possible to do lightweight REST calls in Flex?

We are converting a Flex application to use some REST APIs.
When adding the mx.rpc.http.HTTPService class to the code, the SWF binary output grew from 175KB to 260KB. This is an unacceptable hit.
Is there any better way to do lightweight REST calls from a Flex app? Are we better off using an external interface JS just to make the calls from there?
flash.net.URLLoader is built into the runtime and won't cause any increase in filesize. I've used it as a JSON client before, so you shouldn't have any troubles with it.
Below is a very simple example. See documentation for HTTP_STATUS and HTTP_RESPONSE_STATUS for information on their restrictions.
var request: URLRequest = new URLRequest("http://tempuri.org/service/json");
request.method = "POST";
request.contentType = "application/json";
request.data = JSON.encode(jsonObject);
var loader : URLLoader = new URLLoader(request);
// Only supported by some browsers
loader.addEventHandler(HTTPStatusEvent.HTTP_STATUS, statusCodeReceived);
// AIR only
loader.addEventHandler(HTTPStatusEvent.HTTP_RESPONSE_STATUS, statusCodeReceived);
loader.addEventHandler(Event.COMPLETE, function(ev:Event):void
{
var responseJson : String = request.data as String;
var responseJsonObject : String = JSON.decode(responseJson);
});
loader.addEventHandler(SecurityErrorEvent.SECURITY_ERROR, errorHandler);
loader.addEventHandler(IOErrorEvent.IO_ERROR, errorHandler);
I've always thought a good approach to this would be to create a small interface to the browser's JavaScript HTTP API, XmlHttpRequest. I've never tried it, but I've looked into it, and it looked like it might be fairly straightforward.
This would have the added benefit of working around Flash Player's security restrictions which make its HTTP support terribly crippled.

Dispose a stream in a BizTalk pipeline component?

I'm fairly new to BizTalk and creating a custom pipeline component. I have seen code in examples that are similar to the following:
public void Disassemble(IPipelineContext pContext, IBaseMessage pInMsg)
{
Stream originalDataStream = pInMsg.BodyPart.GetOriginalDataStream();
StreamReader strReader = new StreamReader(originalDataStream);
string strOriginalData = strReader.ReadToEnd();
byte[] bufferOriginalMessage = new byte[strOriginalData.Length];
bufferOriginalMessage = ASCIIEncoding.Default.GetBytes(strOriginalData);
Stream ms = new MemoryStream();
ms.Write(bufferOriginalMessage, 0, strOriginalD
//other stuff here
ms.Seek(0, SeekOrigin.Begin);
pInMsg.BodyPart.Data = ms;
}
But nowhere in the method is the StreamReader being closed or disposed. The method simply exits.
Normally when using StreamReader and other classes, it is best practice to use a using statement so that the stream is automatically disposed.
Is there a particular reason (perhaps in BizTalk) why you wouldn't dispose this StreamReader?
I have not found any information on this point. Can anyone help?
In general, yes, it's a good practice to close readers and streams you don't need anymore. That said, there might not necessarily be 100% required everytime. For example, closing the reader would close the underlying stream normally, but chances are, something else is probably already aware of the stream and will close it at the right time on it's own.
What is good practice, however, is to add any streams you use in a pipeline component with a lifetime matching that of the message to the resource tracker, so that BizTalk can dispose them automatically when the pipeline execution finishes and the message has been processed.

Resources