Search Results

Search found 42993 results on 1720 pages for 'static method'.

Page 4/1720 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Draytek Vigor 2820 static IP's

    - by dannymcc
    I have a Draytek Vigor 2820 router which is connected to our ADSL provider (British Telecom, BT). We currently have one static IP address which is accessible from anywhere outside of our network and points at a simple web server on port 80. We have just been given 5 more static IP addresses which I would like to point at five servers that have static IP's. As an example: Current static IP - 80.123.123.123 New Static IP's - 100.100.100.100-105 Server IP's - 192.168.1.129-133 I have confused myself completely between NAT addresses, static routes and WAN IP aliases. If anyone can give me a clear idea of what I need to do it would be greatly appreciated.

    Read the article

  • Creating a seperate static content site for IIS7 and MVC

    - by JK01
    With reference to this serverfault blog post: A Few Speed Improvements where it talks about how static content for stackexchange is served from a separate cookieless domain... How would someone go about doing this on IIS7.5 for a ASP.NET MVC site? The plan so far: Register domain eg static.com, create a new website in IIS Manually copy the js / css / images folders from MVC as is so that they have the same paths on the new server Enable IIS gzip settings (js/css = high compression, images = none) Set caching with far future expiry dates <clientCache cacheControlCustom="public" /> in the web.config Never set any cookies on the static.com site Combine and minimize js / css Auto deploy changes in static content with WebDeploy Is this plan correct? And how can you use WebDeploy to deploy the whole web app to one server and then only the static items to another? I can see there is a similar question, but for apache: Creating a cookie-free domain to serve static content so it doesn't apply

    Read the article

  • Static method , Abstract method , Interface method comparision ?

    - by programmerist
    When i choose these methods? i can not decide which one i must prefer or when will i use one of them?which one give best performance? First Type Usage public abstract class _AccessorForSQL { public virtual bool Save(string sp, ListDictionary ld, CommandType cmdType); public virtual bool Update(); public virtual bool Delete(); public virtual DataSet Select(); } class GenAccessor : _AccessorForSQL { DataSet ds; DataTable dt; public override bool Save(string sp, ListDictionary ld, CommandType cmdType) { } public override bool Update() { return true; } public override bool Delete() { return true; } public override DataSet Select() { DataSet dst = new DataSet(); return dst; } Second Type Usage Also i can write it below codes: public class GenAccessor { public Static bool Save() { } public Static bool Update() { } public Static bool Delete() { } } Third Type Usage Also i can write it below codes: public interface IAccessorForSQL { bool Delete(); bool Save(string sp, ListDictionary ld, CommandType cmdType); DataSet Select(); bool Update(); } public class _AccessorForSQL : IAccessorForSQL { private DataSet ds; private DataTable dt; public virtual bool Save(string sp, ListDictionary ld, CommandType cmdType) { } } } I can use first one below usage: GenAccessor gen = New GenAccessor(); gen.Save(); I can use second one below usage: GenAccessor.Save(); Which one do you prefer? When will i use them? which time i need override method ? which time i need static method?

    Read the article

  • Static classes and/or singletons -- How many does it take to become a code smell?

    - by Earlz
    In my projects I use quite a lot of static classes. These are usually classes that naturally seem to fit into a single-instance type of thing. Many times I use static classes and recently I've started using some singletons. How many of these does it take to become a code smell? For instance, in my recent project which has a lot of static classes is an Authentication library for ASP.Net. I use a static class for a helper class that fixes ASP.Net error codes so it can be used like CustomErrorsFixer.Fix(Context); Or my authentication class itself is a static class //in global.asax's begin_application Authentication.SomeState="blah"; Authentication.SomeOption=true; //etc //in global.asax's begin_request Authentication.Authenticate(); When are static or singleton classes bad to use? Am I doing it wrong, or am I just in a project that by definition has very little per-instance state associated with it? The only per-instance state I have is stored in HttpContext.Current.Items like so: /// <summary> /// The current user logged in for the HTTP request. If there is not a user logged in, this will be null. /// </summary> public static UserData CurrentUser{ get{ return HttpContext.Current.Items["fscauth_currentuser"] as UserData; //use HttpContext.Current as a little place to persist static data for this request } private set{ HttpContext.Current.Items["fscauth_currentuser"]=value; } }

    Read the article

  • Encapsulate update method inside of object or have method which accepts an object to update

    - by Tom
    Hi, I actually have 2 questions related to each other: I have an object (class) called, say MyClass which holds data from my database. Currently I have a list of these objects ( List < MyClass ) that resides in a singleton in a "communal area". I feel it's easier to manage the data this way and I fail to see how passing a class around from object to object is beneficial over a singleton (I would be happy if someone can tell me why). Anyway, the data may change in the database from outside my program and so I have to update the data every so often. To update the list of the MyClass I have a method called say, Update, written in another class which accepts a list of MyClass. This updates all the instances of MyClass in the list. However would it be better instead to encapulate the Update() method inside the MyClass object, so instead I would say foreach(MyClass obj in MyClassList) { obj.update(); } What is a better implementation and why? The update method requires a XML reader. I have written an XML reader class which is basically a wrapper over the standard XML reader the language natively provides which provides application specific data collection. Should the XML reader class be in anyway in the "inheritance path" of the MyClass object - the MyClass objects inherits from the XML reader because it uses a few methods. I can't see why it should. I don't like the idea of declaring an instance of the XML Reader class inside of MyClass and an MyClass object is meant to be a simple "record" from the database and I feel giving it loads of methods, other object instances is a bit messy. Perhaps my XML reader class should be static but C#'s native XMLReader isn't static.? Any comments would be greatly appreciated Thanks Thomas

    Read the article

  • Can Eclipse generate method-chaining setters

    - by Chris R
    I'd like to generate method-chaining setters (setters that return the object being set), like so: public MyObject setField (Object value) { this.field = value; return this; } This makes it easier to do one-liner instantiations, which I find easier to read: myMethod (new MyObject ().setField (someValue).setOtherField (someOtherValue)); Can Eclipse's templates be modified to do this? I've changed the content to include return this; but the signature is not changed.

    Read the article

  • Test a site with a static subdomain locally

    - by bcmcfc
    How can I test a site that uses one or more static domains for serving images locally? e.g. domain.tld with images servered from static.domain.tld Local working copy of the site on WAMP checked out from SVN: URLs will be pointing at static.domain.tld rather than static.domain.local

    Read the article

  • C# String.format extension method

    - by Paul Roe
    With the addtion of Extension methods to C# we've seen a lot of them crop up in our group. One debate revolves around extension methods like this one: public static class StringExt { /// <summary> /// Shortcut for string.Format. /// </summary> /// <param name="str"></param> /// <param name="args"></param> /// <returns></returns> public static string Format(this string str, params object[] args) { if (str == null) return null; return string.Format(str, args); } } Does this extension method break any programming best practices that you can name? Would you use it anyway, if not why? If I renamed the function to "F" but left the xml comments would that be epic fail or just a wonderful savings of keystrokes?

    Read the article

  • Javascript static method intheritance

    - by Matteo Pagliazzi
    I want to create a javascript class/object that allow me to have various method: Model class Model.all() » static method Model.find() » static method Model delete() » instance method Model save() » instance method Model.create() » static that returns a new Model instance For static method I can define them using: Model.staticMethod(){ method } while for instance method is better to use: function Model(){ this.instanceMethod = function(){} } and then create a new instance or using prototype? var m = function Model(){ } m.prototype.method() = function(){ } Now let's say that I want to create a new class based on Model, how to inherit not only its prototypes but also its static methods?

    Read the article

  • Override ActiveRecord#save, Method Alias? Trying to mixin functionality into save method...

    - by viatropos
    Here's the situation: I have a User model, and two modules for authentication: Oauth and Openid. Both of them override ActiveRecord#save, and have a fair share of implementation logic. Given that I can tell when the user is trying to login via Oauth vs. Openid, but that both of them have overridden save, how do "finally" override save such that I can conditionally call one of the modules' implementations of it? Here is the base structure of what I'm describing: module UsesOauth def self.included(base) base.class_eval do def save puts "Saving with Oauth!" end def save_with_oauth save end end end end module UsesOpenid def self.included(base) base.class_eval do def save puts "Saving with OpenID!" end def save_with_openid save end end end end module Sequencer def save if using_oauth? save_with_oauth elsif using_openid? save_with_openid else super end end end class User < ActiveRecord::Base include UsesOauth include UsesOpenid include Sequencer end I was thinking about using alias_method like so, but that got too complicated, because I might have 1 or 2 more similar modules. I also tried using those save_with_oauth methods (shown above), which almost works. The only thing that's missing is that I also need to call ActiveRecord::Base#save (the super method), so something like this: def save_with_oauth # do this and that super.save # the rest end But I'm not allowed to do that in ruby. Any ideas for a clever solution to this?

    Read the article

  • Why is there no facility to overload static properties in PHP?

    - by Jon
    Intro PHP allows you to overload method calls and property accesses by declaring magic methods in classes. This enables code such as: class Foo { public function __get($name) { return 42; } } $foo = new Foo; echo $foo->missingProperty; // prints "42" Apart from overloading instance properties and methods, since PHP 5.3.0 we can also overload static methods calls by overriding the magic method __callStatic. Something missing What is conspicuously missing from the available functionality is the ability to overload static properties, for example: echo Foo::$missingProperty; // fatal error: access to undeclared static property This limitation is clearly documented: Property overloading only works in object context. These magic methods will not be triggered in static context. Therefore these methods should not be declared static. As of PHP 5.3.0, a warning is issued if one of the magic overloading methods is declared static. But why? My questions are: Is there a technical reason that this functionality is not currently supported? Or perhaps a (shudder) political reason? Have there been any aborted attempts to add this functionality in the past? Most importantly, the question is not "how can I have dynamic static properties in userland PHP?". That said, if you know of an especially cute implementation based on __callStatic that you want to share then by all means do so.

    Read the article

  • Static DataTable or DataSet in a class - bad idea?

    - by Superbest
    I have several instances of a class. Each instance stores data in a common database. So, I thought "I'll make the DataTable table field static, that way every instance can just add/modify rows to its own table field, but all the data will actually be in one place!" However, apparently it's a bad idea to do use static fields, especially if it's databases: Don't Use "Static" in C#? Is this a bad idea? Will I run into problems later on if I use it? This is a small project so I can accept no testing as a compromise if that is the only drawback. The benefit of using a static database is that there can be many objects of type MyClass, but only one table they all talk to, so a static field seems to be an implementation of exactly this, while keeping syntax concise. I don't see why I shouldn't use a static field (although I wouldn't really know) but if I had to, the best alternative I can think of is creating one DataTable, and passing a reference to it when creating each instance of MyClass, perhaps as a constructor parameter. But is this really an improvement? It seems less intuitive than a static field.

    Read the article

  • Serving static content with Struts2: Tomcat error 404

    - by Nicolas Raoul
    With Struts2 I can't find a way to serve a static CSS :-/ Newbie question but I could not find any answer on the Internet: The CSS file is static/styles.css in my WAR file. Tomcat replies with 404 when I request http://server/myapp/static/styles.css But it works if I put styles.css at the root of the WAR and request http://server/myapp/styles.css I tried adding the following to my struts.xml in the only package but still 404: <action name="/static/*"> <result>/static/{1}</result> </action> Or as a second package: <package name="static" extends="struts-default" namespace="/static"> <action name="/static/*"> <result>/static/{1}</result> </action> </package>

    Read the article

  • VirtualBox - Public Static IP for a Debian Guest on a Dedicated Server

    - by user86296
    Goal: I want to run a Debian-squeeze-Guest in VirtualBox and it's own public static ip. I found tons of threads about this topic, but all in all I'm now trying for 10 hours (reading the manual, the forums, trying to learn about networking concepts & commands) to give a Guest his own public static ip (so that the Guest is similar to a vServer you can order from a hosting company), but wasn't able to. Since I'm a big noob as far as networking stuff is concerned, I'm probably doing something wrong.(please bear with me :-) ) Situation: VirtualBox 4.0.10 (headless no gui) is running on a dedicated Debian-Server, the Guest OS is Debian as well. The server has a static ip and I ordered an additional ip for a VM. Problem description: Upto now I was able to use NAT to access the VM from the outside and to setup an internal network between several Guests and all of this worked very well. When setting NIC 1 to bridged and configuring a public static ip on the guest, the guest was unpingable. (neither from outside, nor from the host) I could connect to the guest via the internal network, from another vm, though. ( VBoxManage controlvm VMGuest nic1 bridged eth0 ) ( configuration attempt of static-ip on the guest '/etc/network/interfaces' is below) Please let me know what I'm doing wrong, or what I can try to get it to work, or if you need more info. I think I've read that with a current VirtualBox-version for bridged networking no special host-configuration is necessary, is that accurate, or might that be the problem? Additional Info Info I got from the hosting company about the additional IP Please note that you can use the IP address only for this server. IP: 46.4.xx.xx Gateway: 46.4.xx.xx Mask: 255.255.255.248 VBoxManage showvminfo VMGuest |less ... NIC 1: MAC: 080027D72F7B, Attachment: Bridged Interface 'eth0', Cable connected: on, Trace: off (file: none), Type: 82540EM, Reported speed: 0 Mbps, Boot priority: 0 NIC 2: MAC: 080027B03B75, Attachment: Internal Network 'InternalNet1', Cable connected: on, Trace: off (file: none), Type: Am79C973, Reported speed: 0 Mbps, Boot priority: 0 NIC 3: disabled (...rest is disabled) cat /etc/network/interfaces on the Host-machine # Loopback device: auto lo iface lo inet loopback # device: eth0 auto eth0 iface eth0 inet static address 46.4.xx.xx broadcast 46.4.xx.xx netmask 255.255.255.224 gateway 46.4.xx.xx post-up mii-tool -F 100baseTx-FD eth0 # default route to access subnet up route add -net 46.4.xx.xx netmask 255.255.255.224 gw 46.4.xx.xx eth0 cat /etc/network/interfaces on the Guest-VM # This file describes the network interfaces available on your system # and how to activate them. For more information, see interfaces(5). # The loopback network interface auto lo iface lo inet loopback # The primary network interface allow-hotplug eth0 auto eth0 iface eth0 inet static address 46.4.xx.xx netmask 255.255.255.248 gateway 46.4.xx.xx auto eth1 iface eth1 inet dhcp ifconfig -a on the Guest shows the correct static ip for eth0 but the Guest is unreachable "over eth0" eth0 Link encap:Ethernet HWaddr 08:00:27:d7:2f:7b inet addr:46.4.xx.xx Bcast:46.4.xx.xx Mask:255.255.255.248 inet6 addr: fe80::a00:27ff:fed7:2f7b/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:21 errors:0 dropped:0 overruns:0 frame:0 TX packets:69 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:1260 (1.2 KiB) TX bytes:3114 (3.0 KiB) eth1 Link encap:Ethernet HWaddr 08:00:27:b0:3b:75 inet addr:192.168.10.3 Bcast:192.168.10.255 Mask:255.255.255.0 inet6 addr: fe80::a00:27ff:feb0:3b75/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:142 errors:0 dropped:0 overruns:0 frame:0 TX packets:92 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:15962 (15.5 KiB) TX bytes:14540 (14.1 KiB) Interrupt:16 Base address:0xd240 lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:123 errors:0 dropped:0 overruns:0 frame:0 TX packets:123 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:25156 (24.5 KiB) TX bytes:25156 (24.5 KiB)

    Read the article

  • Why does Java's invokevirtual need to resolve the called method's compile-time class?

    - by Chris
    Consider this simple Java class: class MyClass { public void bar(MyClass c) { c.foo(); } } I want to discuss what happens on the line c.foo(). At the bytecode level, the meat of c.foo() will be the invokevirtual opcode, and, according to the documentation for invokevirtual, more or less the following will happen: Look up the foo method defined in compile-time class MyClass. (This involves first resolving MyClass.) Do some checks, including: Verify that c is not an initialization method, and verify that calling MyClass.foo wouldn't violate any protected modifiers. Figure out which method to actually call. In particular, look up c's runtime type. If that type has foo(), call that method and return. If not, look up c's runtime type's superclass; if that type has foo, call that method and return. If not, look up c's runtime type's superclass's superclass; if that type has foo, call that method and return. Etc.. If no suitable method can be found, then error. Step #3 alone seems adequate for figuring out which method to call and verifying that said method has the correct argument/return types. So my question is why step #1 gets performed in the first place. Possible answers seem to be: You don't have enough information to perform step #3 until step #1 is complete. (This seems implausible at first glance, so please explain.) The linking or access modifier checks done in #1 and #2 are essential to prevent certain bad things from happening, and those checks must be performed based on the compile-time type, rather than the run-time type hierarchy. (Please explain.)

    Read the article

  • C# using consts in static classes

    - by NickLarsen
    I was plugging away on an open source project this past weekend when I ran into a bit of code that confused me to look up the usage in the C# specification. The code in questions is as follows: internal static class SomeStaticClass { private const int CommonlyUsedValue = 42; internal static string UseCommonlyUsedValue(...) { // some code value = CommonlyUsedValue + ...; return value.ToString(); } } I was caught off guard because this appears to be a non static field being used by a static function which some how compiled just fine in a static class! The specification states (§10.4): A constant-declaration may include a set of attributes (§17), a new modifier (§10.3.4), and a valid combination of the four access modifiers (§10.3.5). The attributes and modifiers apply to all of the members declared by the constant-declaration. Even though constants are considered static members, a constant-declaration neither requires nor allows a static modifier. It is an error for the same modifier to appear multiple times in a constant declaration. So now it makes a little more sense because constants are considered static members, but the rest of the sentence is a bit surprising to me. Why is it that a constant-declaration neither requires nor allows a static modifier? Admittedly I did not know the spec well enough for this to immediately make sense in the first place, but why was the decision made to not force constants to use the static modifier if they are considered constants? Looking at the last sentence in that paragraph, I cannot figure out if it is regarding the previous statement directly and there is some implicit static modifier on constants to begin with, or if it stands on its own as another rule for constants. Can anyone help me clear this up?

    Read the article

  • How can i get the value of a session variable inside a static method in c#?

    - by Pandiya Chendur
    I am using asp.net pagemethods with jquery.... How to get the value of a session variable inside static method in c#... protected void Page_Load(object sender, EventArgs e) { Session["UserName"] = "Pandiya"; } [WebMethod] public static string GetName() { string s = Session["UserName"].ToString(); return s; } when i compile this i get the error An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.Session.get' Any suggestion or any alternative...

    Read the article

  • Naming Suggestions For A Function Providing Method Chaining In A Different Way

    - by sid3k
    I've coded an experimental function which makes passed objects chainable by using high order functions. It's name is "chain" for now, and here is a usage example; chain("Hello World") (print) // evaluates print function by passing "Hello World" object. (console.log,"Optional","Parameters") (returnfrom) // returns "Hello World" It looks lispy but behaves very different since it's coded in a C based language, I don't know if there is a name for this idiom and I couldn't any name more suitable than "chain". Any ideas, suggestions?

    Read the article

  • Why some consider static analysis a testing and some do not?

    - by user970696
    Preparing myself also to ISTQB certification, I found they call static analysis actually as a static testing, while some engineering book distinct between static analysis and testing, which is the dynamic activity. I tent to think that static analysis is not a testing in the true sense as it does not test, it checks/verifies. But sure I would love to hear opinion of the true experts here. Thank you

    Read the article

  • Call a non static methode in a static SQLiteDatabase class

    - by Fevos
    i want to display a msg to the user (msg box or Toast) when exception happend in a static SQLite Database class that i use. the proplem is that i cant call a non static methode in a static class , how can i handle this. this is the class private static SQLiteDatabase getDatabase(Context aContext) { and i want to add something like this in the class when exception happen but context genertae the problem of reference to non static in static class. Context context = getApplicationContext(); CharSequence text = "Hello toast!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show();

    Read the article

  • Issues with static IP (Ubuntu Server 10.04)

    - by letseatfood
    I am following this tutorial for setting up a testing server for my web development projects. When I attempt setting up a static IP address (using the configuration below), I receive the error "ping: unknown host www.google.com" when I attempt using ping. auto eth0 iface eth0 inet static address 192.168.0.100 netmask 255.255.255.0 network 192.168.0.0 broadcast 192.168.0.255 gateway 192.168.0.1 Ping works fine when the configuration is: auto eth0 iface eth0 inet static I am a novice to server setup and administration.

    Read the article

  • Nginx: Serve static files out of a given directory - one level too deep

    - by Joe J
    I'm pretty new to nginx configs. I'm having some difficulty with a pretty basic problem. I'd like to host some static files at /doc (index.html, some images, etc). The files are located in a directory called /sites/mysite/proj/doc/. The problem is, is that with the nginx config below, nginx tries to look for a directory called "/sites/mysite/proj/doc/doc". Perhaps this can be fixed by setting the root to /sites/mysite/proj/, but I don't want to potentially expose other (non-static) assets in the proj/ directory. And for various reasons, I can't really move the doc/ directory from where it is. I think there is a way to use a Rewrite rule to solve this situation, but I don't really understand all the parts, so having some difficulty formulating the rule. rewrite ^/doc/(.*)$ /$1 permanent; I've also included a working example of hosting files out of a /sites/mysite/htdocs/static/ directory. > vim locations.conf location /static { root /sites/mysite/htdocs/; access_log off; autoindex on; } location /doc { root /sites/mysite/proj/doc/; access_log on; autoindex on; } 2011/11/19 23:49:00 [error] 2314#0: *42 open() "/sites/mysite/proj/doc/doc" failed (2: No such file or directory), client: 100.100.100.100, server: , request: "GET /doc HTTP/1.1", host: "myhost.com" Does anyone have any ideas how I might go about serving this static content? Any help is much appreciated. Thanks, Joe

    Read the article

  • VMWare Hypervisor vSphere 5 - VM static ip from VLAN NAT

    - by Ian Livingstone
    I have a VMWare vSphere 5 Hypervisor server that has a static ip address assigned to it by VLAN that is configured to perform NAT. The static IP is assigned to the bare metal server via the NIC's mac address. I want to setup a guest machine to also have a static ip address, how can I go about having this setup? I have assigned a IP for the guest's MAC Address but it doesn't seem to be working as when I ping the ip address it does not respond. The guest is running ubuntu 10.04 server edition. I am trying to assign it a static public ip address. Any help would be greatly appreciated.

    Read the article

  • The Template Method Design Pattern using C# .Net

    - by nijhawan.saurabh
    First of all I'll just put this pattern in context and describe its intent as in the GOF book:   Template Method: Define the skeleton of an algorithm in an operation, deferring some steps to Subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the Algorithm's Structure.    Usage: When you are certain about the High Level steps involved in an Algorithm/Work flow you can use the Template Pattern which allows the Base Class to define the Sequence of the Steps but permits the Sub classes to alter the implementation of any/all steps.   Example in the .Net framework: The most common example is the Asp.Net Page Life Cycle. The Page Life Cycle has a few methods which are called in a sequence but we have the liberty to modify the functionality of any of the methods by overriding them.   Sample implementation of Template Method Pattern:   Let's see the class diagram first:            Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:8.0pt; mso-para-margin-left:0in; line-height:107%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi; mso-font-kerning:1.0pt; mso-ligatures:standard;}   And here goes the code:EmailBase.cs     1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5 using System.Threading.Tasks;     6      7 namespace TemplateMethod     8 {     9     public abstract class EmailBase    10     {    11     12         public bool SendEmail()    13         {    14             if (CheckEmailAddress() == true) // Method1 in the sequence    15             {    16                 if (ValidateMessage() == true) // Method2 in the sequence    17                 {    18                     if (SendMail() == true) // Method3 in the sequence    19                     {    20                         return true;    21                     }    22                     else    23                     {    24                         return false;    25                     }    26     27                 }    28                 else    29                 {    30                     return false;    31                 }    32     33             }    34             else    35             {    36                 return false;    37     38             }    39     40     41         }    42     43         protected abstract bool CheckEmailAddress();    44         protected abstract bool ValidateMessage();    45         protected abstract bool SendMail();    46     47     48     }    49 }    50    EmailYahoo.cs      1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5 using System.Threading.Tasks;     6      7 namespace TemplateMethod     8 {     9     public class EmailYahoo:EmailBase    10     {    11     12         protected override bool CheckEmailAddress()    13         {    14             Console.WriteLine("Checking Email Address : YahooEmail");    15             return true;    16         }    17         protected override bool ValidateMessage()    18         {    19             Console.WriteLine("Validating Email Message : YahooEmail");    20             return true;    21         }    22     23     24         protected override bool SendMail()    25         {    26             Console.WriteLine("Semding Email : YahooEmail");    27             return true;    28         }    29     30     31     }    32 }    33   EmailGoogle.cs      1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5 using System.Threading.Tasks;     6      7 namespace TemplateMethod     8 {     9     public class EmailGoogle:EmailBase    10     {    11     12         protected override bool CheckEmailAddress()    13         {    14             Console.WriteLine("Checking Email Address : GoogleEmail");    15             return true;    16         }    17         protected override bool ValidateMessage()    18         {    19             Console.WriteLine("Validating Email Message : GoogleEmail");    20             return true;    21         }    22     23     24         protected override bool SendMail()    25         {    26             Console.WriteLine("Semding Email : GoogleEmail");    27             return true;    28         }    29     30     31     }    32 }    33   Program.cs      1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5 using System.Threading.Tasks;     6      7 namespace TemplateMethod     8 {     9     class Program    10     {    11         static void Main(string[] args)    12         {    13             Console.WriteLine("Please choose an Email Account to send an Email:");    14             Console.WriteLine("Choose 1 for Google");    15             Console.WriteLine("Choose 2 for Yahoo");    16             string choice = Console.ReadLine();    17     18             if (choice == "1")    19             {    20                 EmailBase email = new EmailGoogle(); // Rather than newing it up here, you may use a factory to do so.    21                 email.SendEmail();    22     23             }    24             if (choice == "2")    25             {    26                 EmailBase email = new EmailYahoo(); // Rather than newing it up here, you may use a factory to do so.    27                 email.SendEmail();    28             }    29         }    30     }    31 }    32    Final Words: It's very obvious that why the Template Method Pattern is a popular pattern, everything at last revolves around Algorithms and if you are clear with the steps involved it makes real sense to delegate the duty of implementing the step's functionality to the sub classes. Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:8.0pt; mso-para-margin-left:0in; line-height:107%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi; mso-font-kerning:1.0pt; mso-ligatures:standard;}

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >