How to Convert and Reverse MAC Address to Bytes C# - c#

I need to convert an MAc Address - 88:E9:FE:A8:1F:2F
for this format '0xA8FEE988 0x00002F1F 0x00000000 0x00000000'
I did this code below, but it is not elegant. Someone can help me?
string txtMacAddr = "88:E9:FE:A8:1F:2F";
string cmdMAc = "";
var macReverso = Util.Mac_Reverso(txtMacAddr.Replace(":",""));
string[] macRev = new string[4];
macRev[0] = $"0x{macReverso.Substring(4, 8)}";
macRev[1] = $"0x0000{macReverso.Substring(0, 4)}";
macRev[2] = "0x00000000";
macRev[3] = "0x00000000";
foreach (var xl in macRev)
{
cmdMAc += xl + " ";
}
Logger.WriteLine(cmdMAc); //op '0xA8FEE988 0x00002F1F 0x00000000 0x00000000'
public static string Mac_Reverso(string macAddress)
{
string macRevertido = string.Empty;
string s = macAddress.Replace("0x", "");//'0xA8FEE988 0x00002F1F 0x00000000 0x00000000'
string[] macLista = s.Split(' ');
foreach (var mac in macLista)
{
for (var i = mac.Length; i > 0; i -= 2)
{
macRevertido += mac.Substring(i - 2, 2);
if (macRevertido.Length == 12)
{
return macRevertido; //2F1FA8FEE988
}
}
}
return macRevertido;
}

What do you mean by not elegant? The following code will get the same result and in my opinion its easier to read. The first option is to show it can be done just by using char references, if the mac address will always look the same. The second result is easier to read in my head.
Note: If 88 was changed to 08 and the zero was omitted for some reason, the the following input would break both of them: 8:E9:FE:A8:1F:2F Does this case matter to you?
Is the output you included in your post what you are trying to get? What exactly are you trying to do?
//Reference each char individually. Could break if char position changes.
string mac = "88:E9:FE:A8:1F:2F";
string reverseMac = "0x" + mac[9] + mac[10] + mac[6] + mac[7] + mac[3] + mac[4] + mac[0] + mac[1] + " 0x0000" + mac[15] + mac[16] + mac[12] + mac[13] + " 0x00000000 0x00000000";
//Output:0xA8FEE988 0x00002F1F 0x00000000 0x00000000
//Better Option: Split by the ':' delimiter and reference each group of chars.
string[] macChars = mac.Split(":"); //Breaks into groups
string newMac2 = "0x" + macChars[3] + macChars[2] + macChars[1] + macChars[0] + " 0x0000" + macChars[5] + macChars[4] + " 0x00000000 0x00000000";
//Output: 0xA8FEE988 0x00002F1F 0x00000000 0x00000000
Update: Based on what you are trying to do, two methods would be better. You could reuse your Mac_Reverso in place of RevertMac below.
//Input 88:E9:FE:A8:1F:2F
//Output 0xA8FEE988 0x00002F1F 0x00000000 0x00000000
public static string ConvertMac(string macAddress)
{
string[] macChars = macAddress.Split(":");
string macRevertido = "0x" + macChars[3] + macChars[2] + macChars[1] + macChars[0] + " 0x0000" + macChars[5] + macChars[4] + " 0x00000000 0x00000000";
return macRevertido;
}
//Input 0xA8FEE988 0x00002F1F 0x00000000 0x00000000
//Output 88:E9:FE:A8:1F:2F
public static string RevertMac(string mc)
{
string revertedMac = "" + mc[8] + mc[9] + ":" + mc[6] + mc[7] + ":" + mc[4] + mc[5] + ":" + mc[2] + mc[3] + ":" + mc[19] + mc[20] + ":" + mc[17] + mc[18];
return revertedMac;
}
This doesn't address the endian issues Neil mentioned. Your question mentions reversing bytes, and your output format implies reversing the order of bytes in the array. Is that your objective?

Related

Results in descending order

I've got a block of code which sums up time togged for various tasks in a project and returns the total hours logged per project (intMinutesLogged). How do I get my results n descending order?
static async void NotifyEntriesByWorkSpace(Dictionary<string, List<TimeEntry>> dicEntriesByWorkspace, string strChatURL)
{
string strMessage = "";
foreach (var kvpEntry in dicEntriesByWorkspace)
{
var lstTimeEntries = kvpEntry.Value;
string strTitle = "";
var intMinutesLogged = 0;
var intMinutesBillable = 0;
var intMinutesNonBillable = 0;
foreach (var objTimeEntry in lstTimeEntries)
{
if (objTimeEntry.Billable)
{
intMinutesBillable += objTimeEntry.TimeInMinutes;
}
else
{
intMinutesNonBillable += objTimeEntry.TimeInMinutes;
}
}
strTitle = Workspaces.getWorkspaceFromCache(kvpEntry.Key).Title;
//Console.WriteLine(intMinutesLogged + ": " + strTitle + "m");
intMinutesLogged = intMinutesBillable + intMinutesNonBillable;
Console.WriteLine(TimeLoggedMessage(intMinutesLogged) + ": " + strTitle + " " + "(Billable: " + TimeLoggedMessage(intMinutesBillable) + ";" + " " + "Non-Billable: " + TimeLoggedMessage(intMinutesNonBillable) + ")");
strMessage += TimeLoggedMessage(intMinutesLogged) + ": " + strTitle + " " + "(Billable: " + TimeLoggedMessage(intMinutesBillable) + ";" + " " + "Non-Billable: " + TimeLoggedMessage(intMinutesNonBillable) + ")" + "\n";
}
await SendMessage(strChatURL, strMessage);
}
static string TimeLoggedMessage(int intMinutesLogged)
{
return intMinutesLogged / 60 + "h" + " " + intMinutesLogged % 60 + "m";
}
You could use LINQ for this: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.orderbydescending?view=net-6.0
You could create a simple class or anonymous type to hold the integer values you're summing up (total minutes, billable minutes, non-billable minutes). Then you could populate a collection of this type within the code you shared and afterwards call OrderByDescending on it. You could order based on any of the three integer values.

How to retrieve data from text file

I have data appended line by line in a text file for all confirmed transaction. I want to add Search functionality, where the user enters their E-mail address and all related transaction details connected to that E-mail must be displayed.
bool writeNextLine = false;
StringBuilder sb = new StringBuilder();
// Read the file and display it line by line.
using (System.IO.StreamReader file = new System.IO.StreamReader("record.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(txt_SearchBooking.Text))
{
// This append the text and a newline into the StringBuilder buffer
sb.AppendLine(line.ToString());
lbl_result.Text += sb.ToString();
}
}
}
but only the line containing Email is displayed other details are not.
Email is located on the last line of every transaction detail.
confirmmsg =
" Transaction # : " + EmployeeIDTextBox.Text + ClientIDTextBox.Text + UniqueIDTextBox.Text + "\r\n"
+ " First Name : " + ClientFirstNameTextBox.Text + "\r\n"
+ " Telephone Number : " + ClientTelephoneNumberTextBox.Text + "\r\n"
+ " Investment : " + investmentamt.ToString("C2") + "\r\n"
+ " Interest : " + (twelvemonthint * 100).ToString() + "%" + "\r\n"
+ " Interest Amount : " + (invesmentcalc(investmentamt, twelvemonthterm, twelvemonthint) - investmentamt).ToString("C2") + "\r\n"
+ " Bonus : " + bonus.ToString("c2") + "\r\n"
+ " Total Returns : " + invesmentcalc(investmentamt, twelvemonthterm, twelvemonthint).ToString("C2") + "\r\n"
+ " E-mail : " + ClientEmailTextBox.Text;
This is the data which is written into the text file.
If you always have 9 lines per transaction, with email being the last line, you could use File.ReadAllLines and a counter.
var lines = File.ReadAllLines("records.txt");
for(int i = 0; i < lines.Length; i++)
{
var line = lines[i];
if(line.Contains(txt_SearchBooking.Text))
{
//Retrieve the previous lines
for(int y = i-8; y <= i; y++)
{
lbl_result.Text += lines[y];
}
}
}

Add pause to Alexa without using SSML

Is there a way to add a pause (preferably 1 second) in Amazon Alexa without using SSML? Perhaps there is a trick I can do with the Outputspeech.Text and I just don't know it.
Below, I am saying "Here are works of art by {artist name}" but the name and the start of the works of art become mixed together - in spite of the period - so I end up with things like "Here are the works of art by Pablo Picasso Harlequin..."
I am using C# and my own https endpoint, not AWS Lambda.
Any suggestions? Otherwise I will add it as SSML. Thanks.
var output = new StringBuilder();
var outputCard = new StringBuilder();
string m_location;
string m_current_location;
string m_artist = dt_artist.Rows[0]["DisplayName"].ToString();
output.Append("here are works of art for " + m_artist + ". ");
outputCard.Append("Here are works of art for " + m_artist + ".\n\n");
foreach (DataRow dr in dt_artist_objs.Rows)
{
m_current_location = dr["CurrentLocation"].ToString();
if (m_current_location == " ")
{
m_location = "The location is not available.";
}
else
{
m_location = "It is located on the " + m_current_location;
}
output.Append(dr["Title"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + m_location);
outputCard.Append(dr["Title"].ToString() + ", " + dr["Dated"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + dr["Creditline"].ToString() + ". " + m_location + ".\n"); // It is located on the " + dr["CurrentLocation"].ToString());
}
sql_conn_data.Close();
response.Response.OutputSpeech.Text = output.ToString();
response.Response.Card.Title = "Art";
response.Response.Card.Type = "Standard";
response.Response.Card.Text = outputCard.ToString();
response.Response.ShouldEndSession = true;
return response;
UPDATE
OK. Ended up going the SSML route which looks like this:
var output = new StringBuilder();
var outputCard = new StringBuilder();
string m_location;
string m_current_location;
string m_location_card;
string m_artist = dt_artist.Rows[0]["DisplayName"].ToString();
output.Append("<speak>");
output.Append("here are works of art for " + m_artist + ". <break time='1s'/> ");
outputCard.Append("Here are works of art for " + m_artist + ".\n\n");
foreach (DataRow dr in dt_artist_objs.Rows)
{
m_current_location = dr["CurrentLocation"].ToString();
if (m_current_location == " ")
{
m_location = "The location is not available. <break time='1s' />";
m_location_card = "The location is not available. ";
}
else
{
m_location = "It is located on the " + m_current_location + "<break time = '1s' />";
m_location_card = "It is located on the " + m_current_location;
}
output.Append(dr["Title"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + m_location);
outputCard.Append(dr["Title"].ToString() + ", " + dr["Dated"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + dr["Creditline"].ToString() + ". " + m_location_card + ". \n");
}
output.Append("</speak>");
sql_conn_data.Close();
response.Response.OutputSpeech.Ssml = output.ToString();
response.Response.OutputSpeech.Type = "SSML";
response.Response.Card.Title = "Art";
response.Response.Card.Type = "Standard";
response.Response.Card.Text = outputCard.ToString();
response.Response.ShouldEndSession = true;
return response;
}
There is not a way to introduce a pause in Alexa without SSML. You will need to build the ssml string and return it back to Alexa using the pause, or the cadence strings.

How to discover the BSSID that your WLAN is connected to using NativeWifi API in C#

A WLAN can have more than one BSSID. I need to discovery which BSSID I am connected with.
In the NativeWIFI API using the struct WlanAvailableNetwork I can discover the WLAN that I am connected to, but it didn't tell me which is the connected BSSID.
In the Struct WlanBssEntry I can get all the BSSID of any WLAN, but i also can't discover which one I am connected.
All that I need is the MAC addrees of the WLAN I am connected with. That's why I want to discover which BSSID I am connected with.
I already discovered it...
I will post here my solution in case anyone needs it in the future...
using NativeWifi;
public void GetLog(int Count)
{
string Conectividade = "Disc";//Initi variable Conectividade as Disconnected
string RRate = "0";//Initi variable RRate as 0
string TRate = "0";//Initi variable TRate as 0
WlanClient client = new WlanClient();
foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)// Get the WLANs available
{
Wlan.WlanAssociationAttributes conAttributes = wlanIface.CurrentConnection.wlanAssociationAttributes;//Get the Attributes of current connection
string ConnectedSSID = Encoding.ASCII.GetString(conAttributes.dot11Ssid.SSID).ToString();//Save the SSID of WLAN connected with
string ReceivedRate = conAttributes.rxRate.ToString();//Save the receipted rate of the connected WLAN
string TransmitededRate = conAttributes.txRate.ToString();//Save the transmitted rate of the connected WLAN
byte[] ConnectedMacAddr = conAttributes.dot11Bssid;//MAC of the BSSID in which the WLAN is connected with
string ConMac = "";
for (int i = 0; i < ConnectedMacAddr.Length; {
ConMac += ConnectedMacAddr[i].ToString("x2").PadLeft(2, '0').ToUpper();//ConMac sera o MAC da BSSID conectada
}
Wlan.WlanBssEntry[] wlanBssEntries = wlanIface.GetNetworkBssList();//Vector with the BSS available
Wlan.WlanAvailableNetwork[] wlanAvailableNetwork = wlanIface.GetAvailableNetworkList(0);//Vector with the WLANS available
WriteLog("\"ID" + listSeparatorQuotes + "DateTime" + listSeparatorQuotes + "SSID" + listSeparatorQuotes + "MAC" + listSeparatorQuotes + "Type" + listSeparatorQuotes + "Auth" + listSeparatorQuotes + "Cipher" + listSeparatorQuotes + "Connection" + listSeparatorQuotes + "RecivRate" + listSeparatorQuotes + "TransmiRate" + listSeparatorQuotes + "SignalQuality" + listSeparatorQuotes + "NumberOfBSSIDS\"", path, "WLANs" + StartDay + StartHour + ".csv");
foreach (Wlan.WlanAvailableNetwork AVnetwork in wlanAvailableNetwork)
{
string SSIDatual = Encoding.ASCII.GetString(AVnetwork.dot11Ssid.SSID).ToString();//Actual SSID
if(SSIDatual.Equals(ConnectedSSID))
{
Conectividade = "Con";
RRate = ReceivedRate;
TRate = TransmitededRate;
}
//___________________________ wlanAvailableNetwork ___________________________
WriteLog(Count.ToString() + listSeparator + System.DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + listSeparator + SSIDatual + listSeparator + ConMac + listSeparator + AVnetwork.dot11BssType + listSeparator + AVnetwork.dot11DefaultAuthAlgorithm + listSeparator + AVnetwork.dot11DefaultCipherAlgorithm + listSeparator + Conectividade + listSeparator + RRate + listSeparator + TRate + listSeparator + AVnetwork.wlanSignalQuality + listSeparator + AVnetwork.numberOfBssids + "\"", path, "WLANs" + StartDay + StartHour + ".csv");//Its a function that's writes a log in the selected path...case you need this function send me a message!
//_________________________ End wlanAvailableNetwork _________________________
Conectividade = "Disc";//Reinitialize the value of Conectividade RRate = "0";//Reinitialize the value of RRate
TRate = "0";//Reinitialize the value of TRate
}
foreach (Wlan.WlanBssEntry network in wlanBssEntries)// Get all existent BSSIDs
{
int rss = network.rssi;
byte[] macAddr = network.dot11Bssid;
string tMac = "";
for (int i = 0; i < macAddr.Length; i++)
{
tMac += macAddr[i].ToString("x2").PadLeft(2, '0').ToUpper();
}
//___________________________ wlanBSSEntries __________________________
WriteLog(Count.ToString() + listSeparator + System.DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + listSeparator + System.Text.ASCIIEncoding.ASCII.GetString(network.dot11Ssid.SSID).ToString() + listSeparator + network.dot11BssType + listSeparator + network.chCenterFrequency + listSeparator + network.linkQuality + listSeparator + rss.ToString() + listSeparator + tMac, path, "BSSIDs" + StartDay + StartHour + ".csv");
//_________________________ End wlanBSSEntries _________________________
}
Console.ReadLine();
}
}
OBS: I'm writing the LOG as a .csv file, and I'm using culture to get the items separator, this way it will work in any place and culture... for example in Brazil and German the item's separator is a ";", but in USA the separator is a ",". It will adapt for any situation...
Here is the code to get the culture and the separation...
using System.Globalization;
private static string listSeparator = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
private static string listSeparatorQuotes = "\"" + listSeparator + "\"";

How can I successfully extract this substring in C#?

Here is the offending code. I haven't done much string manipulation yet, and am currently having issues.
if (orderid != orderlist[orderlist.Count - 1])
{
response2 = GetSubstringByString("{\"orderid\": \"" + orderid + "\"", "{\"orderid\": \"", response2);
}
else
{
response2 = GetSubstringByString("{\"orderid\": \"" + orderid + "\"", "success", response2);
}
Console.WriteLine("Response 2 is: " + response2);
logger.Log("Writing " + writepath + filename);
File.WriteAllText(writepath + filename, response2);
}
public string GetSubstringByString(string a, string b, string c) //trims beginning and ending of string
{
Console.WriteLine("String a is: " + a + "String b is: " + b + "String c is: " + c);
return c.Substring((c.IndexOf(a) + a.Length), (c.IndexOf(b) - c.IndexOf(a) - a.Length));
}
I am having issues extracting a substring, as the beginning and ending strings are the same, and therefore it is unable to differentiate the strings from each other.
Here is the main issue:
response2 = GetSubstringByString("{\"orderid\": \"" + orderid + "\"", "{\"orderid\": \"", response2);
Is there a way I can add a check if the orderid for the ending string differs from the starting string orderid? Thanks for any help!
I was working with code that was already set to scan rather than parse JSON in the optimal fashion.
I utilized this regex to remove orderid before each number as to not cause scanner length exceptions. I also overloaded string.IndexOf as mentioned by juharr.
var regex = new Regex(Regex.Escape("orderid")); //replace first occurrence of orderid
response2 = regex.Replace(response2, "", parsecount-1);
public string GetSubstringByString(string a, string b, string c) //trims beginning and ending of string
{
logger.Log("String a is: " + a + "String b is: " + b + "String c is: " + c);
var offset = c.IndexOf(b);
//lastcheck will return 0 if it's last element in orderlist, because ending string differs for last
return c.Substring((c.IndexOf(a) + a.Length), (c.IndexOf(b, offset + lastcheck) - c.IndexOf(a) - a.Length));
}

Categories