|
Try:
Process.Start(@"http://codeproject.com");
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
using System.Diagnostics;
Process.Start("URl");
|
|
|
|
|
|
Does anyone really use Factory Patterns? To me, it seems like it involves a lot of classes that create other classes. What's the point?
If it's not broken, fix it until it is
|
|
|
|
|
It doesn't neccessarily involve a lot of classes. E.g. I have a factory class for creating an instance of a database-access-wrapper-class (abstract base class with concrete implementations for SQL-Server, Postgres, ..). Depending on the supplied parameters it creates that database-access-wrapper-class-instance for the appropriate database. The point is that its not really the responsibility of the created class to know about all variants, it should just do its own specialized job.
|
|
|
|
|
It can be as simple as a function that returns a new instance of something. The point is that it's more flexible than a constructor. It can choose which type to return an instance of, and it can be overridden in ways that a constructor can not be. It's often abused, to the point that many people cringe upon seeing the word "factory", but it's useful sometimes. It's one of those patterns (well, aren't they all) that you've probably invented yourself before even learning it was a pattern and had a name.
|
|
|
|
|
I asked because many times when I see a factory (ThisFactory<t> or ThatFactory(int x)), it's usually just a class with one method with a switch statement that returns an instance.
I don't see the real fascination with factories, so I thought I'd ask.
If it's not broken, fix it until it is
|
|
|
|
|
The abuse is probably more rampant in Java. Factory classes are only occasionally useful. Compared to factory methods they have only slightly more power (you can pass an instance of them as faux-delegate (this actually makes sense in Java), they can keep state (but that's ugly), they could have a subclass and have a factory to create factories (please no)).
Coder For Hire wrote: switch statement that returns an instance. Well, that's really the point. The rest is just details.
|
|
|
|
|
|
Coder For Hire wrote: it involves a lot of classes that create other classes.
That actually is abstract factory.
In the Factory pattern, classes are responsible for creating their own instances.
Some Patterns are useful.
So long as your code is decoupled (Class B should not change behaviour because A changed) and cohesive (each class doing only one thing), you would be ok.
|
|
|
|
|
IDbConnection.CreateCommand is a factory. Call it from a SqlConnection, you get a SqlCommand.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
I use it quite a bit in class libraries so that I can use a custom MEF DI framework. It allows my applications to self-assemble without requiring explicit support from the application that uses the library.
|
|
|
|
|
I would appreciate hearing more details about this technique.
thanks, Bill
«To kill an error's as good a service, sometimes better than, establishing new truth or fact.» Charles Darwin in "Prospero's Precepts"
|
|
|
|
|
Sure,
First we need an interface to hold the metadata that we want to have our queries based on. In this case, we'll just use a name variable:
public interface IExportMetadata
{
string Name { get; }
}
Then generally I'll tag an export that I plan to provide multiple instances for with a custom ExportAttribute, such as:
[MetadataAttribute, AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class MyAttribute : ExportAttribute
{
public string Name { get; set; }
public MyAttribute(Type type, string name) : base(type) { Name = name; }
}
Then I can tag anything I export with a name so that it can be targeted:
[My(typeof(IMyInterface),"Test!")]
public class MyClass
{
...
}
And then my factory can provide it to a host application based on a specific request or a configuration:
public static class MefProvider
{
private static readonly Lazy<CompositionContainer> _container =
new Lazy<CompositionContainer>(() => new CompositionContainer(_catalog.Value));
private static readonly Lazy<AggregateCatalog> _catalog =
new Lazy<AggregateCatalog>(() => new AggregateCatalog(
new AssemblyCatalog(Assembly.GetExecutingAssembly())));
public static CompositionContainer Container
{
get { return _container.Value; }
}
public static T Provide<T>(string name = "")
{
if (string.IsNullOrWhiteSpace(name))
{
return _container.Value.GetExportedValueOrDefault<T>();
}
return Container.GetExports<T, IExportMetadata>()
.Where(x => x.Metadata.Name
.Equals(name, StringComparison.InvariantCultureIgnoreCase))
.Select(y => y.Value)
.FirstOrDefault();
}
}
|
|
|
|
|
Hi,
My application has a properties class that I currently instantiate in a form. I then read values from a database to store in the class. I use this class to store settings I need in the form currently.
I want this class to be application wide instead, as more than one form (or other class) will need the data. I defined my properties class in the namespace already.
If I want to instantiate the class for the WHOLE application, should I use the app.Properties.Settings.Default to use it application wide? This is not an object I want to persist. I will create and load it up every time the application starts.
Can I define an instance of the class as static member in the program.cs module? Load it up by running a function before the application.Run is executed?
I don't want this to be form dependent if possible, as I want to re-use the concept in my future applications, whether they are forms, services etc.
What is the best method to accomplish this cleanly?
Best wishes!
|
|
|
|
|
I tend to think of Properties.Settings.Default as being "persistent" for a given user / client machine; not something that is restored from a database.
For your case I would consider using System.Windows.Application and its "Properties" property to store and access your settings object(s). Application.Properties is a thread-safe dictionary.
You may want to define some public static wrapper methods (somewhere) to standardize access and facilitate black-box testing.
|
|
|
|
|
Well that looks like what I was looking for. If it is thread safe, all the better, I can use that in any application, whether it is a gui or a service. I want to use the same 'framework' to speed my app dev. What I am doing now is I load up application settings from a database table and use this in the app. ( same settings table for all the apps in one area of the company, a column for app name)
I suppose the application properties can use a reference to any object? I not only have some value types, but I also have object types such as arrays, dictionnaries and lists. Would those also work in the application.properties property?
THanks a bunch, that was helpful.
|
|
|
|
|
Yes; you can store any type of object; just like the "Tag" property on most controls; or like "Sender" on events.
For a reference type, you can use it like this:
MySettings settings = Application.Current.Properties["Settings"] as MySettings;
Use a cast for simple value types.
|
|
|
|
|
Hi,
Unless I am missing something, this properties property is for a WPF object. In my case this is a plain old forms app.
If I add a static member in the Program class in program.cs would this do the trick properly? is this a proper method of doing things? The other option could be to create a static class in the namespace that has the objects containing the data I use. I am not sure what the right way is...
|
|
|
|
|
(Yes; that was a WPF class ... I assumed too much).
You can get the same functionality as WPF Application.Current.Properties using a ConcurrentDictionary from the System.Collections.Concurrent namespace; i.e. a thread-safe dictionary that can be keyed using a string and can have object values; e.g.
public static ConcurrentDictionary<string,object> MySettings = new ConcurrentDictionary<string,object>();
MySettings[ "Now" ] = DateTime.Now;
Don't know about "proper", but when I build something that is going to be used in multiple apps, I tend to create a "class library" (i.e. DLL) and reference that. I might give the above its own class so that I can standardize access using get/set instead of having a consumer use string keys.
|
|
|
|
|
After giving it some thought and using good old google, I was reading about static classes vs singleton designs.
I decided to use a singleton class. I defined the class inside a separate file to keep it modular. Inside my class I have the properties I need. Initially the properties that are objects are null. They are they populated when the application runs its startup stuff.
I am also including utility functions, such as a write to logfile function, since it uses a log directory setting in the class.
The ConcurrentDictionary sounds like a great idea to put all my settings in. It could make my class completely portable to any future apps I will write.
Your opinion on this design?
Thanks a lot for the help!
|
|
|
|
|
I've seen different "patterns" for implementing singletons ...
You can have a static class that has a static constructor for initializing static fields / properties. The static constructor is called only once and at the time when the class is first referenced.
If I have a static property referencing an object that is instantiated in the static constructor with a private setter and a public getter, then in my way of thinking I have a "singleton" using a static class.
That meets my requirements; and I like the static methods in this case.
|
|
|
|
|
You can also use a Lazy singleton for thread safety. This also has the inherit benefit of lazy instantiation.
public class MyStaticSingleton
{
#region Instance Control
private static Lazy<MyStaticSingleton> _instance =
new Lazy<myStaticSingleton>(() => new MyStaticSingleton());
private MyStaticSingleton(){}
public static MyStaticSingleton Instance
{
get { return _instance.Value; }
}
#endregion
#region Properties, methods, etc...
...
#endregion
}
|
|
|
|
|
I am trying to modify a PerformanceCounter I have created in C#. But it doesn't seem to be that it is being changed. This counter needs actualy to be a flag : 0 or 1.
I took the following code from the codeproject. It created the collectors category along with the counters well. But the RawValue always shows 0!
I am working on Win7/64.
Can you advise please?
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace PerformanceCounterSample
{
class PerformanceCounterSampleStarter
{
[DllImport("Kernel32.dll")]
public static extern void QueryPerformanceCounter(ref long ticks);
<pre>
[STAThread]
static void Main(string[] args)
{
PerformanceCounterSample test = new PerformanceCounterSample();
Random rand = new Random();
long startTime = 0;
long endTime = 0;
for (int i=0; i<1000; i++)
{
QueryPerformanceCounter(ref startTime);
System.Threading.Thread.Sleep(rand.Next(500));
QueryPerformanceCounter(ref endTime);
test.DoSomeProcessing(endTime - startTime);
}
}
}
public class PerformanceCounterSample
{
private PerformanceCounter m_cntrJoinConctConf_VPG_MyJamboLogin;
public PerformanceCounterSample()
{
if (!PerformanceCounterCategory.Exists("JamboCpmTool"))
{
CounterCreationDataCollection counters = new CounterCreationDataCollection();
CounterCreationData VPG_MyJamboLogin = new CounterCreationData();
VPG_MyJamboLogin.CounterName = "JoinConnectConf_VPG_MyJamboLogin";
VPG_MyJamboLogin.CounterHelp = "Join Connect Conf VPG MyJambo Login Success";
VPG_MyJamboLogin.CounterType = PerformanceCounterType.NumberOfItems64;
counters.Add(VPG_MyJamboLogin);
// create new category with the counters above
System.Diagnostics.PerformanceCounterCategory.Create("JamboCpmTool", "Sample category for Codeproject", PerformanceCounterCategoryType.SingleInstance, counters);
}
// create counters to work with
m_cntrJoinConctConf_VPG_MyJamboLogin = new PerformanceCounter();
m_cntrJoinConctConf_VPG_MyJamboLogin.CategoryName = "JamboCpmTool";
m_cntrJoinConctConf_VPG_MyJamboLogin.CounterName = "JoinConctConf_VPG_MyJamboLogin";
m_cntrJoinConctConf_VPG_MyJamboLogin.MachineName = ".";
m_cntrJoinConctConf_VPG_MyJamboLogin.ReadOnly = false;
m_cntrJoinConctConf_VPG_MyJamboLogin.RawValue = 0;
}
///
/// Increments counters.
///
/// <param name="ticks" />The number of ticks the AverageTimer32 counter must be incremented by
public void DoSomeProcessing(long ticks)
{
m_cntrJoinConctConf_VPG_MyJamboLogin.RawValue = 100L;
Console.WriteLine("m_cntrJoinConctConf_VPG_MyJamboLogin = " + m_cntrJoinConctConf_VPG_MyJamboLogin.RawValue);
}
}
}
|
|
|
|
|
how to make Textbox for numbers with a comma thousand seperator and can clear this C#
|
|
|
|