Now am looking after my Friend's Project. In that project my friend encoded some value and store it in Database. Now I need to Use those values. So, I have to decode them. I Don't know where to start it...can anyone help me.
Given the Encoding method :
string strmsg = string.Empty;
byte[] encode = new byte[Text.Length];
encode = Encoding.UTF8.GetBytes(Text);
strmsg = Convert.ToBase64String(encode);
Text is the string which is encoded here.
Note : I Need to decode the "strmsg" value.
This should decode your strmsg back to your text.
byte[] decode = Convert.FromBase64String(strmsg); //strmsg is the encoded text
strmsg = Encoding.UTF8.GetString(decode); //this strmsg is your decoded original text
Related
Another website sends me data with the POST method.
I would like to take this data and insert it into the database.
After some research online, I concluded that ADODB.Stream should do the job for me.
I dont have problem with getting the binary data with Request.TotalBytes.
With the following code, I am not receiving an error but it does not save the data either. So I must be doing something wrong with the ADODB Stream.
tot_bytes = Request.TotalBytes
Set BinaryStream = CreateObject("ADODB.Stream")
BinaryStream.Mode = 3
BinaryStream.Type = 1
BinaryStream.Open
gBinaryData = BinaryStream.Write(tot_bytes)
BinaryStream.Close
Set BinaryStream = Nothing
SQL = "INSERT INTO STATUSES (StatusMessage, StatusDateEntered) VALUES ('"& gBinaryData &"', '"& FormatDateMySQL(NOW) &"')"
Set objAddC = objConn.execute(SQL)
.
Following a successful subscription, Facebook will proceed to call your endpoint every time that there are changes (to the chosen fields or connections). For each update, it will make an HTTP POST request.
The request will have content type of application/json and the body will comprise a JSON-encoded string containing one or more changes.
Note for PHP developers: In PHP, to get the encoded data you would use the following code:
$data = file_get_contents("php://input");
$json = json_decode($data);
First of all, Write method does not return anything, in fact it's just a sub-routine. And Request.TotalBytes is just length of request in bytes. When you need to read request data as array of bytes, you should use Request.BinaryRead(length of bytes). Therefore, in Stream object, you need to read all of bytes using Read method after the writing bytes and setting position to the start.
However, it seems not neccessary in this case if you have to store the data as binary.
I assume that you need the data as text, most likely it's json string. So, you should convert data to string from bytes.
Note that, you need to handle an exception about total bytes. If the Request does not contain anything, Request.TotalBytes equals to zero and since Request.BinaryRead expects a number bigger than zero and less than or equal to total bytes an error occurs.
Dim tot_bytes, postData
tot_bytes = Request.TotalBytes
If tot_bytes > 0 Then
With Server.CreateObject("Adodb.Stream")
.Charset = "utf-8" 'specify the request encoding
.Type = 1 'adTypeBinary, a binary stream
.Open
.Write Request.BinaryRead(tot_bytes) 'Write bytes
.Position = 0 ' set position to the start
.Type = 2 ' adTypeText, stream type is text now
postData = .ReadText 'read all text
.Close
End With
With Server.CreateObject("Adodb.Recordset")
.Open "STATUSES", objConn , , 3
.AddNew
.Fields("StatusMessage").Value = postData
.Fields("StatusDateEntered").Value = Now()
.Update
.Close
End With
Response.Write "data stored successfully"
Else
Response.Write "no post data"
End If
Beside the fact that it is a very bad idea to directly insert your data into a database like this (possible sql injection), how do you post for form data? CLassic ASP can not handle binary data directly either. So this won't work at all.
So whatever you post, first you have to make sure that you post with form enctype="multiform/data".
To get the data into a object try this instead:
byteArray = Request.BinaryRead(Request.TotalBytes)
BUt to handle it, store to database, or save to a file, you need a component, e.g. http://www.motobit.com/help/scptutl/upload.asp or try check this article (special when you upload more thatn just one file): http://www.codeguru.com/csharp/.net/net_asp/article.php/c19297/Pure-ASP-File-Upload.htm.
EDIT:
Antonin Fuller has also made a sample ASP code without using his DLL.
Try this, too:
Private Function RSBinaryToString(xBinary)
'Antonin Foller, http://www.motobit.com
'RSBinaryToString converts binary data (VT_UI1 | VT_ARRAY Or MultiByte string)
'to a string (BSTR) using ADO recordset
Dim Binary
'MultiByte data must be converted To VT_UI1 | VT_ARRAY first.
If vartype(xBinary)=8 Then Binary = MultiByteToBinary(xBinary) Else Binary = xBinary
Dim RS, LBinary
Const adLongVarChar = 201
Set RS = CreateObject("ADODB.Recordset")
LBinary = LenB(Binary)
If LBinary>0 Then
RS.Fields.Append "mBinary", adLongVarChar, LBinary
RS.Open
RS.AddNew
RS("mBinary").AppendChunk Binary
RS.Update
RSBinaryToString = RS("mBinary")
Else
RSBinaryToString = ""
End If
End Function
See more here: http://www.motobit.com/tips/detpg_binarytostring/
Finally you should get the stream, convert it, and work with it.
I am trying to decrypt my password stored in aspnet_membership table...
I am using the following code,
Dim encodedPassword() As Byte = System.Text.Encoding.UTF8.GetBytes(password)
encodedPassword = MyBase.EncryptPassword(encodedPassword)
Dim decryptedPassword() As Byte = MyBase.DecryptPassword(encodedPassword)
If (decryptedPassword IsNot Nothing) Then
Return System.Text.Encoding.UTF8.GetString(decryptedPassword, 0, decryptedPassword.Length)
End If
but at the line of DecryptPassword(encodedPassword) it shows error as
"Length of the data to decrypt is invalid."
I think you need to Base64 Decode it first:
byte[] encodedPassword = Convert.FromBase64String(pass);
byte[] bytes = this.DecryptPassword(encodedPassword);
or in VB.NET:
Dim encodedPassword As Byte() = Convert.FromBase64String(pass)
Dim bytes As Byte() = Me.DecryptPassword(encodedPassword)
Edit: As #Eranga pointed out, this is provided that the MembershipProvider used actually supports decryption and for the default provider the passwordFormat setting controls if it's "hashed", "encrypted" or "plain". By default the setting is "hashed", which means no decryption possible.
Encrypted passwords are base64 encoded before being saved to the database and for that reason they need to be decoded before being decrypted.
I am exporting a HTML table to excel by sending the data as a HTML Table string and setting the content headers:
Dim html as String = "<table><tr><td>example<td></tr></table>"
context.Response.Clear()
context.Response.AddHeader("Content-Disposition", "attachment; filename=" & "exceldata-" & Now.ToString("yyyyMMddHHmmss") & ".xls")
'context.Response.AddHeader("Content-Length", ????)
context.Response.ContentType = "application/octet-stream"
context.Response.Write(response)
context.Response.End()
Is there a simple way of setting the content-length based on the size of the html string? Or should I just leave it blank anyway...would be nice to have the content-length ideally...
I am returning this using a GenericHandler in asp.net
Replace with the encoding of your choice, probably UTF8. Sorry for the C#:
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytes = encoding.GetBytes(html);
int length = bytes.Length;
Source: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.contentlength.aspx
This seems too easy, but is it not just equal to html.Length?
I haven't used ASP.NET, but I guess that the Length() method returns the length of the string in chars, not bytes, so it won't work if your server uses UTF-8 or Unicode for serving the pages.
As noted in another answer, just let the server fill it for you. If you think about it, you don't have to add it when you generate HTML pages from ASP since the web server would generate it based in the response from the ASP module.
I'm using this to write to the Response stream:
using (var writer = new StringWriter())
{
context.Server.Execute(virtualpath, writer);
string s = writer.ToString().Replace(...);
context.Response.Write(s);
}
But I'm getting a byte order mark in the response. Am I screwing up the encoding? How do I NOT return the BOM?
EDIT: SOrry Rubens, my first example was incorrect.
Try this:
context.Server.Execute(virtualpath, context.Response.Output);
EDIT: So, try this to force your encoding:
MemoryStream ms = new MemoryStream();
StreamWriter writer = new StreamWriter(ms);
context.Server.Execute(virtualpath, writer);
context.Response.Write(Encoding.UTF8.GetString(ms.ToArray()).Replace(...));
Server.Execute() returns an encoded stream, but StringWriter() is intended to store simple .NET strings (which are 16-bit Unicode and don't have a BOM) and doesn't know how to decode the incoming bytes. So, the BOM in the response becomes literal characters in your string.
Try writing to a MemoryStream() instead, then decode that back into a string using whichever encoding (UTF-8 or whatever) that the Server.Execute() is passing back. Then you can parse it and write it back to your Response.
I am having an issue with writing a file to the response object. The file is Base64 encoded and is being sent to the ASP code via a web service.
dim contentType, fileName
filename = request("FileName")
contentType = request("ContentType")
If Not Response.isClientConnected Then
Response.end
End If
Response.buffer = true
Response.Clear
Response.Addheader "Content-Disposition", "attachment; filename=" & filename
Response.contenttype = contentType
dim oSoapClient
Set oSoapClient = Server.CreateObject("MSSOAP.SoapClient")
oSoapClient.ClientProperty("ServerHTTPRequest") = True
oSoapClient.mssoapinit "http://myWS/test.asmx?WSDL"
dim sRequest, sResponse
sRequest = "<Root><Attachment id=""" & Request("ID") & """/></Root>"
sResponse = oSoapClient.GetAttachment(sRequest)
Dim oXML: Set oXML = LoadXMLString(sResponse)
Dim oAttachment
set oAttachment = oXML.SelectSingleNode("/Root/Attachment")
if not oAttachment is nothing then
Response.Binarywrite(Base64Decode(oAttachment.attributes.getNamedItem("BinaryData").value))
End if
Response.End
The BinaryWrite is adding extra null characters every other byte. Change it to response.write and it does not put the nulls but terminates the string if a null character is found.
I'm looking for a method to use the binarywrite without it adding the extra nulls. Is it a charset issue?
Thanks
BinaryWrite is doing the correct thing here. What is the return type for your Base64Decode function? Extra null characters between every byte are a symptom of improper handling of UTF-16/UCS-16 unicode data.
Ideally, you should send a VARIANT to BinaryWrite that represents an object exposing IStream, or a SAFEARRAY. If you send in a VARIANT that is a string, it will be received by BinaryWrite as a BSTR, which is 16 bits wide and will exhibit nulls/zeroes every other byte for english/latin charset data.