How to store a text lib in an efficient way - c#

I would ask you what you think about the method I use to store a lot of string constant that I use in my program.
The goal is not to block memory resources and have some text string used for, an example, a debugger, but not only, basically its a text library used in all my program with some default text string.
I first thought about a singleton class but I don't know if it would be more efficient in this case, while singleton is in the heap and not cool for memory issues while the struct is normally in the stack and seeing microsoft advice would be more efficient.
here is the code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
MessageBox.Show(Library.Apps_txt.resultvalue);
//I want to be able to call that in any form or class using this namespace
}
}
public class Library
{
public struct Apps_txt
{
public static String resultvalue { get { return "result value IS: "; } }
public static String Pbexcept { get { return "Exception has raised."; } }
//thousand of string.
//...
public static String mystring1000000 { get { return "my string 1000000"; } }
}
}
Thanks a lot.

Related

Is a static Application variable in c# a bad idea

I've two Classes
public class DemoProperty
{
public int ID { get; set; }
public string Title { get; set; }
public string MenuCode { get; set; }
public string OriginalURL { get; set; }
}
public class MyCommonProperties
{
private static List<DemoProperty> _DemoList;
public static List<DemoProperty> DemoList
{
get { return _DemoList; }
set { _DemoList = value; }
}
}
My need is to keep some common data throughout the project.For that I've using an application variable and it holds a Dictionary<string,List<DemoProperty>>.
Global.asx
void Application_Start(object sender, EventArgs e)
{
Application["DemoProperty"] = new Dictionary<string,List<DemoProperty>>();
MyCommonProperties.DemoList= (Dictionary<string,List<DemoProperty>>)Application["CommonProperties"];
}
Actually I don't know more about its demerits. If it is a bad idea could you please suggest me a good one.
What the static keyword ensures, is that the specific property / class exists only once in your application.
If this is bad or not is a very general question to which the answer unfortunately seems to be "it depends". Ultimately it is a question how you want to design you program.
Making something static can however make automatic testing harder, because you can not easily decouple your program into smaller testable parts (as all parts directly interact with your static data). It also makes reading the code harder, because it could be hard to understand when and what modifies the global data.
I will try an example to underline this:
class Data {
public static string Entry;
}
class Operations {
void SetOne() {
Data.Entry = "one";
}
}
With this example, for someone calling SetOne() it might be non-obvious that the method actually sets something in Data.
Another approach could be:
class Data {
public string Entry;
}
class Operations {
void SetOne(Data data) {
data.Entry = "one";
}
}
Now for the caller its is more obvious that Data is used in some way by the method, because the call now looks like SetOne(data).
In my humble personal experience static was almost never a good idea. While it might make things quicker in the short run, its drawbacks concerning readability & testability of your code are usually too big to ignore.

Wrapper Class Method Parameters

Apologies but this is new to me, I will gladly explain further or edit this post where necessary.
I have a project class library which I need to create a wrapper class library for. This class contains custom classes for constructors, which are then used as parameters in the methods that I'll be calling from my wrapper.
Within my wrapper I don't really want to have to use a using statement referencing the original class library, so I was wondering what the best way to handle these custom constructors are?
Here is an example I knocked up of what the DLL I'm wrapping looks like:
public CustomResult WriteMyDataAndReturnResult(CustomerWriterData data)
{
CustomerResult result = // Do stuff
return result;
}
public partial class CustomResult
{
private int resultId;
private MyResponse response;
public int resultIdField
{
get { return this.resultId; }
set { this.resultId = value; }
}
}
public partial class MyResponse
{
private string myMessage;
public string myMessageField
{
get { return this.myMessage; }
set { this.myMessage = value; }
}
}
public partial class CustomerWriterData
{
private string outputPath;
private string inputPath;
public string myOutputPath
{
get { return this.outputPath; }
set { this.outputPath = value; }
}
public string myInputPath
{
get { return this.inputPath; }
set { this.inputPath = value; }
}
}
So in the example above in my wrapper I'd be looking to have a method that calls WriteMyDataAndReturnResult, but this contains a custom object. What would be the best way to handle things in terms of this? I have toyed with the idea of recreating each of the partial classes in my wrapper, and then having convert methods to change from one to the other, but this seems like I'd be re-writting a lot of code.
Is there a better way for me to avoid having to include a using statement to the original library within code that calls my wrapper project?
Sorted it myself by creating a script that mapped the API to my DTO objects. This wasn't the path I specifically wanted to take, but it at least allowed me to create a separation between the 3rd party API and my main code.

The name does not exist in the current context. Not seeing class

I am very new to C# coding, so this may be very simple. In my Site.Master.cs, I have the following code:
GetLoggedInUserProperties();
lblLoginUser.Text = string.Format("Welcome {0}", Session[SessionVars.UserName]);
In a class file, I have put the following in a Public Class:
void GetLoggedInUserProperties()
{
string sLoginId = Program.ExtractUserName(HttpContext.Current.Request.ServerVariables["LOGON_USER"]);
HttpContext.Current.Session[SessionVars.LoginId] = sLoginId;
VerifyInAD(sLoginId);
}
There are no errors in the class file, but my Site.Master.cs cannot find the code in the class file.
I am sure there is a better way to do this, so feel free to let me know. Also, the lblLoginUser does not seem to work either. It has the same error. I have tried recreating the label and deleting the designer file (which never came back). Not sure if this is related or not.
Thank you.
You need to make your methods public or protected to be visible from the markup. So if you want to reference GetLoggedInUserProperties() from the markup, you'll need to change your method declaration to something like this.
protected void GetLoggedInUserProperties()
{
}
Make your method public
Here your class
public class ClassName
{
public void GetLoggedInUserProperties()
{
}
}
public MainWindow()
{
InitializeComponent();
ClassName instance = new ClassName();
instance.GetLoggedInUserProperties();
}
Or make your class static and call your method :
public static class ClassName
{
public static void GetLoggedInUserProperties()
{
}
}
public MainWindow()
{
InitializeComponent();
ClassName.GetLoggedInUserProperties();
}

access TextBox And DropDownList Values from a class inside code behind

i know i lack a base knowlage of the realtions between classes and inheritance
i find it hard to understand a simple thing :
a given DDl or TextBox could be accessed from code behind
int selected = DDLID.SelectedIndex ;
string userInput = TBXID.Text;
Now from a class that is placed in code behind :
public static class ControlsValue
{
public static int UserSel = DDLID.Selected.index;
public static string UserText = TBXID.Text;
}
i was trying to "Arange" my code so i will be able to reuse it in some other projects
...so i have moved all global variables related to the code in that class into the class
and what i can't do is assign variables with webControls Values
what is the way to do it ?
update
a way i could think of is via parameter
public static class ControlsValue
{
public static void getValues(DropDownList DDLID)
{
public static int UserSel = DDLID.Selected.index;
}
public static string UserText(TextBox TBXID)
{
return TBXID.Text;
}
}
Create a different class like this
public class ControlValues{
private int_dropDownIndex;
public int DropDownIndex{
get { return _dropDownIndex; }
set { _dropDownIndex= value; }
}
private string _textBoxValue;
public string TextBoxValue{
get { return _textBoxValue; }
set { _textBoxValue= value; }
}
public ControlValues(int dropDownIndex, string textBoxValue){
this._dropDownIndex = dropDownIndex;
this._textBoxValue = textBoxValue;
}
}
You can create an instance from your code behind like below
ControlValues cv= new ControlValues(DDLID.Selected.index, TBXID.Text);
Now you can access the DropDown index and text as
cv.DropDownIndex;
cv.TextBoxValue;
Although I provided an answer for this, Please note:
Remember the stateless nature of web application and the way you are going to use this.
In ASP.NET, it will be inefficient to create an Instance of class to hold values of server control because those controls and their values are directly accessible from the code behind. Using this approach will be an extra overhead.
If you are serious about learning re-usability, I would strongly recommend you to learn basics of object oriented programming. Once you have a good grip of OOP, you will see clearly when to apply OOP principles.

How can I return a ReadOnly object class with mutable properties while allowing write access

I've got quite a number of classes, which have got the standard set and get methods. My problem is that many of these set methods should not be callable from outside the class which holds the objects. I'm not quite sure if there are any patterns or C# for lack of a better word - operations that would make this easier.
In reference to the code below, there are a number of classes similar to SecureSite, which the controller should be able to call functions or access variables to modify the SecureSite (and the other similar classes). However when the user asks to see SecureSite etc. they shouldn't be able to change this.
From my limited knowledge and the answers I've seen to similar questions on this site, the main issue appears to be that the Write_SecureSite can't be made fully immutable due to the List<String> AccessHistory variable. So, what I've come up with looks as ugly as a bulldogs backside and is just as messy. Essentially there is a Write version of the SecureSite class which contains a class within it, which returns a readonly version of the SecureSite class.
So, am I missing something magic in C# that would make this all so much easier?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ReadOnlyExample {
public class Write_SecureSite {
private List<String> mAccessHistory;
public List<String> AccessHistory {
get {
return mAccessHistory;
}
}
public SecureSite ReadOnly {
get {
return new SecureSite(this);
}
}
public class SecureSite {
public SecureSite(Write_SecureSite aParent) {
AccessHistory=aParent.AccessHistory;
}
public IEnumerable<String> AccessHistory;
}
}
public static class Controller {
private static Write_SecureSite SimpleSecureSite=new Write_SecureSite();
public static Write_SecureSite.SecureSite Login(String MyLogin) {
SimpleSecureSite.AccessHistory.Add(MyLogin);
return SimpleSecureSite.ReadOnly;
}
public static Write_SecureSite.SecureSite Details() {
return SimpleSecureSite.ReadOnly;
}
}
public static class User {
public static void Miscellaneous() {
Controller.Login("Me");
Write_SecureSite.SecureSite SecureSite=Controller.Details();
//Not going to happen.
SecureSite.AccessHistory.Add("Me2");
//No problem.
foreach(String AccessedBy in SecureSite.AccessHistory) {
Console.Out.WriteLine("Accessed By: "+AccessedBy);
}
}
}
}
I suggest to use interfaces:
public interface IReadSecureSite
{
IEnumerable<String> AccessHistory { get; }
}
class Write_SecureSite : IReadSecureSite
{
public IList<String> AccessHistoryList { get; private set; }
public Write_SecureSite()
{
AccessHistoryList = new List<string>();
}
public IEnumerable<String> AccessHistory {
get {
return AccessHistoryList;
}
}
}
public class Controller
{
private Write_SecureSite sec= new Write_SecureSite();
public IReadSecureSite Login(string user)
{
return sec;
}
}
...
Controller ctrl = new Controller();
IReadSecureSite read = ctrl.Login("me");
foreach(string user in read.AccessHistory)
{
}
This is not so much an answer as a direction to look into. I am also struggling with the Immutable class
So far I am using my constructors to set my read-only private vars
I am using methods to update my lists internally instead of exposing them as public properties: ie. use public Void Add(string itemToAdd)
I am reading a book by Petricek and Skeet called "Real World Functional Programming" and it is helping me move in the direction you are discussing
Here is a small tutorial from the same author's that introduces some basic concepts: http://msdn.microsoft.com/en-us/library/hh297108.aspx
Hope this helps a bit
Update: I probably should have been clearer: I was looking to point you in the direction of a more functional view as opposed to rewriting the class you had listed in your question - my apologies (removed sample)

Categories