C#

I’ve just realized that my web app is not keyboard friendly. How’s yours?

Visual FoxPro!

Today I’ve met a senior programmer. He used visual foxpro for his latest ERP system. Honestly I’m amazed with what kind of features that foxpro can provide and how good they are. Foxpro, really? That old not-popular programming language? Maybe that’s what you have in mind. But honestly, you’ll be amazed by how good Foxpro interact with database objects. Moreover, how fast the database is! Though it haven’t being tested over 50 users though.

I’m amazed at the features of foxpro!

So? Do we all move to foxpro all together? No, foxpro is good, but not in every aspect. One of the reason is that application structure is very tightly coupled with the data object, which is good for administrative tools but not for the other. I’m not using foxpro, so I can’t give more reason, and that topic is not what I want to discuss now.

It’s a desktop app!

I just want to shared that the visual foxpro that has been developed is desktop app. I must admit that no matter how good you are at web programming, you can’t defeat the UI functionality and keyboard-friendly functionality of desktop apps. There isn’t even safe cross browser hotkey that can be used in web. While in app, you can easily navigate using arrows, tabs, function keys (I’m pointing at you, F1-F12!), page up page down, control + keys, etc. Not to mention the responsiveness, and the functionality of one-page application (nah, ajax can’t even compete with it).

Web apps won’t win against desktop in UI and keyboard functionality

Man, I missed the desktop-based development time of my university time.

But that’s it. Desktop integrated system is losing popularity over year, as better web environment is emerging such as web socket, html5, css3, etc. But I must say that web apps will never beat desktop apps for transaction-intensive activities. No POS (point of sales) in hypermarkets using it.

Hypermarket using web-based POS? How slow will it be?

Do you imagine integrating barcode scanner with web apps? Do you imagine using mouse to choose which payment method? What will happen if they need to wait for respond after submitting, waiting for the payment change? That won’t do. We must back to our very first factor of application development: requirement. If they require it, then it must be done.

The very first factor of application development: requirement

So, we back to desktop app?

Yes for that particular activities. But how many of those transaction-intensive activities are there? There won’t be many of that kind transaction in today’s business. More often we need flexibility and portability more than keyboard shortcut. Let’s say reports, approvals, notes, attachments, all of them are better cross-browsers and portable. Employee self service (reimbursement, leave) is better online. Marketing will be more awesome online, since it can directly communicate to media via links and connections.

Of course we must ignore web-specialized features such as online trading, blog and social media though.

reports, approvals, notes, attachments, reimbursement, leave is better online

Conclusion

We go back to the very first rule of application development: requirement. If it is required to have intensive-transaction application or embedded devices (printer, barcode scanner), then use desktop. If not, then it’s better web since it’s easier to access and easier to maintain and publish. So, compare and plan before deciding the approach!

Embed Asp.Net MVC views in class library dll

If you’re anything like me, you may want to define asp.net mvc views in class library, so that it can be used from anywhere. However, it’s not an easy task, regarding the MVC architecture of asp.net mvc. The view normally be placed at Views folder physically, making us unaware of possibility to embed the view and controller to shared library (dll).

Define view in library

Create the view file

You can create the view file inside library project. If you cannot find the view template from add file, you can choose text file then rename the extension as cshtml (razor) or aspx.

Set the view as embedded resource

The view file need to be set as embedded resource during compilation, so that the file can be referenced from other projects.

Set the build action into embedded resource

Set the build action into embedded resource

How to make asp.net mvc find embedded view

There is a way to tell asp.net mvc to look up from specific source. One of them is embedded view. It can also get from database but I haven’t tried that or need a case for that.

To tell the asp.net mvc to look up at embedded resource, first we need to define a VirtualFile (System.Web.Hosting.VirtualFile). VirtualFile class can act as a “false” view file. When accessed, it can read the embedded resource file and return it instead of serving the asp.net mvc engine with physical file. Next step, we need to supply asp.net mvc with VirtualPathProvider class that can direct the engine into finding and serving the VirtualFile instead of physical file. Both of the files that will make it possible to serve asp.net views from source other than physical file.

Here’s the code for both class (with supporting class):

    public class EmbeddedResourcePathConfiguration
    {
        public EmbeddedResourcePathConfiguration(string rootNameSpace, string viewFolderName, Assembly resourceAssembly)
        {
            this.RootNameSpace = rootNameSpace;
            this.ViewFolderName = viewFolderName;
            this.ResourceAssembly = resourceAssembly;
        }
        public string RootNameSpace { get; set; }
        public string ViewFolderName { get; set; }
        public Assembly ResourceAssembly { get; set; }
        public string ViewNameSpace
        {
            get
            {
                return RootNameSpace + "." + ViewFolderName;
            }
        }

    }

    public class EmbeddedResourceNameProvider
    {
        private EmbeddedResourcePathConfiguration configuration = null;
        public EmbeddedResourcePathConfiguration Configuration
        {
            get { return configuration; }
            set { configuration = value; }
        }

        public string GetResourceName(string virtualPath)
        {
            var resourcename = virtualPath
                .Substring(virtualPath.IndexOf(configuration.ViewNameSpace));

            return resourcename;
        }
    }

    public class EmbeddedVirtualFile : VirtualFile
    {
        public EmbeddedVirtualFile(string virtualPath, EmbeddedResourcePathConfiguration configuration)
            : base(virtualPath)
        {
            this.configuration = configuration;
            EmbeddedResourceNameProvider.Configuration = configuration;
        }
        private EmbeddedResourcePathConfiguration configuration = null;

        EmbeddedResourceNameProvider embeddedResourceNameProvider = new EmbeddedResourceNameProvider();
        public EmbeddedResourceNameProvider EmbeddedResourceNameProvider
        {
            get { return embeddedResourceNameProvider; }
            set { embeddedResourceNameProvider = value; }
        }

        public override Stream Open()
        {
            string resourcePath = EmbeddedResourceNameProvider.GetResourceName(VirtualPath);
            return configuration.ResourceAssembly.GetManifestResourceStream(resourcePath);
        }
    }
    public class EmbeddedViewPathProvider : VirtualPathProvider
    {
        EmbeddedResourceNameProvider embeddedResourceNameProvider = new EmbeddedResourceNameProvider();
        public EmbeddedResourceNameProvider EmbeddedResourceNameProvider
        {
            get { return embeddedResourceNameProvider; }
            set { embeddedResourceNameProvider = value; }
        }

        private EmbeddedResourcePathConfiguration configuration = null;
        public EmbeddedViewPathProvider(EmbeddedResourcePathConfiguration configuration)
        {
            this.EmbeddedResourceNameProvider.Configuration = configuration;
            this.configuration = configuration;
        }

        private bool IsVirtualFile(string virtualPath)
        {
            return virtualPath.Contains(configuration.ViewNameSpace);
        }

        private bool ResourceFileExists(string virtualPath)
        {
            var resourcename = EmbeddedResourceNameProvider.GetResourceName(virtualPath);
            var result = resourcename != null && configuration.ResourceAssembly.GetManifestResourceNames().Contains(resourcename);
            return result;
        }

        public override System.Web.Caching.CacheDependency GetCacheDependency(string virtualPath, System.Collections.IEnumerable virtualPathDependencies, DateTime utcStart)
        {
            if (IsVirtualFile(virtualPath))
            {
                return new System.Web.Caching.CacheDependency(configuration.ResourceAssembly.Location);
            }
            return base.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
        }

        public override bool FileExists(string virtualPath)
        {
            if (IsVirtualFile(virtualPath))
            {
                bool exists = ResourceFileExists(virtualPath);
                return exists;
            }
            else
            {
                return base.FileExists(virtualPath);
            }
        }

        public override VirtualFile GetFile(string virtualPath)
        {
            if (IsVirtualFile(virtualPath))
            {
                return new EmbeddedVirtualFile(virtualPath, configuration);
            }
            else
            {
                return base.GetFile(virtualPath);
            }
        }
    }

Register the path provider into applications

The last step is to register the path provider to application. You can use the following code at global.asax, inside Application_Start.

EmbeddedResourcePathConfiguration configuration =
                    new EmbeddedResourcePathConfiguration(
                        rootNameSpace: "HtmlViewTemplate",
                        viewFolderName: "Views",
                        resourceAssembly: Assembly.Load("HtmlViewTemplate"));
                HostingEnvironment.RegisterVirtualPathProvider(new EmbeddedViewPathProvider(configuration));

Framework development is hard

Note: I intended to make this article only as draft or brainstorming article, however my idea maybe useful for some of the reader. This article will lack supporting source and theory, and maybe having un-arranged topic. I’ll try to publish another article after some time after this to re-arrange the writing.

Have you ever tried to develop framework, or even as simple as code library? Is it easy? Is it hard? Well yeah, the answer is it depends. It depends based on the complexity and size of framework/library you develop. But I think that it is fairly easy to develop at start. It will get harder to develop when the framework is already large enough, especially modifying existing features.

I can’t imagine how hard the developer at .Net / C# is when developing new version.

Backward Compatibilty

It’s hard. Jon Skeet also say that backward compatibility is hard. I have developed a medium-sized framework for Asp.Net MVC server side for around 1 year. In that elapsed time span, I have made around three breaking changes. Without good architect / planner, the library will be likely have bad structure and need to be refactored much.

I don’t think that if asp.net still support backward compatibility with asp classic, it will still have the utilities and flexibility as it have now. What will happen if the new C# version does not consider backward compatibility? What powerful feature that can be introduced by the breaking change? Here I will say that “without backward compatibility, the new version of a framework should be much more powerful”.

Defining name, namespace categorization

Defining name is not easy. Often I don’t know how to name a specific class / operation. In a worse case, the class name will be very long to express the operation.

Categorizing the operation is even harder. Will it be put under Excel namespace? App namespace? Web namespace? Javascript? etc. Most of the time I refactor is because the incorrect namespace category / project placement.

Flexible / Parameters definition

Developing framework / library is not easy. Developing flexible library is even harder. Most of the time, the breaking change will happen at different parameter definition. Mostly can be handled using default parameter, while the other need to be added or modified, introducing breaking change.

Another problem during developing library is the amount of parameter required for an operation (function / method). Often we find that the operation need many parameters. That kind of structure is not recommended, because it will make the operation harder to use. Encapsulating the parameters into one class may be useful, but again it introduce another model. Moreover, many parameters usage is a sign of “god object“, which is hard to maintain.

Parameter initialization / life cycle

Parameter initialization is another pain. Many times I find the case where when I want to use object A in class X, it haven’t been fully initialized yet. Or worse, you can only use object A in class X after you do operation Z.

The setup + parameter structure

Despite the limitation, I like the idea in some of .Net’s library structure. XmlSerializer is one of them. The process that is needed to use XmlSerializer is: instantiate object, define setup, do operation (serialize). Inside the class, there exists some “setup” object, where you can modify to change the operation behavior, instead of passing all the setup objects yourself. Moreover, it has “default” setup parameter, in which you will need less effort rather than constructing the setup parameter down from zero.

It has limitation though, the “mutability”. The mutability at service object is bad. You cannot use the same object over and over again. One object is used one operation, unless the same setup is required at the operation. Don’t use the setup + parameter structure when you are using long-lasting object (such as static object).

Separate context class with service class

I am the follower or Anemic Domain Model pattern despite being classified as anti pattern. I think ADM with POCO class (DTO-style) really supporting SRP, instead using RDM, in which we can easily fall into the god object anti pattern. It’s not that I say RDM tend to violates SRP, however I find that in most case, it is easier for RDM to violates SRP rather than ADM’s antipattern bring cause.

That’s why I usually like to separate context class (as data model) with service class (the operation). The context is an object that hold all the data required during one “operation life cycle”. Example: AppContext hold all data required during application running. Setup class is a context, it holds all the data required during the class’s operation. In Asp.Net, RequestContext holds all data required during the web request.

Meanwhile service class hold almost no data and only responsible to process the request passed from parameter (in exception to the setup class). StringBuilder is one of them. I also like to separate entity (domain model) class with it’s operations. That way, I can easily develop more class to handle different business rules and cases.

The separation is intended to scope and encapsulate the operation / context. That scoping will be useful to make the class’s modification easier. Any modification happen at one service class won’t break other operation in other service class.

Don’t refer to static context directly

I admit, I also like to do something like this:

public void Do(){
    string userId = App.Context.Current.User.UserId;
    if(userId == "....") { /*the operation*/ }
}

It is a bad design in general, because we cannot use the service without the context. However, passing the context into parameter is out of question. It will increase operation complexity. However, you can separate the context into class’s property and do lazy loading for default context.

private App.Context context;
public App.Context Context{
    set { this.context = value; }
    get { return (this.context ? (this.context = App.Context.Current)); }
}

public void Do(){
    string userId = this.Context.User.UserId;
    if(userId == "....") { /*the operation*/ }
}

Now you can mock the context easily and provide it to the class before processing. And it’s testable now.

Conclusion

Framework development is hard.

DataBinding is Neat

Data binding is a nice feature and powerful. I am quoting what Martin Fowler has said in his article about state:

One copy of data lies in the database itself. This copy is the lasting record of the data, so I call it the record state. A further copy lies inside in-memory Record Sets within the application. Most client-server environments provided tools which made this easy to do. This data was only relevant for one particular session between the application and the database, so I call it session state. The final copy lies inside the GUI components themselves. This, strictly, is the data they see on the screen, hence I call it the screen state.

Data binding primarily used to solve the synchronization problem between state in GUI (screen state) with application memory state. Any change happen at GUI reflected to memory and vice versa. It is the ideal solution for developer who do not like to do anything twice or multiple times.

Why is databinding is an ideal solution for us developers?

  1. Less code for developers
    It is the absolute benefit for developers since less code means less work, less review and less debugging. As most of developer is often quoted with: It seems that perfection is attained not when there is nothing more to add, but when there is nothing more to remove. In rough understanding, it means faster development.
  2. Consistent
    The code used for handling data binding is same for entire system/framework. It means one solution for a case is also applicable for the same case in other place. Also in some other words, the consistency itself is DRY, since it follows “Every piece of knowledge must have a single, unambiguous, authoritative representation within a system”.
  3. Flexible
    A good databinding feature can give you more flexibility. You can do modification with the display easier and nice, with less code to do.
  4. Encourage Single Responsibility Principle
    It helps to decouple your viewmodel with your UI. Databinding can help to remove the responsibility to handle UI update from your viewmodel, thus encourage SRP.

Conclusion

Databinding can help you to solve synchronization problem between UI state and memory state, and a nice feature to have. If you are doing intensive data entry with updated UI here and there, it can provide you with flexibility and ease of use to freely modify the display.

But does it have any drawback aside from it’s powerful functionality?

Code Smell : Stringly Typed

This is a reposted article from the old blog.

This term “Stringly Typed” were coined from codinghorror site here. It is described as “an implementation that needlessly relies on strings when programmer & refactor friendly options are available”. Now, have you ever think that you can replace almost every data type, even functions / methods with string? If not, then you can see it here.

(more…)

Code Smell : Array-based Data Model

This is a reposted article from the old blog.

In OOP, you have classes to define your data model. Your class can be passed between methods and even other classes as well, making it very flexible to be used, and at the same time still keeping the data structure. It is nice isn’t it? Unfortunately, there are a group of programmers who like array-based data model more rather than modeling using classes.

If you find those group working for medium-high complexity projects, quickly demoted them, and exclude them from the socialization. If you find yourself doing the same thing, quickly go to nearest worship place and atone your sin, then begin to start a new life. Is it that bad? Yes it is. Why? Here we go:

(more…)