Getting RestSharp response from another cs file - c#

Here's the thing: I want to get the string named "IPAddress" from FullParse.cs to Form1.cs. What would it be if I'll get multiple variables aside from "IPAddress"?
Here's the code I've made
FullParse.cs
using RestSharp;
namespace WindowsFormsApp2
{
internal class FullParse
{
public void getIP() {
RestClient client = new RestClient("http://ip-api.com/json/?fields=9009");
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
string source = (response.Content);
dynamic data = JObject.Parse(source);
string IPAddress = data.query;
}
}
}
Form1.cs
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
FullParse fullParse = new FullParse();
}
}
}
It's still my first time using C# especially OOP so I don't really know if i'm doing this right.

Example of one way you can do this with multiple out parameters:
Changes to FullParse.cs:
using RestSharp;
namespace WindowsFormsApp2
{
internal class FullParse
{
public string getIP(out int firstOutInt, out string secondOutString) {
RestClient client = new RestClient("http://ip-api.com/json/?fields=9009");
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
string source = (response.Content);
dynamic data = JObject.Parse(source);
string IPAddress = data.query;
int firstOutInt = 1234;
string secondOutString = "some text";
return IPAddress;
}
}
}
Changes to Form1.cs:
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
FullParse fullParse = new FullParse();
string ipAddress = fullParse.getIP(out int firstOutInt, out string secondOutString);
//doSomething is not defined here - this is just an example of a function using the values from getIP
doSomething(ipAddress, firstOutInt, secondOutString);
}
}
}

Related

Generating partial classes using source generator removes original class

So I'm experimenting with the new ISourceGenerator system to generate a few I18n strings & classes from XML files. This works but now I want to extend an existing partial class using a source generator, but whenever I do the original class contents become inaccessible! This is the class I have:
// File: Strings.cs
namespace MyProject.I18n
{
public static partial class Strings
{
public const string Options = "Options";
}
}
This is what I'm generating:
// Generated file: GeneratedStrings.cs
namespace MyProject.I18n
{
public static partial class Strings
{
public const string MainMenu = "Main menu";
}
}
This is how I'm generating it (MVCE):
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
[Generator]
public class I18NGenerator : ISourceGenerator
{
private const string XML_EXAMPLE = #"
<Strings>
<MainMenu>Main menu</MainMenu>
</Strings>
";
private StringBuilder sb = null!;
private int indentation;
public void Initialize(GeneratorInitializationContext context)
{
sb = new StringBuilder();
indentation = 0;
}
public void Execute(GeneratorExecutionContext context)
{
var root = XDocument.Parse(XML_EXAMPLE).Root!;
void Process(XElement element)
{
var text = element.Nodes().FirstOrDefault(node => node is XText);
if (text is XText xText)
{
IndentedLn($#"public static string {element.Name.LocalName} = ""{xText.Value}"";");
}
else
{
BeginBlock($"public static partial class {element.Name.LocalName}");
foreach (var xElement in element.Elements())
Process(xElement);
EndBlock();
}
}
BeginBlock("namespace MyProject.I18n");
Process(root);
EndBlock();
context.AddSource("GeneratedStrings.cs", SourceText.From(sb.ToString(), Encoding.UTF8));
}
private void Indent()
{
indentation++;
}
private void Dedent()
{
indentation--;
}
private void BeginBlock(string statement = "")
{
if (statement.Length != 0)
IndentedLn(statement);
IndentedLn("{");
Indent();
}
private void EndBlock()
{
Dedent();
IndentedLn("}");
}
private void Raw(string text) => sb.Append(text);
private void Indented(string code)
{
for (var i = 0; i < indentation; i++)
Raw("\t");
Raw(code);
}
private void IndentedLn(string code) => Indented(code + "\n");
}
Trying to access Strings.Options gives the compilation error 'Strings' does not contain a definition for 'Options'.
I can add that if I generate BOTH files they merge just fine.

Single Method handling multiple SerialPort.DataReceived events with lock

I open multiple serial ports and assign the DataReceived event to a single method. If now multiple com ports receive at the same time something, SerialPort_DataReceived is called parallel(?) so i tried to use lock so that only one event could be handled at the same time.
using System;
using System.Collections.Generic;
using System.Windows;
using System.IO.Ports;
using System.Text;
namespace MainApplication
{
public partial class MainWindow : Window
{
private SerialConnectionHandler m_SerialConnectionHandler;
public MainWindow()
{
InitializeComponent();
m_SerialConnectionHandler = new SerialConnectionHandler();
m_SerialConnectionHandler.ResponseReceived += SerialConnectionHandler_ResponseReceived;
}
private void SerialConnectionHandler_ResponseReceived(object sender, EventArgs e)
{
// Do something.
}
}
public class SerialConnectionHandler
{
private List<SerialPort> m_SerialConnections;
private List<SerialCommand> m_CommandQueue;
private object m_DataReceivedLock;
public event EventHandler ResponseReceived;
public SerialConnectionHandler()
{
m_SerialConnections = new List<SerialPort>();
m_CommandQueue = new List<SerialCommand>();
m_DataReceivedLock = new object();
foreach (var comPortName in SerialPort.GetPortNames())
{
var newSerialPort = new SerialPort(comPortName);
newSerialPort.DataReceived += SerialPort_DataReceived;
var newSerialCommand = new SerialCommand(comPortName, "Command", "Response");
newSerialPort.Open();
newSerialPort.Write(newSerialCommand.Command, 0, newSerialCommand.Command.Length);
m_SerialConnections.Add(newSerialPort);
}
}
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
lock (m_DataReceivedLock)
{
var serialPort = (SerialPort)sender;
var receivedContent = new byte[serialPort.BytesToRead];
serialPort.Read(receivedContent, 0, receivedContent.Length);
// Clear in buffer.
serialPort.DiscardInBuffer();
// Do something which could lead to problems if multiple com ports receive at the same time something.
foreach (var command in m_CommandQueue.FindAll(command => command.SerialPortName.Equals(serialPort.PortName)))
{
if (command.ExpectedResponse.Equals(receivedContent.ToString()))
{
ResponseReceived?.Invoke(this, new EventArgs());
m_CommandQueue.Remove(command);
break;
}
}
}
}
}
public class SerialCommand
{
public string SerialPortName { get; }
public byte[] Command { get; }
public string ExpectedResponse { get; }
public SerialCommand(string serialPortName, string command, string expectedResponse)
{
SerialPortName = serialPortName;
Command = Encoding.ASCII.GetBytes(command);
ExpectedResponse = expectedResponse;
}
}
}
My question is now, could lock lead to missed received content due to the fact that not every event is handled immediately? I'm calling SerialPort.Read() and SerialPort.DiscardInBuffer() from inside the lock block.

Set image in Picture-box from Business Logic Class to Main application Class

I write a c# code according to software architecture. In business logic layer I implement a code by which I can extract data from wikipedia api to get image. I want to show it on application layer which is Form1.cs. But it is not working at all. My code for getting the image from Wikipedia looks like this:
public class ImageService
{
private string _baseUrl = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=pageimages&pithumbsize=400&titles={0}";
public string GetImage(string name)
{
string requestUrl = string.Format(_baseUrl, name);
string result;
using (WebClient client = new WebClient())
{
var response = client.DownloadString(new Uri(_baseUrl));
var responseJson = JsonConvert.DeserializeObject<ImgRootobject>(response);
var firstKey = responseJson.query.pages.First().Key;
result = responseJson.query.pages[firstKey].thumbnail.source;
string Image_title = responseJson.query.pages[firstKey].title;
}
return result;
}
}
My Form1.cs is:
public partial class Form1 : Form
{
private readonly ImageService _imageService;
public Form1()
{
_imageService = new ImageService();
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.LoadAsync(_imageService);
}
}
You didn't call the GetImage method from ImageService which returns the string. The LoadAsync method of the PictureBox accept one string as it's parameter but you've sent an instance of ImageService to it. It should be like this:
pictureBox1.LoadAsync(_imageService.GetImage(a string parameter for name));

Windows Phone 8.1 Currency converter Json

I got a school project. I have to make a currency converter and I got stuck. I found something on the Code Project web site, but I am new at this and I do not really know how to implement it in my project.
I tried something like `
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
class WebClient
{
internal string DownloadString(string url)
{
throw new NotImplementedException();
url = "https://openexchangerates.org/api/latest.json?app_id=ae11142304694b10a1dbf2d25933a333";
var currencyRates = _download_serialized_json_data<App9.CurrencyRates>(url);
}
}
public static T _download_serialized_json_data<T>(string url) where T : new()
{
var w = new WebClient();
{
//using (var w = new WebClient()) {
var json_data = string.Empty;
// attempt to download JSON data as a string
try
{
json_data = w.DownloadString(url);
}
catch (Exception) { }
// if string with JSON data is not empty, deserialize it to class and return its instance
return !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<T>(json_data) : new T();
}
}
private void comboBoxTo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void convertButton_Click(object sender, RoutedEventArgs e)
{
if (amountTb.Text == string.Empty)
{
afisareTb.Text = "Scrieti o valoare";
}
else
{
var currencyRates = _download_serialized_json_data<CurrencyRates>("https://openexchangerates.org/api/latest.json?app_id=YOUR_APP_ID ");
}
}
}
`
I do not have any errors, it is just that, when I press on converter button from my app, nothing happens.

Entering data into Excel worksheets in an add in (C#)

I'm creating an add in for Microsoft Excel that includes a ribbon tab. On this tab is a button with the following code:
public void setAccounts()
{
foreach (Excel.Worksheet displayWorksheet in Globals.ThisAddIn.Application.Worksheets)
{
displayWorksheet.Range[budget_cell].Value2 = "$" + Convert.ToString(budget);
displayWorksheet.Range[account_cell].Value2 = "$0.00";
displayWorksheet.Range[transaction_cell].Value2 = "Amount";
}
}
The button opens up a separate form where the user specifies budget_cell, account_cell, and transaction_cell. I then pass that data to the above code in SolutionName.ThisAddIn.cs (where SolutionName is the namespace of the solution). Strictly speaking, the code works. However, the data doesn't show up in the cells until the button is pressed a second time. Why is that? Is it because I'm retrieving the data from a different object in the solution?
Also, I've been trying to get this code and the aforementioned form to activate when the add in first starts up.
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
frmStartup startup = new frmStartup();
startup.Show();
setAccounts();
}
I've been at this for a good twelve hours now, and I can't get it to work. What am I missing?
ThisAddIn.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
namespace AccountingAddIn
{
public partial class ThisAddIn
{
public static string budget_cell = "";
public static string account_cell = "";
public static string transaction_cell = "";
public static string date_cell = "";
public static string time_cell = "";
public static string description_cell = "";
public static bool date = false;
public static bool time = false;
public static bool description = false;
public static decimal budget = 0;
List<Account> accounts = new List<Account>();
public void budgetStartUp()
{
frmStartup startup = new frmStartup();
startup.Show();
setAccounts();
}
public void setAccounts()
{
foreach (Excel.Worksheet displayWorksheet in Globals.ThisAddIn.Application.Worksheets)
{
displayWorksheet.Range[budget_cell].Value2 = "$" + Convert.ToString(budget);
displayWorksheet.Range[account_cell].Value2 = "$0.00";
displayWorksheet.Range[transaction_cell].Value2 = "Amount";
if (date == true)
{
displayWorksheet.Range[date_cell].Value2 = "Date";
}
if (time == true)
{
displayWorksheet.Range[time_cell].Value2 = "Time";
}
if (description == true)
{
displayWorksheet.Range[description_cell].Value2 = "Description";
}
Account na = new Account(0, displayWorksheet);
accounts.Add(na);
}
}
protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
{
return Globals.Factory.GetRibbonFactory().CreateRibbonManager(
new Microsoft.Office.Tools.Ribbon.IRibbonExtension[] { new MyRibbon() });
}
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
CreateRibbonExtensibilityObject();
budgetStartUp();
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
}
}
frmStartup.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace AccountingAddIn
{
public partial class frmStartup : Form
{
public frmStartup()
{
InitializeComponent();
}
private void btnHelp_Click(object sender, EventArgs e)
{
MessageBox.Show("Please enter a starting amount for your budget and " +
"which cells will display the running total for your " +
"accounts." +
"\n\nNote: Leaving the budget blank will" +
" result in a starting budget of $0.00.");
}
private void btnOkay_Click(object sender, EventArgs e)
{
AccountingSeminar.ThisAddIn.budget += Convert.ToDecimal(txtStartingAmount.Text);
AccountingSeminar.ThisAddIn.budget_cell = txtBudget.Text;
AccountingSeminar.ThisAddIn.account_cell = txtAccount.Text;
AccountingSeminar.ThisAddIn.transaction_cell = txtTransaction.Text;
if (chkDate.Checked)
{
AccountingSeminar.ThisAddIn.date_cell = txtDate.Text;
AccountingSeminar.ThisAddIn.date = true;
}
if (chkTime.Checked)
{
AccountingSeminar.ThisAddIn.time_cell = txtTime.Text;
AccountingSeminar.ThisAddIn.time = true;
}
if (chkDescription.Checked)
{
AccountingSeminar.ThisAddIn.description_cell = txtDescription.Text;
AccountingSeminar.ThisAddIn.description = true;
}
Close();
}
}
}

Categories