When should we write static function in asp.net class - c#

I am having asp.net page where i have combo box . I am highly confused that how to fill that combo because i am having two approach
Fetch combobox data : by creating object of my database class. and call function for combobox data.
Fetch combobox data : using static function
When should we create static function and how can we decide whether function should be static or not.
Suppose i need to fill No of people living in city based upon city Id and there is another condition of filter like business group, service group, students.
What is better approach of filling combobox.

Function should be static if it's supposed to be stateless. Simple as that.

You can have a lot of scenario how to fill your combobox.
For example:
You can derive from ComboBox and you can fill they on on Load event (or on anyone else event, if you want)
You can have classes for combobox fill with same interface (for example: UserConboBoxFiller, InvoiceComboBoxFiller, ArticleComboBoxFiller, etc...)
You can have static methods for combobox fill - as you wrote. It's not wrong, in simple scenarios.
If you have several filter conditions for filling comboboxes, I recomend use the classes for filling:
public interface IComboBoxFiller {
void Fill( ComboBox cbo );
}
public class UsersComboBoxFiller : IComboBoxFiller {
public bool OnlyOnlineUsers {get;set;}
public void Fill( ComboBox cbo ) {
// there is logic for combobox filling
// you can dynamicly generate where condition
// by the "OnlyOnlineUsers"
}
}

You make your functions static if they do not need to work on class instances and access that instance state.
Static classes and functions are of common use in web applications because these applications are mostly stateless working over stateless HTTP. Or at least they mimic statefulness by using some tricks like sessions, cookies or injecting some helper content into HTML. But even so, there is almost no state in PC memory as such - objects are created to serve the request and deleted after the response has been sent. So, classes and functions are mostly there to pack user data and sent it to the database and in reverse direction. Mostly, just dataflow processing.

Related

Where to put Global List of object used in the Application C#?

Where to put Global List of object used in the Application C#?
Let's say I got a list of category, which I want to be able to use any time, without having to retrieve these categories each time I need to use it.
What I will do is to retrieve the categories and store it to the List of category at startup. Then I will use this List of category, to update the items if there is changes to the items or access the items when I need to do operations on the time.
How can I do this?
My application is splitted up in a console layer, dataaccess layer and Logic layer. Where do I usually store this kind of List in order to be able to access it any time?
Right now I'm having a
public dynamic Categories{ get; set; }
Which I save the data to.
I'm using dependency injection, Ninject.
Please create as static.
public static dynamic Categories{ get; set; }
Not sure if you need DI for that, but one thing you could do is declare a static class lets say CategoriesCache which has a static list (or any kind of approporiate datastructure) and fetch the list at application startup. After that you can use that list. Maybe store it at app shutdown.
If you want to solve it with DI I can provide you with a snippet (SimpleInjector, but you can tailor it to your needs) for a similar problem:
public class ServiceBootstrapper
{
serviceContainer.Register<IApplicationSettings>(() => ApplicationSettings.Read(), Lifestyle.Singleton);
}
Note: This isn't a proper thing to do if your categories ever change during app lifecycle.

Can a function return a static function?

TL;DR: the title says it all, and a simple answer would be great if the question can be answered simply
Longer Version:
I am using a pre-existing library to build invoices, and the library holds the instantiation of the invoice object and static functions which add items to the invoice. The items on the invoice include breakdowns of sub-items, and it has about a dozen columns. No item uses all the columns, and the column usage and values depends on the item listed and it's depth within a breakdown.
So, the invoice can be built with pseudocode like this:
Invoice customerInvoice = new Invoice();
MainItem widget = new MainItem(); //the entirety of the sale, this is shown as the top-level item
SubItem component = new SubItem(widget, values[]); //a component of widget. The parameters identify the main piece that this attaches to, and a set of values for the other columns.
SubItem piece = new SubItem(widget, values[]); //another component; the values[] will be slightly different but correspond to the same columns.
SubItem bolt = new DeepSubItem(piece, lowestValues[]); //an irreducibly small item which is a part of the "piece" item, with it's own set of values which fill a different arrangement of columns
Components and sub-components are shown on indented lines below their parent object.
I am trying to create a new class structure that can help simplify this. The largest problem is that values[] here represents about 20 individual parameters. Additionally, a maze of conditional statements is necessary due to quirks of individual products, variations based on sale location or time, and many other factors. The only constant is that each function corresponds to a single line on the invoice. The original library was great at nesting objects properly, but it can't handle the logic. The SubItem instantiations of piece, bolt, and component only exist so that they can be broken down. When SubItem() or DeepSubItem() are called, the objects are attached to the object that they include in their parameter.
First question: What is a good plan/design pattern/strategy to build a new structure that can use the existing library, but provide flexible logic?
Second question: If I could create an 'instance' of the static functions, I could use that instance without the great verbosity of the parameters. Is there any way to do this, or something that will have a similar effect?
I've been thinking of creating a new class that will conduct the logic and hold the needed sets of values. That class can then create 'objects' (ideally, instances of the static functions) which I can use in the code we already have, replacing the function calls. That would allow me to separate the verbosity (which rarely needs to change) from the logic (which often needs to change). I can't simply use the object "bolt" because the moment I instantiate it, it is added to the invoice - hence why I want to treat the function like an object.
Your wise input (and/or reality check) is greatly appreciated. Thanks,
One of the ways you could do this would be to use the Func object. This allows you to pass functions by reference. Here's an example:
private static object TestStaticFunction()
{
return "test";
}
public static Func<object> GetStaticFunction
{
get { return TestStaticFunction; }
}
Then, any function that calls GetStaticFunction will get TestStaticFunction returned to it. Likewise, Console.Write(GetStaticFunction()) will display "test".
Note that if you want to pass a method that does not return a value, use Action instead.
Here's the MSDN documentation on Func: http://msdn.microsoft.com/en-us/library/bb549151%28v=vs.110%29.aspx
And another StackOverflow thread with more explanation: What is Func, how and when is it used
As far as your program design, I'm not really sure that I understand the library well enough to point you towards a better pattern. Are you forced to work within this library?
Are you talking about delegates?
class Program
{
static void Main(string[] args)
{
var returnedFunction = TestClass.FunctionToReturnAStaticMethod();
returnedFunction();
}
}
public class TestClass
{
public delegate void TypeOfFunctionToReturn();
public static TypeOfFunctionToReturn FunctionToReturnAStaticMethod()
{
return () => StaticMethod();
}
public static void StaticMethod()
{
Console.WriteLine("\"StaticMethod\" called");
}
}

M-V-VM: What is the best way to handle model data that is generated dynamically from XmlSerialized data

I have both, actual user-generated data and data that depends on it (like the background color of UniformGrid cells that is used to indicate dupe values in the grid, which is calculated each time an INotifyPropertyChanged is fired from the grid's ObservableCollection). There are other such objects that are interdependent in the model. Now when deserialized, depending on the order of the objects in the model class, some dependending objects are updated correctly and some are not. (I come from MFC programming and am used to call UpdateData() after loading a file and set all DDX controls at once.)
The whole thing is quite susceptible to getting buggy on subsequent changes in the code and feels very clumsy. It's like many things with WPF: If you want to acomplish an easy task, it's done in no time. If you want something specific, it gets much more complicated than it should. Is there any good practice how to deal with the problem?
It seems like your main propblem is the correct separation of concerns. WPF & MVVM is quite different from more traditional methods of Windows development.
First up, let's get something sorted here - it might just be a confusion with the terminology, but I'll mention it.
In MVVM the model is not used to store data.
Can it be used to hold data? Yes.
Should it be used to hold data? No.
Holding and transforming the data is the job of the viewmodel. The job of the model is to act as a conduit, it fetches the data (i.e. retrieves from your repository, or controls communication with WCF services, etc). If your model is holding data that means your view will be binding to the model, which is wrong.
Some of the data you talk of should also be held in the view. Determining whether something is a duplicate can be determined in the viewmodel, possibly even in the model (the model could apply business rules and flag data as it passes through). The color to show for the duplicate is a view responsibility - unless that color is determined by business rules, then you can move it to the viewmodel.
You are binding to an ObservableCollection, which infers that you are using a repeater type control like a DataGrid. In this case each row is not aware of any other row. If you fire a property change event from the data object of one row, another row will be totally unaware of it and therefore cannot change how it is rendered based on those changes. In cases like this you must adjust the data of the related row in an observer pattern way.
When you have interdependencies like this, it is normal to wrap each actual data object in another lightweight object that acts as a facade, some people refer to this as having a viewmodel for each row's data object. For example here is a simple Customer object:
public class Customer
{
public string FirstName {get; set;}
public string Surname {get; set;}
}
As you store this in the ObservableCollection in your viewmodel you can wrap it:
public class CustomerWrapper
{
private Customer _customer;
public CustomerWrapper (Customer customer)
{
_customer = customer;
}
public bool HasRelation{get;set;}
public Customer Customer { get {return _customer;}}
}
Now if you want to indicate an interdependency between your Customer objects, for example if they were part of a family, you can simply set the HasRelation property once the CustomerWrapper object has been created:
var myCustomerList = GetMyCustomers();
foreach (var customer in myCustomerList)
{
myObservableCollection.Add(new CustomerWrapper(customer)
{
HasRelation = myCustomerList.Where(p => string.Equals(p.Surname, customer.Surname).Count() > 1)
});
}
Now when you bind your repeater control to the ObservableCollection you can use the HasRelation property to control UI color etc.
Keep in mind that I've kept this is a contrived example and I've kept it simple, I've deliberately missed some stuff out to keep it brief. If your viewmodel subscribes to the property changed event of each Customer object it can then update the CustomerWrapper objects as needed. The interdependency state doesn't need to be stored with the data in the repository because you can determine it each time you display the data. One of the things I ommitted was wrapping the FirstName and Surname proeprties - you could put in a wrapper property for them, or you can simply use the path in your XAML's binding to drill down to the nested object.

Storing Methods in Entity Framework Database

Is there a simple way to store methods in an EF table, akin to inheritance?
For example, I have a table representing apps on a portal page (kind of like your basic iphone or android home screen). I'd like to display a number by each app showing how many notifications the app has. However, the method to get the number of notifications varies greatly depending on the app.
My current solution is to just have a class containing all the methods I need, and then switch based on the app name. Is there a better way?
Assuming that your method to obtain the notifications is parameterless, you could store the method name in a column in that table and invoke it via reflection. For this example we'll call the column/property NotificationMethodName.
//this would go in your entity class
public int GetNotificationCount()
{
MethodInfo mi = typeof(HelperClass).GetMethod(this.NotificationMethodName);
return (int)mi.Invoke(this, null);
}
public class HelperClass
{
//your class that currently has all the methods to get notification count
}

Accessing a listview box

I am pretty new to programming in c#. I have a listview (ListViewProjects) box in ProjectListForm but I want to be able to access the items in the listview box in AddProjectForm. How can I access them? I was going to try to do something like this
ProjectListForm.ListViewProjects.Items.Clear
but when I type in ProjectListForm., ListViewProjects isn't an option.
You can either set the list view's design time options to generate a public member (in control's properties, under Design set Modifiers to Public), or possibly better you could add a public property to ProjectListForm to expose either the list view or just the Items collection, eg:
public class ProjectListForm : Form
{
...
public ListView.ListViewItemCollection ProjectsListViewItems
{
get { return ListViewProjects.Items; }
}
}
The best way IMO is to write public methods in ProjectListForm that do what you're trying to achieve in AddProjectForm, such as ProjectListForm.ClearProjects(). That way you're not forcing AddProjectForm to depend on the implementation of ProjectListForm, say if you later want to change to a TreeView.
You cannot achieve this way in C#. you need to create the instance of the object.
To do this you have to create the method in ProjectListForm and in that methos you have to call this.ListViewProjects.Items.Clear.
Now from the AddProjectForm you have to call this method of the running instance of ProjectListForm.
If you want to know more about how to make the call, then please give the flow about how do you show the AddProjectForm from the ProjectListForm.

Categories

Resources