As you know we don't have session in WinForm. I have several forms (Customer, Service, Operator, ...) in my project, and I take from Operator some values ( operator Name, Operator LastName and Profile Picture address). I want to store this values somewhere in run-time and whenever I need it, I can fetch it from where I stored it.
Is there an easy way to do this ?
I think these are the words of a long time web developer. I hear you my friend. I've been there...
Session object of web programming is just a workaround to work around the problem of saving state in a stateless environment. On the other hand winforms programming does not have this problem. Your application has objects that all keep their state information.
As for passing information from one form to another:
You can define parameters on the receiving forms constructor to pass
parameters. Then you define local variables in the receiving form to hold references to those objects.
You can set a separate method on the receiving form to
send parameters and call it from sender form.
You can make the information public on the sender
form (or some other place) and get it from receiving form when you
need it.
Which one is best? Depends entirely on your business case and application logic.
I believe that the simplest way to do this is to create a class that can be accessed from your forms which contains the data you want
Example
// Class1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace myNameSpace
{
class Class1
{
public static string Name = "";
public static string LastName = "";
public static string ProfilePictureaddress = "";
}
}
Using this, whenever you would like to store or retrieve data, you may use myNameSpace.Class1. For example, if you would like to store into the Name, you may use myNameSpace.Class1.Name = "value";. This will set Name to value.
Thanks,
Happy Holidays! :)
also you can use project properties like this:
//write
Properties.Setting.Default["key"] = value;
Properties.Setting.Default.Save();
//read
value = Properties.Setting.Default["key"];
Related
I'm trying to build a program in which I consume an API through a client that a company has made available for its software.
Here's a link to it.
Though it does make it easier for one to establish a connection and make a call through its embedded methods, I'm having a difficult time manipulating the data once I receive it.
[Note: I know it's sort of meaningless to provide y'all with the background of the client and how I'm making the call, but I would think it'd be hard for one to get a glimpse of what's going on if I'm not even providing how the connection is happening behind the client or how the database looks.]
Previously, I tried manipulating the data directly after making the call like this (link below), but I realized this is too difficult for me since I'm still a noob at C#, and it's been hard to mess with the results (object) as a dynamic[] value.
Link
Therefore, I believe it'd be best if I pursue the route of getting the data as an object, serialize it, turn it to (json), and map it to properties. I believe once I do this it should be easier to manipulate the data because I'd have an easier time turning the data into single values, lists, etc. However, I'm having a difficult time connecting the dots at this point of the code.
This is what I have so far..
I'm only interested in the EntryID, NameFirst, and NameLast of the results, but further along the way I do see myself utilizing the info from the other fields of this table and others. If someone could help me make the connection from the results to these properties, I would very much appreciate it. This would be a huge step in the application I'm trying to build using this API data.
Thanks in advance!
Class of Properties Link
JsonData Processor Link
JSON Results from Call Link
using System;
using [Custom]Api;
using Newtonsoft.Json;
namespace testing2
{
public class Program
{
public static void Main(string[] args)
{
[CustomApi]Client connection = new [CustomApi]Client("BaseURL",
"Username", "Password");
var value =
connection.Select("Entry",Criteria.Equals("NameLast","Rincon Recio"));
string results = JsonConvert.SerializeObject(value);
///not sure if making results as string is the right call to begin
this
//[Syntax where I tell results to match properties of Class 1]
//[Create list of EntryID, NameFirst, NameLast]
//[Display list in listbox]
Console.WriteLine(results);
Console.ReadLine();
}
}
}
No, JsonConvert.SerializeObject(value) shouldn't make a difference.
Try Deserialising values to array of Class1.
Like so
var realResult = JsonConvert.DeserializeObject<Class1[]>(values);
Source
Im creating an Windows Phone app and I find myself writing the same MessageBox.Show("Same error message") multiple times. For instance
"Could not connect to server"
This happens when the user do not have internet access.
Is there somewhere I can put it so that I write the text once and fetch the same text all over the place?
I could write a static class, but maybe there is a file for this?
Is there somewhere I can put it so that I write the text once and fetch the same text all over the place?
Yes, there is a special kind of file specifically for this, called strings.resx. It lets you write
MessageBox.Show(strings.ServerNotFound);
instead of
MessageBox.Show("Server not found");
The added benefit (in fact, the intended purpose) of using strings.resx is that your application becomes easily localizable (see answer to this question): adding proper translations and setting the current locale is all it would take to change all strings that your application displays to users with their proper local translations.
If you want it to be multi-lingual in the end I'd go for the Resource.resx file.
If not, you can go for all kinds of solutions:
keep the string there where they make most sense, in the class where you use them
store them all together in a dedicated class
Like:
class MyClass
{
private static string MyString = "blah";
// other meaningful stuff
}
Or:
public class MyStaticStrings
{
public static string MyString = "blah1";
public static string AnotherString = "blah2";
}
You can create a static variable in the App.xaml.cs page in the App class, so that you can access it all over the application.
I have an asp.net 4.0 c# web application. I am using listview and formview controls with templates on my forms. I am trying to control the maxlength property of my bound textboxes without hard coding the field sizes into my aspx pages. I would like to when I first load the application fill some kind of local object or array with the column lengths of my fields and then use those values to dynamically set the maxLength field of textboxes.
There are so many methods out there to try and I am not sure what is the most efficient.
My sql to get the schema info is
SELECT TOP (100) PERCENT sys.sysobjects.name AS TableName, sys.syscolumns.name AS ColumnName, sys.systypes.name AS DataType,
sys.syscolumns.length
FROM sys.sysobjects INNER JOIN
sys.syscolumns ON sys.sysobjects.id = sys.syscolumns.id INNER JOIN
sys.systypes ON sys.syscolumns.xtype = sys.systypes.xtype WHERE (sys.sysobjects.xtype = 'U') AND (sys.systypes.name <> 'sysname')
ORDER BY TableName, sys.syscolumns.colid
how can i store this locally so I don't have to keep querying the server and I can I set this dynamically using c#
I am a semi newbie so as much detail as can be provided would be appreciated.
See you are getting the column lengths from the database, now you need to do this txtBox.MaxLength.
Doing this dynamically can be avoided if you already design your aspx pages tightly coupled with database tables.
But if you are sure you want to go this way then:
1.) On application start up fetch all the values from the DB and make a dictionary cache out of it, it will sit in memory as long as the application is up.
2.) Now, on each page load you need to read those values from the dictionary and use TextBox.MaxLength property to set the values. This way you are adjusting the max length property before it is delivered to the client machine.
Thats it !!!
Anyways, any approach of this sort will bring down application performance. Consider pre-designing aspx pages.
There are two main ways of doing this, static variables (essentially global variables) or using the application cache. Personally I prefer static variables as I find the API for System.Web.Caching to be over-complicated.
This is how you use static variables with a bit of a discussion on which is the best method (including how to use the new Lazy class in .Net 4.0+):
Why use System.Runtime.Caching or System.Web.Caching Vs static variables?
This is how to use System.Web.Caching:
http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx
I wouldn't worry too much about which is more efficient, the methods of doing this are almost identical performance wise.
Thanks for your suggestions. For my purposes I just kept it simple because this is a relatively small app.
Since I am using templates I have the same field defined multiple times in many places. Since my application data fields will be changing not infrequently, this just gives me one place in the application to change the maxLength property.
in my aspx page:
' MaxLength="<%# TableSchema.SomeField1Length%>" />
I made a class
public static class TableSchema
{
public static int SomeField1Length
{
get { return 15; }
}
public static int SomeField2Length
{
get { return 100; }
}
public static int SomeField3Length
{
get { return 15; }
}
}
It's seems to be working ok. I have to see if this causes a performance hit.
I want to declare a variable in such a way that I can access that particular variable and its value in all the asp pages in the project. Can anyone tell me how to declare a variable in C# such that it has project-wide scope?
You have a couple of choices and the best may require more specific information about what you are trying to accomplish. For example, do you need to be able to write to this variable as well?
But a simple approach is just to store it in the application object: Application["mydata"] = value;
Note that you can lose this data if your application is reset, which can happen from time to time. You can look at using cookies or a database to persist across resets.
Declare it as a "static" variable in a static class anywhere in the projects. You can declare it either as "internal" or "public".
However, you should always be careful about such a thing. If you need this, your design might need some work.
You can use a public property in the global.asax. That way you will be able to retrieve it from anywhere in the project.
global.asax:
private string _myvar = "";
public static string MyVar{ get { return _myvar; } set { _myvar = value; } }
any page code-behind:
string text = MyClassName.Global.MyVar
Based on what you said, I supose you want some kind of global variable.
If tha's the case you should learn about the Application object and, probably, initialize your variable in the Application_Start method of global.asax file
If you need some generic approach. Create a project in your solution called Common as class library. Add a class file and add some public static members there . Compile it to dll, and you are now ready to use the members within the solution and if you wnt to use the same in some other application you can use too by adding reference.
But if you need it for some specific time you can use either of them stated above. In addition you can also use Session["MyObject"] = object_value. All have cons and pros. Google and use what ever suits you best. You have various options now, :)
Application scope defined within your global.ascx file.
Thus: Application["VariableName"] = value.
If it is user and session specific, you could always store it in a session. It's simple as: Session["VarName"] = object;
You can use the HttpContext to store items that need to be accessed throughout the lifecycle.
Example:
HttpContext.Items["myVariableKey"] = "my value";
The item put into that collection are only available for the current request.
I have a console application that I am rebuilding from C to C#. This application has to be able to support the legacy method of storing information like parameters from a command-line and parameters from a file (called the system parameters) that customize each run. The system parameters file is in plain-text with a simple key-value structure.
My questions are:
Should I combine these different parameters into a single Configuration object?
How would I call this configuration object from the code to store parameters?
How would I call this configuration object from the code to retrieve parameters?
Should this object be strongly-typed?
I will need access to this structure from a lot of different places in the code. What is the most elegant way to retrieve the values in the object without passing the object itself around everywhere?
I have a feeling that it should be a single, strongly-typed object and that it should be an instantiated object that is retrieved from a repository with a static retrieval method however I really want validation of this method.
I would use a single configuration object like the following:
using System;
using System.IO;
using System.Reflection;
public sealed class Setting {
public static int FrameMax { get; set; }
public static string VideoDir { get; set; }
static readonly string SETTINGS = "Settings.ini";
static readonly Setting instance = new Setting();
Setting() {}
static Setting() {
string property = "";
string[] settings = File.ReadAllLines(SETTINGS);
foreach (string s in settings)
try {
string[] split = s.Split(new char[] { ':' }, 2);
if (split.Length != 2)
continue;
property = split[0].Trim();
string value = split[1].Trim();
PropertyInfo propInfo = instance.GetType().GetProperty(property);
switch (propInfo.PropertyType.Name) {
case "Int32":
propInfo.SetValue(null, Convert.ToInt32(value), null);
break;
case "String":
propInfo.SetValue(null, value, null);
break;
}
} catch {
throw new Exception("Invalid setting '" + property + "'");
}
}
}
Since this is a singleton, it will create one and only one instance of itself the first time a public static property is referenced from the Setting object.
When the object is created, it reads from the Settings.ini file. The settings file is a plain-text file with a simple key : value structure that might look like this:
FrameMax : 12
VideoDir : C:\Videos\Best
The object uses reflection to discover each property and to store its initial value. In this example, two properties have been defined:
public static int FrameMax { get; set; }
public static string VideoDir { get; set; }
The code as written handles Int32 and String types. By adding additional case statements to the switch statement, you could easily add support for types like Float and Decimal.
To change a setting, you would use something like:
Setting.FrameMax = 5;
To retrieve a setting, you would use something like:
if (Setting.FrameMax > 10) ...
You'll notice that all the properties are strongly-typed. Also, you don't have to pass the Setting object around, as all the Setting properties are static and always available everywhere.
I hope this idea is helpful.
I like using Settings. These can be generated automatically either by creating a settings file using the Add New File dialog box, or by adding a default settings file from project properties.
Each setting may be in user or application scope, which controls whether or not the user can change them or they are restricted to their default values. They are easily saved with the Save() method and loaded automatically into the static Default property.
This class seems to be for application or user-based settings. I'm looking for per-run settings. Would you still recommend using this class in that case? – x97mdr
Yes. If you have both user/application based settings and per-run settings you should use two different classes - the normal (saved) settings and the per-run settings.
As long as you don't save the per-run settings, you should be safe and settings are still quite easy to use. These are static settings though. If the same application run needs several instances - this is the wrong approach.
I find that whenever I have to deal with a legacy system, sticking with the old format almost always works best. Often times there are other people using the legacy formats for other tasks (like automation of the app, for example), so if you recode the way the application handles inputs, you might break other systems.
On the other hand, if you are pretty confident that you know all the people using the system, and they tell you that they don't care if you change these types of things, I would probably move everything to XML. Besides all the nice features of XML from an application point of view (like being in ASCII so it's easily modified by humans, being self-documenting, etc ...), XML is also time-saving, in that you don't have to write your own I/O or parser. There's already a wide variety of libraries out there, particularly in .NET 3.0/3.5, that do very well. (As you're moving to C#, I'm guessing you're already thinking along these lines :)
So ultimately, you'd have to base your decision on cost-to-implement: if you lower your cost of implementation by moving to XML or similar, make sure that you don't raise other people's cost of implementation to move to your new application framework.
Good luck!
XmlDocument - you can generate a class definition using XSD.exe