I have this code in C# which use it to generate a QR code base64 and want to decode the output into original TLV values as strings, for example in my code I am generating the QR code encode base64 and want to get back with original TLVs tags and store it in separate string per each value
using System;
namespace tlvgenerator
{
class Program
{
static void Main(string[] args)
{
string Name = GetHexString(1, Encoding.UTF8.GetBytes("Name")); //Tag1
string Serial = GetHexString(2, Encoding.UTF8.GetBytes("123456789123456789")); //Tag2
string dateTimeStr = GetHexString(3, Encoding.UTF8.GetBytes("2022-07-17T11:20:51Z")); //Tag3
string ModelNum = GetHexString(4, Encoding.UTF8.GetBytes("12356.123")); //Tag4
string PartNo = GetHexString(5, Encoding.UTF8.GetBytes("9782.45")); //Tag5
string SN = GetHexString(6, Encoding.UTF8.GetBytes("abcdef12345"));//Tag6
string Shelf = GetHexString(7, Encoding.UTF8.GetBytes("A2F345"));//Tag6
string Area = GetHexString(8, Convert.FromBase64String(Area)); //Tag7
string Building = GetHexString(9, Convert.FromBase64String(Building)); //Tag8
string decString = Name + Serial + dateTimeStr + ModelNum + PartNo + SN + Shelf + Area + Building;
string finalQR = HexToBase64(decString);
Console.WriteLine(finalQR);
}
static string GetHexString(int tagNo, byte[] tagValue)
{
string strTagNo = string.Format("0{0:X}", tagNo);
string tagNoVal = strTagNo.Substring(strTagNo.Length - 2, 2);
string strTagValueLength = string.Format("0{0:X}", tagValue.Length);
string tagValueLengthVal = strTagValueLength.Substring(strTagValueLength.Length - 2, 2);
return tagNoVal + tagValueLengthVal + BitConverter.ToString(tagValue).Replace("-", "");
}
static string gethexDec(Int32 TagValue)
{
string hxint = String.Format("0{0:X}", TagValue);
return hxint.Substring(hxint.Length - 2, 2);
}
public static string HexToBase64(string strInput)
{
try
{
var bytes = new byte[strInput.Length / 2];
for (var i = 0; i < bytes.Length; i++)
{
bytes[i] = Convert.ToByte(strInput.Substring(i * 2, 2), 16);
}
return Convert.ToBase64String(bytes);
}
catch (Exception)
{
return "-1";
}
}
}
}
Related
I use this code
// background.js
chrome.runtime.sendNativeMessage( "com.example.native",
{ text: "test" },
function(response) {
console.log("Received " + response);
});
C# code
private static void OpenStandardStreamOut(string stringData)
{
string msgdata = "{\"text\":\"" + stringData + "\"}";
int DataLength = msgdata.Length;
Stream stdout = Console.OpenStandardOutput();
stdout.WriteByte((byte)((DataLength >> 0) & 0xFF));
stdout.WriteByte((byte)((DataLength >> 8) & 0xFF));
stdout.WriteByte((byte)((DataLength >> 16) & 0xFF));
stdout.WriteByte((byte)((DataLength >> 24) & 0xFF));
Console.Write(msgdata);
}
private static List<LoginPack> OpenStandardStreamIn()
{
Stream stdin = Console.OpenStandardInput();
int length = 0;
byte[] bytes = new byte[4];
stdin.Read(bytes, 0, 4);
length = System.BitConverter.ToInt32(bytes, 0);
string input = "";
for (int i = 0; i < length; i++)
{
input += (char)stdin.ReadByte();
}
JObject Read=(JObject)JsonConvert.DeserializeObject<JObject>(input);
//string dataPackStr = JsonConvert.SerializeObject(Read);
Chrome chromeClass = new Chrome();
List<LoginPack> lp = new List<LoginPack>();
if (Read!=null)
if (Read.Count != 0)
lp = chromeClass.getInfoFromChrome(Read["text"].ToString());
if (lp.Count == 0)
return null;
return lp;
}
//class chrome
public class Chrome
{
public class Data
{
public string key { get; set; }
public string value { get; set; }
}
public List<LoginPack> getInfoFromChrome(string colName)
{
try
{
// string filename = "my_chrome_passwords.html";
// StreamWriter Writer = new StreamWriter(filename, false, Encoding.UTF8);
string db_way = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
+ "/Google/Chrome/User Data/Profile 1/Login Data1";
Console.WriteLine("DB file = " + db_way);
string db_field = "logins";
List<LoginPack> lp = new List<LoginPack>();
byte[] entropy = null;
string description;
string ConnectionString = "data source=" + db_way + ";New=True;UseUTF16Encoding=True";
DataTable DB = new DataTable();
string sql = string.Format("SELECT * FROM {0} where action_url=\"{1}\" or origin_url=\"{2}\"", db_field, colName, colName);
// System.IO.StreamWriter file1 = new System.IO.StreamWriter("c:\\test.txt");
// file1.WriteLine(sql);
// file1.Close();
using (SQLiteConnection connect = new SQLiteConnection(ConnectionString))
{
SQLiteCommand command = new SQLiteCommand(sql, connect);
SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
adapter.Fill(DB);
int rows = DB.Rows.Count;
for (int i = 0; i < rows; i++)
{
byte[] byteArray = (byte[])DB.Rows[i][5];
byte[] decrypted = DPAPI.Decrypt(byteArray, entropy, out description);
lp.Add(new LoginPack { userNameElement = (string)DB.Rows[i][2], userName = (string)DB.Rows[i][3], passElement = (string)DB.Rows[i][4], pass = new UTF8Encoding(true).GetString(decrypted) });
//System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test2.txt");
//file.WriteLine(lp[i].userName);
//file.Close();
}
}
// Writer.Close();
return lp;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
ex = ex.InnerException;
return null;
}
}
}
Application(C#) give data from extension but Extension cant get any response from app
if I use OpenStandardStreamOut function at first(in C# app) then Extension can get response from it
what's the problem?
I think your 'Chrome' class is working badly. Check that again and make sure to use Standard Streams instead of your third party Streams. Also remove Console.WriteLine("DB file = " + db_way); line and try again.
i have try with postman in my local server to route the API
this is my code
[HttpPost]
[Route("photo")]
public IHttpActionResult Upload()
{
// LOCAL VARIABLE
int ErrCode = 1;
dynamic ExpObj = new ExpandoObject();
string FilePath = HttpContext.Current.Server.MapPath("/Img");
// GET SID & DECRYPTING OBJEK TO JSON OBJ
var HttpRequest = HttpContext.Current.Request;
string SID = GetSID(this.Request.Headers);
dynamic objek = GetobjekuMultipart(SID, HttpRequest.Form["objek"]);
// EXTRACT OBJEK
string UserID = objek.userID;
if (HttpRequest.Files.Count > 0)
{
// GET UPLOADED IMAGE
var PostedFile = HttpRequest.Files["image"];
// SET FILE NAME ( USERID + Right(FileName,10) )
string FileName = GetFileName(UserID, PostedFile.FileName, 10);
// SAVE IMAGE
string ImagePath = Path.Combine(FilePath, FileName);
PostedFile.SaveAs(ImagePath);
ExpObj.imageURL = ServerUrl + ServerPath + FileName;
}
else
{
ErrCode = -900;
}
// RETURN IF GOT ERROR
if (ErrCode < 0)
{
return StatusCode((HttpStatusCode)(ErrCode * (-1)));
}
// SERIALIZING & ENCRYPTING
string SerializedObj = JsonConvert.SerializeObject(ExpObj, JsonSetting);
string EncryptedReturn = Encrypt(SerializedObj, SID);
// RETURN
return Ok(EncryptedReturn);
}
and this is my public method (General Method)
public string Decrypt(string cipherText, string sid)
{
RNCryptor.Decryptor D = new Decryptor();
string DecryptedString = "";
if (Prod == true)
{
try
{
DecryptedString = D.Decrypt(cipherText, sid + SigningKey);
}
catch (Exception ex)
{
int ErrCode = -902; // Error in Decrypt
throw new HttpResponseException((HttpStatusCode)(ErrCode * (-1)));
}
}
else
{
DecryptedString = cipherText;
}
return DecryptedString.Trim();
}
public dynamic GetObjekMultipart(string sid, string Objek)
{
string StrObjek = Decrypt(Objek, sid);
return JsonConvert.DeserializeObject<dynamic>(StrObjek);
}
public string GetFileName(string UserID, string fileName, int length)
{
string FileName;
string FileFormat;
// GET FILE FORMAT
string[] Words = fileName.Split('.');
FileFormat = "." + Words[Words.Length - 1];
// GET FILE NAME WITHOUT THE FILE FORMAT
FileName = fileName.Substring(0, fileName.Length - FileFormat.Length);
// SET THE FILE NAME
FileName = UserID + "-" + GetRight(FileName, length) + FileFormat;
return FileName;
}
and POSTMAN Result is "Object reference not set to an instance of an object"
the result said that the httprequest.form is NULL
please help :(
I'm using google map API. I have 4 destinations and I want to get their locations ordered by nearest location first followed by second nearest. I have to show on Google Map which location is 1st being the nearest and then the next nearest and so on. So far I have only successfully calculated the distance between 2 locations by using below code:
private void button1_Click(object sender, EventArgs e)
{
getDistance("DECATUR FARM ROAD CHICHESTER PO20 8JT", "UNIT 01 CLIFF REACH GREENHITHE DA9 9SW");
}
public int getDistance(string origin, string destination)
{
System.Threading.Thread.Sleep(1000);
int distance = 0;
//string from = origin.Text;
//string to = destination.Text;
string url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&sensor=false";
string requesturl = url;
//string requesturl = #"http://maps.googleapis.com/maps/api/directions/json?origin=" + from + "&alternatives=false&units=imperial&destination=" + to + "&sensor=false";
string content = fileGetContents(requesturl);
JObject o = JObject.Parse(content);
try
{
distance = (int)o.SelectToken("routes[0].legs[0].distance.value");
return distance;
}
catch
{
return distance;
}
return distance;
//ResultingDistance.Text = distance;
}
protected string fileGetContents(string fileName)
{
string sContents = string.Empty;
string me = string.Empty;
try
{
if (fileName.ToLower().IndexOf("http:") > -1)
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] response = wc.DownloadData(fileName);
sContents = System.Text.Encoding.ASCII.GetString(response);
}
else
{
System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
sContents = sr.ReadToEnd();
sr.Close();
}
}
catch { sContents = "unable to connect to server "; }
return sContents;
}
How do I show the destinations according to their distance on google map. Any tip or pointers will be appreciated.
Please see the image, this is what I am trying to accomplish
Happy :) Enjoy Coding..
ArrayList arraylist;
List<string> adddistance = new List<string>();
List<string> getfinallist = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
string s = "UNIT 01 CLIFF REACH GREENHITHE DA9 9SW,PINETOP BIRKLANDS LANE ST ALBANS AL1 1EE,HOLYWELL HILL ST ALBANS AL1 1BT,OLD RECTORY HOLYWELL HILL ST ALBANS AL1 1BY";
button("DECATUR FARM ROAD CHICHESTER PO20 8JT", s);
}
public void button(string orign , string destination)
{
string[] words = destination.Split(',');
foreach (string word in words)
{
getDistance(orign, word);
}
sorting();
}
public int getDistance(string origin, string destination)
{
System.Threading.Thread.Sleep(1000);
int distance = 0;
string url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&sensor=false";
string requesturl = url;
string content = fileGetContents(requesturl);
JObject o = JObject.Parse(content);
string strdistance = (string)o.SelectToken("routes[0].legs[0].distance.value") + " , " + destination + " , ";
adddistance.Add(strdistance);
return distance;
}
public void sorting()
{
adddistance.Sort();
string getfirststring = adddistance.FirstOrDefault().ToString() ;
var vals = getfirststring.Split(',')[1];
getfinallist.Add(getfirststring.Split(',')[1]);
StringBuilder builder = new StringBuilder();
adddistance.RemoveAt(0);
foreach (string cat in adddistance) // Loop through all strings
{
builder.Append(cat); // Append string to StringBuilder
}
adddistance.Where((wors, index) => index % 2 == 0);
string result = builder.ToString();
string[] words = result.Split(',');
string[] even = words.Where((str, ix) => ix % 2 == 1).ToArray();
adddistance.Clear();
foreach (string word in even)
{ //string get = Regex.Match(word, #"^[" + numSet + #"]+$").ToString();
if (word != " ")
{
getDistance(vals, word);
}
}
sorting();
}
protected string fileGetContents(string fileName)
{
string sContents = string.Empty;
string me = string.Empty;
try
{
if (fileName.ToLower().IndexOf("http:") > -1)
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] response = wc.DownloadData(fileName);
sContents = System.Text.Encoding.ASCII.GetString(response);
}
else
{
System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
sContents = sr.ReadToEnd();
sr.Close();
}
}
catch { sContents = "unable to connect to server "; }
return sContents;
}
I am having a problem receiving files from the client. Someone suggested that I should use binary serialization to send and receive messages in stream. Can you give me ideas on how I should serialize this? I just learned about serialization not long ago so I am quite confused on how I should associate it with my program.
This is the client that 'should' be serialize
public void sendthedata()
{
if (!_timer.Enabled) // If timer is not running send data and start refresh interval
{
SendData();
_timer.Enabled = true;
}
else // Stop timer to prevent further refreshing
{
_timer.Enabled = false;
}
}
private List<int> listedProcesses = new List<int>();
private void SendData()
{
String processID = "";
String processName = "";
String processPath = "";
String processFileName = "";
String processMachinename = "";
listBox1.BeginUpdate();
try
{
piis = GetAllProcessInfos();
for (int i = 0; i < piis.Count; i++)
{
try
{
if (!listedProcesses.Contains(piis[i].Id)) //placed this on a list to avoid redundancy
{
listedProcesses.Add(piis[i].Id);
processID = piis[i].Id.ToString();
processName = piis[i].Name.ToString();
processPath = piis[i].Path.ToString();
processFileName = piis[i].FileName.ToString();
processMachinename = piis[i].Machinename.ToString();
output.Text += "\n\nSENT DATA : \n\t" + processFileName + "\n\t" + processMachinename + "\n\t" + processID + "\n\t" + processName + "\n\t" + processPath + "\n";
}
}
catch (Exception ex)
{
wait.Abort();
output.Text += "Error..... " + ex.StackTrace;
}
NetworkStream ns = tcpclnt.GetStream();
String data = "";
data = "--++" + processFileName + " " + processMachinename + " " + processID + " " + processPath;
if (ns.CanWrite)
{
byte[] bf = new ASCIIEncoding().GetBytes(data);
ns.Write(bf, 0, bf.Length);
ns.Flush();
}
}
}
finally
{
listBox1.EndUpdate();
}
}
And deserializing in the server
private void recieveData()
{
NetworkStream nStream = tcpClient.GetStream();
ASCIIEncoding ascii = null;
while (!stopRecieving)
{
if (nStream.CanRead)
{
byte[] buffer = new byte[1024];
nStream.Read(buffer, 0, buffer.Length);
ascii = new ASCIIEncoding();
recvDt = ascii.GetString(buffer);
/*Received message checks if it has +##+ then the ip is disconnected*/
bool f = false;
f = recvDt.Contains("+##+");
if (f)
{
string d = "+##+";
recvDt = recvDt.TrimStart(d.ToCharArray());
clientDis();
stopRecieving = true;
}
//else if (recvDt.Contains("^^"))
//{
// new Transmit_File().transfer_file(file, ipselected);
//}
/* ++-- shutsdown/restrt/logoff/abort*/
else if (recvDt.Contains("++--"))
{
string d = "++--";
recvDt = recvDt.TrimStart(d.ToCharArray());
this.Invoke(new rcvData(addToOutput));
clientDis();
}
/*--++ Normal msg*/
else if (recvDt.Contains("--++"))
{
string d = "--++";
recvDt = recvDt.TrimStart(d.ToCharArray());
this.Invoke(new rcvData(addToOutput));
}
}
Thread.Sleep(1000);
}
}
public void addToOutput()
{
if (recvDt != null && recvDt != "")
{
output.Text += "\n Received Data : " + recvDt;
recvDt = null;
}
}
Thank you.
There are a couple of rules to follow when serialising a piece of data.
It's easy to convert data to bytes, but consider how to reconstruct the data on the other side. Assume that the server can't have any knowledge on what you sended.
In your serialiser you just convert a couple of strings into a byte[] and send it over. Example:
string x = "abcdef";
string y = "ghijk";
var bytes = Encoding.Ascii.GetBytes(x + y);
the server receives: "abcdefghijk";
Is it possible for the server to determine and reconstruct strings x and y?
Since the server has no knowledge of the length of either x and y: no.
There are ways to solve this:
Use fixed length fields. In my example x should always be 6 chars and y should always be 5 chars in length. decoding on the server then becomes as trivial as
string x = data.Substring(0, 6)
string y = data.Substring(6, 5)
Use delimiters between the fields. If you are familiar with cvs, the ',' splits the fields. This however has it drawbacks, how to handle a ',' somewhere in a string? The data send over would be like "abcdef,ghijk"
Send the size of each field before the content of the field.
A naive approach just to clarify: string x would be send as '6abcdef' and y as '5ghijk'
Doing all this things by hand can get really hairy and is something that I would consider only if really needed.
I would resort to existing frameworks that do an excellent job on this subject:
Json.net
protobuf ported by Jon skeet
In this case I would first create a class to define the data send to the server instead of a bunch of strings:
class ProcessInfo{
public string ProcessID {get;set;}
public string ProcessName {get;set;}
public string ProcessPath {get;set;}
public string ProcessFileName {get;set;}
public string ProcessMachinename {get;set;}
};
the using Json to serialise this:
var procinfo = new ProcessInfo{
ProcessId = "1",
...
};
var serialised = JsonConvert.SerializeObject(procinfo);
var bytes = Encoding.Utf8.GetBytes(serialised);
ns.Write(bytes, 0, bytes.Length);
And restore it on the server just by:
var procInfo = JsonConvert.DeserializeObject<ProcessInfo>(json);
I have some ActionScript code that splits a string using Regular Expression and lets me add content at the split location.
// AS3 Code
function formatTweetText(tweet:String ):String
{
var regUrl:RegExp = /http:\/\/\S+/g;
var _text:String = " "+ tweet + " ";
_text = _text.replace(regUrl, '<font color="#666666"> $&</font>');
_text = _text.substr(1, _text.length-2);
return _text;
}
I'm trying to find the C# equivalent to the above function
What this does is give you the entire text value inserting the Replacement text where the regular expression finds a match.
For example:
var text:String = "Hello there http://www.url.com";
would turn into
var newString:String = "hello there <font color="#666666"> http://www.url.com</font>"
using System.Text.RegularExpressions;
private string formatTweetText(string tweet)
{
string newText = " " + Regex.Replace(tweet, "/http:\/\/\S+/g", "Replacement String") + " ";
return newText.SubString(1, (newText.Length - 2));
}
Regex regUrl = new Regex(#"http://\S+");
string url = regUrl.Match(tweet).Value;
return string.Format("<font color=\"#666666\"> {0}</font>", url);
Using a combination of the answers, here is the function in C# that does the same thing as the ActionScript function.
private string formatTweetText(string tweet)
{
Regex regUrl = new Regex(#"http://\S+");
string url = regUrl.Match(tweet).Value;
if (url.Length > 0)
{
string newReturnVal = string.Format("<font color=\"#FF0000\">{0}</font>", url);
string returnVal = tweet.Replace(url, newReturnVal);
return returnVal;
}
else
{
return tweet;
}
}
The above code only works on the first match, if you have multiple matches you'll need to use this code:
private string formatTweetText(string tweet)
{
string returnVal = tweet;
string updatedValue = tweet;
Regex regUrl = new Regex(#"http://\S+");
Match matches = regUrl.Match(tweet);
while (matches.Success)
{
for (int i = 0; i <= 2; i++)
{
Group g = matches.Groups[i];
CaptureCollection cc = g.Captures;
for (int j = 0; j < cc.Count; j++)
{
Capture c = cc[j];
string url = c.Value;
if (c.Length > 0)
{
string newReturnVal = string.Format("<font color=\"#FF0000\">{0}</font>", url);
returnVal = updatedValue.Replace(url, newReturnVal);
}
updatedValue = returnVal;
}
}
matches = matches.NextMatch();
}
return returnVal;
}
Like this?
string FormatTweetText(string tweet)
{
string regUrl = "http:\/\/\S+";
string text = " " + tweet + " ";
text = Regex.Replace(text, regUrl,
"<font color=\"#666666\"> $&</font>");
text = text.Substring(1, text.Length - 2);
return text;
}