How Get data Trough DNS in C# Unity3D - c#

I have a database that stores players stats. The database isn't working with my IP, so I want to get the data from a DNS (like 1.1.1.1)
How can I make C# script to go through the DNS?
The Problem is this Azuara blocks Iranian IP and i want somehow Get a Work Around it
enter image description here
This is my C# code in Unity:
public void GetUserData(OnDataReceivedCallback onDataReceived)
{ //called when the 'Get Data' button on the data part is pressed
if (IsLoggedIn)
{
//ready to send request
StartCoroutine(sendGetDataRequest(LoggedIn_Username, LoggedIn_Password, onDataReceived)); //calls function to send get data request
}
}
IEnumerator sendGetDataRequest(string username, string password, OnDataReceivedCallback onDataReceived)
{
string data = "ERROR";
IEnumerator e = DCF.GetUserData(LoggedIn_Username, LoggedIn_Password); // << Send request to get the player's data string. Provides the username and password
while (e.MoveNext())
{
yield return e.Current;
}
string response = e.Current as string; // << The returned string from the request
if (response == "Error")
{
//There was another error. Automatically logs player out. This error message should never appear, but is here just in case.
LoggedIn_Username = "";
LoggedIn_Password = "";
Debug.Log("Error: Unknown Error. Please try again later.");
}
else
{
data = response;
}
if (onDataReceived != null)
onDataReceived.Invoke(data);
}

Related

C# SerialPort Readline with multiple newline in buffer

I need to get some data from a temperature controller using rs232.
The controller sends me an echo for every character at the end of each complete command it returns a '§' and a '.' if if the command was applied successfully. My test code looks like this:
static string GetData(int memoryAddress)
{
if (!_session.IsOpen)
return "No Connection";
string toSend = "*A_r_" + memoryAddress.ToString() + "_0" + (char)21;
foreach (char character in toSend)
_session.Write(character.ToString());
Thread.Sleep(100);
return _session.ReadExisting();
}
and returns something like this:
*A_r_0_0§.250§
Now I also need to store some data inside the controller and want to reuse the upper part is it possible to use
ReadNewline (with Newline-Symbol §)
to only get the echo and verify it, so that i can read the returned data (in case i choose to read someting) in the next function?
Which value woud get returned first? the one that arrived last or first?
also would it be better to use a timeout for ReadNewline instead of Thread.sleep(100)?
It is good to use 'DataReceived' event
private Object responseSignal = new object();
private string portResponse;
_session.DataReceived += new SerialDataReceivedEventHandler(PortDataReceived);
static string GetData(int memoryAddress)
{
if (!_session.IsOpen)
return "No Connection";
string toSend = "*A_r_" + memoryAddress.ToString() + "_0" + (char)21;
foreach (char character in toSend)
_session.Write(character.ToString());
if (System.Threading.Monitor.Wait(responseSignal, 10000)) // max time we want to wait to receive the response
{
// successful get
}
else
{
// failed to receive the response
}
return portResponse;
}
public void PortDataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
lock (responseSignal)
{
string tmpPortResponse = _session.ReadExisting();
portResponse += tmpPortResponse;
//Complete the response only when you get the end character
if (tmpPortResponse.Contains('.'))
{
// signal allows a waiting SendMessage method to proceed
System.Threading.Monitor.Pulse(responseSignal);
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
}

Simple Chat Client-Server Encryption

I wanted to make a chat client server, very simple, but at the same time very safe, using AES-256bit. I have thought so, tell me if I'm wrong, of course.
The various client enter in a "secure" textbox the passwords (which must be the same everywhere) and in the sending functions (of the client program), clients encrypt messages that I put in another ordinary textbox, using the password and send them to the server; the receiving function always decrypts always using the same key. The server should instead do nothing at the encryption level.
I tried, but I do not know if it doesn't work because of at the code level.
Here's how I modified both the sending and receiving functions on the client: send function
// send the message to the server
private void SendMessage()
{
if (txtMessage.Lines.Length >= 1)
{
byte[] passwordBytes = GetPasswordBytes();
encrypted_message = AES.Encrypt(txtMessage.Text, passwordBytes);
swSender.WriteLine(encrypted_message);
swSender.Flush();
txtMessage.Lines = null;
}
txtMessage.Text = "";
}
receiving function:
private void ReceiveMessages()
{
// Receive the response from the server
srReceiver = new StreamReader(tcpServer.GetStream());
// If the first character of the response is 1, connection was successful
string ConResponse = srReceiver.ReadLine();
// If the first character is a 1, connection was successful
if (ConResponse[0] == '1')
{
// Update the form to tell it we are now connected
this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { "Connessione avvenuta con successo!" });
}
else // If the first character is not a 1 (probably a 0), the connection was unsuccessful
{
string Reason = "Non connesso: ";
// Extract the reason out of the response message. The reason starts at the 3rd character
Reason += ConResponse.Substring(2, ConResponse.Length - 2);
// Update the form with the reason why we couldn't connect
this.Invoke(new CloseConnectionCallback(this.CloseConnection), new object[] { Reason });
// Exit the method
return;
}
// While we are successfully connected, read incoming lines from the server
while (Connected == true)
{
try
{
// Show the messages decrypted in the log TextBox
this.Invoke(new UpdateLogCallback(this.MessageUpdateLog), new object[] { srReceiver.ReadLine() });
}
catch
{
try
{
this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { srReceiver.ReadLine() });
}
catch { }
}
}
}
// This method is called from a different thread in order to update the log TextBox
private void UpdateLog(string strMessage)
{
txtLog.AppendText(strMessage + "\r\n");
}
//Decrypt the messages incoming from the other client
private void MessageUpdateLog(string strMessage_de)
{
byte[] passwordBytes = GetPasswordBytes();
strMessage_de = AES.Decrypt(strMessage_de, passwordBytes);
// Append text also scrolls the TextBox to the bottom each time
txtLog.AppendText(strMessage_de + "\r\n");
}
not to make the job hard, I thought of exchange encryption passwords (keys) via voice, since it would be a chat room for personal use.

How to read Post Parameters from Payment Gateway API After Successful Transaction

I am using a Payment Gateway Which will send the response to the Success page. Their documentation indicates they are sending response as POST parameters. I tried to Read these parameters but i am not able to get the parameters. I had sent a mail to support and they said they will send the data from their server to our server prior redirection to success page. I implemented my code in success page. Where I should Implement and how to save these values in my code for further use.
My code is Here
protected void Page_Load(object sender, EventArgs e)
{
/// store all the posted form variables in an object to use later
response notifyresponse = new response();
notifyresponse.CreditVouchersTransactionId = Request["CreditVouchersTransactionId"];
notifyresponse.MerchantName = GetFormVariableOrNull(Request["MerchantName"]);
notifyresponse.AmountToPay = GetFormVariableOrNull(Request["AmountToPay"]);
notifyresponse.PaymentOKURL = GetFormVariableOrNull(Request["PaymentOKURL"]);
notifyresponse.OrderId = GetFormVariableOrNull(Request["OrderId"]);
notifyresponse.AmountCurrency = GetFormVariableOrNull(Request["AmountCurrency"]);
notifyresponse.PaymentType = GetFormVariableOrNull(Request["AmountType"]);
notifyresponse.PaymentStatus = GetFormVariableOrNull(Request["PaymentStatus"]);
string[] keys = Request.Form.AllKeys;
for (int i = 0; i < keys.Length; i++)
{
Session["amountpay"]=keys[i] ;
}
}
protected string GetFormVariableOrNull(object formvariable)
{
if (formvariable != null)
{
try
{
return formvariable.ToString();
}
catch (Exception ex)
{
/// log the exception in file or DB
Console.WriteLine(ex.Message);/// just for an example
return null;
}
}
else
return null;
}
Thanks
Use Fiddler, it will show you all the traffic going back forth and provide a more accurate picture as to whats going on between those transactions
https://www.telerik.com/download/fiddler
Edit
A HTTP message can be composed of two part, first is the header, the other is the body.
When making a GET request to a server, it won't contain a body. A POST request on the other hand, will. There are line breaks in between the headers and the body... I've demonstrated a POST request below

Create a Computer Request Including IP address Subject Alternative Name

I'm trying to create a request with IP address SAN. This is the function that is responsible for creating the CAlternativeName:
public static CAlternativeNameClass GetCurrentIpName() {
//get current machine IP address
IPAddress ip = GetCurrentIp();
if (ip == null) {
return null;
}
try {
CAlternativeNameClass nameClass = new CAlternativeNameClass();
nameClass.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_IP_ADDRESS, ip.ToString());
return nameClass;
} catch (Exception e) {
Console.WriteLine(e);
return null;
}
}
The problem is that I'm getting the next error:
System.ArgumentException: Value does not fall within the expected range.
at CERTENROLLLib.CAlternativeNameClass.InitializeFromString(AlternativeNameType Type, String strValue)
What am I doing wrong?
InitializeFromString does not accept an AlternativeNameType of XCN_CERT_ALT_NAME_IP_ADDRESS**. You have to use InitializeFromRawData instead. The error is something of a misnomer because it's not actually the value parameter that's the issue, it's the type, but hey.
InitializeFromRawData takes a string as input (because this is Microsoft, not Ronseal), so you need to encode your raw data as a string so it can turn it in to raw data again:
String ipBase64 = Convert.ToBase64String(ip.GetAddressBytes());
nameClass.InitializeFromRawData(AlternativeNameType.XCN_CERT_ALT_NAME_IP_ADDRESS, EncodingType.XCN_CRYPT_STRING_BASE64, ipBase64);
About as intuitive as an Escher artpiece.
** Source: http://msdn.microsoft.com/en-us/library/windows/desktop/aa375024%28v=vs.85%29.aspx

Transferring multiple commands/decisions through tcp socket

Good afternoon all!
The goal of the project:
Build a notification program with client, console, and server executable. Only selected users should get the notification.
The problem:
Sometimes the code works great, and everything works (20% of runs). The rest of the time, it will mess up the order the data is being sent in.
The code:
Server (console = TCPclient):
private void Connect()
{
string username = ReadFromConsole();
if (IsUserAllowed(username)) // Receive username
SendToConsole(bool.TrueString); // Send confirmation
else
{
SendToConsole(bool.FalseString); // Send denial
console.Close();
return;
}
string messageID = ReadFromConsole(); // Receive MessageID
string recipientCount = ReadFromConsole();
int numOfRecipients = int.Parse(recipientCount); // Receive and parse number of recipients
List<string> recipients = new List<string>();
for (int i = 0; i < numOfRecipients; i++)
{
string recipient = ReadFromConsole();
recipients.Add(recipient); // Receive recipient, add to list (required for Message)
}
string department = ReadFromConsole(); // Receive department string
string visibleTime = ReadFromConsole(); // Receive visibility timespan
string expiration = ReadFromConsole(); // Receive expiration datetime
StoreRTF(messageID); // Receive and store RTF file
console.Close(); // Connection is done, close
Message message = new Message(messageID, department, recipients, visibleTime, expiration);
}
Console (server = TCPclient):
private void SendMessage()
{
SendToServer(Environment.UserName);
if (bool.Parse(ReadFromServer()))
{
// User is allowed, continue
string messageID = DateTime.Now.ToUniversalTime().Ticks.ToString();
SendToServer(messageID); // MessageID
string recipientCount = lvRecipients.Items.Count.ToString();
SendToServer(lvRecipients.Items.Count.ToString()); // Amount of recipients
foreach (string item in lvRecipients.Items) // Loop to send each recipient
{
SendToServer(item);
}
string department = TB_Department.Text;
SendToServer(department); // Send department string
string visibleTime = TimeSpan.FromSeconds(SLIDER_VisibleTime.Value).Ticks.ToString();
SendToServer(visibleTime); // Send message visibility time
string expiration = DateTime.Now.ToUniversalTime().AddMinutes(2).ToString();
SendToServer(expiration); //TODO add UI control for this
SendRTFToServer(); // Send RTF file
MessageBox.Show(
"Your designated MessageID is: " + messageID + Environment.NewLine +
"Message upload is succesful.",
"Complete",
MessageBoxButton.OK);
}
else
{
// User is not allowed. Report to user. Disconnect (will be managed by the finally block)
MessageBox.Show("You are not allowed to upload messages to the server.", "Access denied", MessageBoxButton.OK, MessageBoxImage.Stop);
return;
}
}
Send and receive parts (same between console/server/client):
private void SendToServer(string toSend)
{
while (server.GetStream().DataAvailable)
{
// Should wait
}
StreamWriter writer = new StreamWriter(server.GetStream());
writer.WriteLine(toSend);
writer.Flush();
}
private void SendRTFToServer()
{
while (server.GetStream().DataAvailable)
{
// Should wait
}
File.Open(RTFLocation, FileMode.Open, FileAccess.Read).CopyTo(server.GetStream());
server.GetStream().Flush();
server.GetStream().Close();
}
private string ReadFromServer()
{
server.GetStream().Flush();
StreamReader reader = new StreamReader(server.GetStream());
return reader.ReadLine();
}
I have also tried different loops, implementations, switching to byte[]...
After lots of debugging I am getting nowhere. I have checked which information is leaving the console, and that all checks out and is in the right order. However, at the server end it seems to be receiving it in an entirely different order.
Anyone have an idea what is causing this?
I've found how to properly handle this. Code for the relevant parts can be found here:
C# Sockets send/receive problems and questions
Hope this may help someone in the future!

Categories