WPF: How to share a httpClient between windows [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Disclaimer: I'm really new to WPF.
After looking around online I've understood that the HttpClient should be used as a singleton, shared between windows in WPF.
However, I can't seem to find a clear startup entry-point as you'd find in MVC (startup, duh!).
Where should I instantiate my HttpClient, and how can I use it across multiple windows?
Currently I have two windows; Login and MainWindow. Both really basic. Example:
public partial class Login : Window
{
public Login()
{
InitializeComponent();
}
private void BtnLoginSubmit_Click(object sender, RoutedEventArgs e)
{
}
}
In my App.xaml.cs I've instantiated a HttpClient object which I can access from my MainWindow:
App.xaml.cs:
public partial class App : Application
{
public HttpClient httpClient { get; set; }
}
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
private static ObservableCollection<string> states;
public static void Add(string state)
{
states.Add(state);
}
public MainWindow()
{
InitializeComponent();
((App)Application.Current).httpClient = new HttpClient();
states = new ObservableCollection<string>();
states.Add("Initialized");
states.CollectionChanged += states_CollectionChanged;
LblStates.ItemsSource = states;
Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
}
static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLock)
{
}
MainWindow.Add(e.Reason.ToString());
}
void states_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
LblStates.Items.Refresh();
}
}
}

The most basic approach would be to add a static class that holds a static instance of HttpClient.
internal static class HttpClientManager
{
public static HttpClient Client = InititializeHttpClient();
}
You can then reference the client from anywhere, like HttpClientManager.HttpClient.

I don't see why you'd need to necessarily share the HttpClient across different windows - the best approach would be to invoke it whenever you need it, unless there is some need to preserve the state. That said, you can create your HttpClient at app-level, and define a HttpClient there.
You can define it in App.xaml.cs and re-use whenever necessary. It doesn't necessarily need to be static, you just need to refer to the specific instantiated entity.

Related

Virtual void not being overridden with override keyword in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I am trying to make a class the user of my library can derive from and then access a method for debugging the times of each action. Because my main debug method, where most information is stored, is static (and needs to be), I cannot use it to derive a class or add an overridable method in it. To combat this, I added the following code:
public static class Debug
{
internal static void CallObjectEvent(string log)
{
new Call().CallEvent(new Log(log, Timer.GetTime()));
}
}
internal class Call : IDebug
{
internal void CallEvent(Log log)
{
base.Event(log);
}
}
public class IDebug
{
public virtual void Event(Log log) {Console.WriteLine("test");}
}
class Program : IDebug
{
public override void Event(Log log)
{
Console.WriteLine(log.log);
}
}
Every time, it outputs 'test' instead of the log message. How can I fix this? Are there any alternatives to do the same thing?
Your Debug.CallObjectEvent() method explicitly instantiates a Call object and calls the overridden method in that class:
public static class Debug
{
internal static void CallObjectEvent(string log)
{
new Call().CallEvent(new Log(log, Timer.GetTime()));
}
}
The CallEvent() method in the Call class simply calls base.Event(), which resolves to IDebug.Event(). The Program.Event() override is never invoked because Program is not in the class hierarchy at the point of the call.
When you override a method or property, the override applies only to the class where it is defined (and all of its child classes, of course). Since Program isn't a parent class of Call there's no reason why its overrides would ever be referenced.
From what you've written it looks like you're trying to set up a system for handling different log outputs depending on the program's requirements. You need a way to register the appropriate log writer for your program. Something like:
public interface ILogWriter
{
void Event(Log item);
}
private class DefaultLogWriter : ILogWriter
{
public void Event(Log item)
{
Console.WriteLine($"[test] {item.Time} {item.Message}");
}
}
internal static class Debug
{
private static ILogWriter _writer = null;
public static ILogWriter Writer
{
get
{
if (_writer == null)
_writer = new DefaultLogWriter();
return _writer;
}
set => _writer = value;
}
internal static void CallObjectEvent(string log)
{
Writer.Event(new Log(log, Timer.GetTime()));
}
}
class Program
{
private class MyLogWriter : ILogWriter
{
public void Event(Log item)
{
Console.WriteLine($"[MyLogWriter] {item.Time} {item.Message}");
}
}
static void Main()
{
Debug.Writer = new MyLogWriter();
Debug.CallObjectEvent("Test message.");
}
}

C# method running with worksheet [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Maybe it is a beginner question but I can not seem to figure it out. How do I run the method as seen in the picture?
[[image]: https://i.stack.imgur.com/1QlnL.png][1]
By the looks of your picture your code for the ExcelRun may not be in the same class or linked to the class where you are trying to run it.
Example to get it to work:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ExcelRun();
Bogo.excelRun2();
Bogo n = new Bogo();
n.excelRun3();
}
private void ExcelRun()
{
MessageBox.Show("Have the Method Available in the same Class or callable from another.");
}
}
public class Bogo
{
public static void excelRun2()
{
MessageBox.Show("Hello there");
}
public void excelRun3()
{
MessageBox.Show("I am here");
}
}
This tutorial might help:
https://www.tutorialspoint.com/csharp/csharp_methods.htm

I have to use a serial port that is shared across two UIs in C# .NET 4.5 [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a C# application that opens up two GUIs at startup.
One of the GUI opens three virtual COM Ports. I want the other GUI that is a part of the same application to show the data that is being sent on those virtual COM Ports. Is there anyway to share this COM Port declaration that I do in the Main/First GUI that I am opening up.
Three ways:
1) Copy the instance of the connection from Window1 to Window2.
window2.Connection = this.Connection;
2) Make it the connection a public static member
class Window1 : Window
{
public static SerialConnectionClass Connection { get; set; } = new SerialConnectionClass();
}
You can access the connection like that:
class Window2 :Window
{
...
private void func()
{
Window1.Connection.Send("");
}
}
3) Make a static ConnectionManager
static class ConnectionManager
{
public static SerialConnectionClass Connection { get; set; } = new SerialConnectionClass();
public static EventHandler MessageReceived;
public static void Send(string text)
{
Connection.Send(text);
}
...
}
Use it in Window1 and Window2 like this:
class Window2 :Window
{
...
private void func()
{
ConnectionManager.init("COM1");
ConnectionManager.MessageReceived += this.MessageReceived;
ConnectionManager.Send("test123");
}
}

How to prevent class instantiation with dependency injection? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I had an interview question that asked roughly the following: with dependency injection, how do you prevent all of the classes from being instantiated? What if you only want a few, but not all? There are good reasons, they said, for example to avoid them all being in memory at the same time...
I've tried to research this question but it's hard to even figure out the best search term is. And no answers could I find.
A simple way would be to create it with a constructor and instantiate a single class based on a flag or switch. Here is a simple example that shows that only a single OtherClass or OtherClass2 would be instantiated.
I would like to add however that it isn't really Dependency Injection that allows the prevention of instantiation. You could get rid of the DI and have tightly coupled classes and still have a single instance of a class. So maybe I am not understanding the question correctly or maybe the interviewer asked it in a different context/manner?
class AppStart
{
OneClass One;
int _whatToCreate = 0;
public int WhatToCreate
{
get { return _whatToCreate; }
set { _whatToCreate = value; }
}
public void Start()
{
if (_whatToCreate > 0)
{
One = new OneClass(new OtherClass());
}
else
{
One = new OneClass(new OtherClass2());
}
One.PerformSomething();
}
}
class OneClass
{
IDoSomething _doSomething;
public OneClass(IDoSomething doSomething)
{
_doSomething = doSomething;
}
public void PerformSomething()
{
_doSomething.DoSomething();
}
}
class OtherClass : IDoSomething
{
public void DoSomething()
{
//throw new NotImplementedException();
}
}
class OtherClass2 : IDoSomething
{
public void DoSomething()
{
//throw new NotImplementedException();
}
}
interface IDoSomething
{
void DoSomething();
}

What's the functionality of a class has a static member of it self? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
An example:
class E
{
public static E e;
//...
};
What's the functionality of this or under which circumstances should we use this? Thanks.
One of usages can be to implement singleton (When you need a class that has only one instance, and you need to provide a global point of access to the instance): Implementing Signleton
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
A static variable cannot hold a reference to anything else that is declared in an instance, but rather a static variable/method belongs to the type instead of an instance of a type.
Consider this:
public class TestClass
{
private static string _testStaticString;
private string _testInstanceString;
public void TestClass()
{
_testStaticString = "Test"; //Works just fine
_testInstanceString = "Test";
TestStatic();
}
private static void TestStatic()
{
_testInstanceString = "This will not work"; //Will not work because the method is static and belonging to the type it cannot reference a string belonging to an instance.
_testStaticString = "This will work"; //Will work because both the method and the string are static and belong to the type.
}
}
The many usages are so many it could fill books. As someone mentioned, the Singleton pattern makes use of it.

Categories

Resources