Automatic control in ASP.NET MVC

Posted By Venu Thomas

Although the convention proposed by the ASP.NET MVC framework help us to structure our applications and, in most cases, be more productive, occasionally also require us to enter repetitive code to comply with the proposed standard.

For example, in the case of controllers with actions that return the default view, we usually use a code like the following:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Create()
    {
        return View();
    }   

    public ActionResult Edit()
    {
        return View();
    }

    public ActionResult Delete()
    {
        return View();
    }

}

It’s not terrible, but drivers with many actions of this type can be a bit heavy … can not we do something to improve this?
Automatic controllers

Looking at the driver code above, we see that the execution logic is very simple: every action returns the user implemented view as rightful convention. Obviously this is a widespread behavior may be playing with the extension mechanisms of the framework.

A very quick way to do it is to overwrite the method HandleUnknownAction() class Controller , described here some time ago , which allows us to process the requests made to non-existent shares in the controller.

Remember that when a request comes to a controller, running the method whose name matches the action invoked, in the absence of the framework call HandleUnknownAction() , allowing us to take control of the situation. In our case, we could introduce the logic in this method to return the user, automatically, a view whose name matches the action, following the standard naming convention.

To do this, simply create a base class called AutoController , and enter the following code to have the problem solved:

public class AutoController : Controller
{
    protected override void HandleUnknownAction(string strActionName)
    {
 
        //  Try to find a view with the name of the action ...
 
        ViewEngineResult viewResult = ViewEngines.Engines.FindView
                            (this.ControllerContext, , null) ;
 
        if (viewResult.View != null)
        {
            View(strActionName).ExecuteResult(ControllerContext);
            return;
        }
 
        // If we have not found anything, we follow the
        // Default behavior ...
 
        base.HandleUnknownAction(strActionName);
    }

Simple, no? All we do in the code is to use the library ViewEngines to seek a view whose name matches the action you are trying to run, returning it to the user if possible locate it.

If you can not find a view for the action invoked, will run the default treatment for this situation, which is nothing more than throwing an exception of type HttpException with error 404 (not found).

That’s it! From this point, all the driver classes that inherit from AutoController include this behavior, so it will be possible to avoid the implementation of methods whose sole mission is to return the default view as convention.

For example, the driver that we wrote at the beginning of this post might be as follows, much more compact:

public class HomeController: AutoController
{
}

But beware if that is not gold that glitters …

However, before using this technique we must be clear what it really means to not run into unpleasant surprises.

Each request received by the controller is not explicitly implemented will be processed with the operator introduced in HandleUnknowAction() without passing through any type of filter, or send any information in the ViewData .

For example, it would be possible to access the view directly, only know her name, which in some scenarios may be dangerous from the point of view of system security.

Obviously, the technique is also not valid at times when the sight expect to receive some form of driver information (like data view, or indication of use of a specific master page), or when the action must be decorated with a filter .

In these cases, these concrete actions should continue to be implemented explicitly in the controller, but the rest can continue to be processed automatically:

public class HomeController: AutoController
{
    // GET /Home/Employers
    //  Only for registered users
    [Authorize]
    public ActionResult Employers()
    {
        return View();
    }
 
    // GET /Home/Salary
    public ActionResult Salary()
    {
        var varAppServices = new AppServices();
        return View(varAppServices.GetReferences());
    }
 
    // GET /Home/{ExamplePage}
    // Default processing, returns the view {ExamplePage}
}

In summary, in this post we have studied a technique that allows us to create drivers capable of providing a default for all requests made to the same, saving the writing of actions that simply return the default view.

And although, like everything else, practice has limitations and dangers, its use can be interesting websites without major safety requirements, such as public information websites, whose drivers are mostly of the type described.

Processing requests for actions not available in ASP.NET MVC

Posted By Venu Thomas

ASP.NET MVC controllers that inherit from the Controller can easily process the requests made to actions not defined. To do this, all you have to do is override the method HandleUnknownAction() and implement the logic that we want to run in these cases.

In the following code, the requests made to /Home/Index and /Home/About will be processed normally, but /Home/ActionPage will be processed by HandleUnknownAction , whose implementation will show the view “Index” with a personalized message:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";
        return View();
    }

    public ActionResult About()
    {
        return View();
    }
protected override void HandleUnknownAction(string strActionName)
(
ViewData ["Message"] = "Are you trying to" + strActionName + "?"
View("Index").ExecuteResult(this.ControllerContext);
)
)

Happy Programming!! ;-)

Internet Explorer 9 is the perfect browser!

Posted By Venu Thomas

Are you laughing? Do you think this is a joke? because nothing could be further from reality. It turns out that the new Internet Explorer 9 on track to be the best browser on the market, leaving far to browsers such as FireFox and Google Chrome …

Click for large view

According to tests performed by Microsoft’s IE9 scored 100% in every test.
The test consists of 192 tests with collaboration of the World Wide Web Consortium (W3C), the test includes testing of HTML 5, CSS 3, DOM Level, SVG … and a lot of things that god knows are

Well whether the result is 100%, you can see the entire test in the Windows Internet Explorer Testing Center I still can not believe it, as the saying goes “seeing is believing” but bueee… This would be a clear example of how to move from being the worst browser on the market to be the best and only one version.

Anywhere: Twitter JavaScript API

Posted By Venu Thomas

1 month ago Chirp was made, the official conference for developers of Twitter. And there were several developments around the world Twitter. Among them, a new page for developers of Twitter: dev.twitter.com , where we see new tools. In which we focus, being the closest to the theme of the blog is @Anywhere . @Anywhere is a Javascript API that lets you integrate Twitter with your site in a few lines of Javascript. Before you start using it to register as a developer you provide an API key, for it is the call for an application registration Anywhere . After this step, we must only add to the headers of our web page calling this script:

<script src="http://platform.twitter.com/anywhere.js?id=YOUR_API_KEY&v=1" type="text/javascript"></script>

Once you add this script are the way to initialize @ Anywhere is:

twttr.anywhere(function (T) {
// Your code here ...
});

As you can see it calls a function and pass a callback function with a parameter T (you can call it whatever you want). Which will be executed once the script loaded Twitter @ Anywhere. With this API, now you can do the following:

  • AutoLink Twitter usernames
  • Hovercards
  • Follow Buttons
  • Tweet Box
  • User Login

I invite you to the try. From Wisecodes are preparing some demos that you’ll use to teach during these weeks.

Use Google Font Directory website to help you change the text to add a variety of fonts

Posted By Venu Thomas

Every time they issue more and more APIs, and Google is one of the most free APIs. This time has presented at conferences Google I/O, made on 19 and 20 of May, Google Font API . This API helps you to add fonts in any web page. This is about as clear benefit:

  • Font Having high-quality open source
  • It works in most browsers
  • It is extremely easy to use.

You can see all the fonts available in the Google Directory of Fonts . For now have 18 sources, with variations in italics, bold, bold italic. In addition one of them has 10 different families. Therefore we have an extensive catalog that will allow us to another style to our website and get out of the typical universal fonts.

In addition, the catalog is very carefully because it has a tab for each of the fonts. Tab you can find the name of the designer, with a link to his biography and other personal data. You also have the description of the letterpress and the set of characters. There are also examples of texts in different sizes from 36px to 12px, in different colors, # 000, # 333 and # 666, and different variants, italic, bold and bold italic can see the example of typography Cararell sheet .

If you find interesting and want to see how to include it in your web tell you different ways, just by using CSS and Javascript.

Only with CSS

You have several ways to include the fonts on your website. The simplest of all is to include an additional style sheet:

<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Font+Name">

Then simply use the font in your style sheet in the usual way:

CSS selector {
  font-family: 'Font Name', serif;
}

If you do not want to load all variants, the variants can specify that you want to add two points and variations you want separated by commas:

<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Font+Name:variante">

If you want to add multiple fonts, it is necessary to make a call each of them, simply separate the names with pipes “|” is sufficient:

<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Tangerine|Inconsolata|Droid+Sans">

And if you want to do everything at once just follow all the above rules and looks something like this:

<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Tangerine:bold,bolditalic|Inconsolata:italic|Droid+Sans">

Using Javascript

If you do not want the burden of your page is affected by having to solve other DNS servers and upload you can not control, you can try WebFont Loader. A Javascript API that gives you more control over the fonts loaded. This form is also very simple, but requires a minimum knowledge of Javascript. To add these lines into the head of your page should have everything ready for use

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js">
</script>
<script type="text/javascript">
   WebFont.load({
   google: {
      families: [ 'Tangerine', 'Cantarell' ]
   }
  });
</script>

This loads the fonts listed in families and if all went well and the browser supports these fonts will be added in the html classes’ wf-active “and” wf-family-type-active ‘(eg’ wf-Cantarell -n4-active ‘).

This allows us to use our font style sheet alternatives in case of not having the desired load of this:

 .wf-inactive h1 {
       font-family: serif;
     }
     .wf-active h1 { 
       font-family: 'Tangerine', serif;
     }

With Loader WebFont sources can apply to other providers such as called Books TypeKit or even make any font suppliers overnight specifying the supplier .

In the call to Loader WebFont can specify callbacks to run your own code at any given time. Calback functions of which are available:

  • loading() Called when all modules of web fonts providers (google, typekit, and / or custom) have reportadoq ue start loading fonts.
  • fontloading(fontFamily, fontDescription) is called when it starts charging each application for web typography. FontFamily parameter is the name of the font family, and fontDescription represents the style and font weight.
  • fontactive(fontFamily, fontDescription) Called when loading has finished each of the applications.
  • fontinactive(fontFamily, fontDescription) is called if an application has failed to load.
  • select() is called when all web fonts have been loaded or not you were able to charge, as long as at least one is loaded successfully.
  • inactive() is called if the font web browser does not support or none of the sources failed to load.

Google free command line tool to access Web services

Posted By Venu Thomas

Google announced a command-line utility called GoogleCL based on Python . The tool offers various Google services from the command line, including Blogger, Calendar, Contacts, Picasa, Google Docs, and YouTube.

You can download the Linux package or compressed tar file here .

Once installed, you can access Google services from the command line. Access to services is generally limited to a few commands, usually “Add / Upload,” “Delete” and “List.” YouTube, Picasa, Blogger and all let you add tags to your posts, and Picasa also lets you download your photos with one command “get”.

“List” can also give different arguments to define how results are returned as title, url, author, date, and location.

Members of Google Street View team, Jason Holt, and Tom Miller said the team hopes to have the tool included in Debian and Ubuntu repositories in time for their next release.

Five reasons why HTML5 is much better to Flash

Posted By Venu Thomas

If the war was popular in internet browsers, then the standards, now is the HTML5 versus Flash . Which is better? – Why prefer one over another? I think HTML5 is the future. I also believe that Flash has always been a nuisance rather than an asset (and I think since 1999, eight years before it becomes a problem on the table by Apple ).

I believe the right way is to develop on HTML5 for everyone involved, and these are my five reasons why it is better to Flash:

  1. It is native. No need for plugins , extra amenities or load external components to the browser. Flash, unfortunately, being heavy and often need to consume so many resources faster the battery and use a large percentage of the processor.
  2. It does not belong to anyone, is a markup language that can be used by anyone and is supported by all modern browsers. Flash, however, is the owner, serves the interests of one company, Adobe. May be altered to taste them if needed (for whatever reason, economic, by company policy, etc.)
  3. Maintains the overall user experience the web, run the previous and next buttons in the browser, does not operate within a “sandbox” as with Flash, is not limited to the area assigned to the plugin.
  4. All items with all effects and all hierarchies needed to build a fully functional graphical interface to support a web application is 100% possible using HTML5 + CSS + Javascript. Flash was used as a replacement. Gmail is the perfect example. Even more so if viewed from a mobile device. Did you know that the version of Gmail for IPAD is much higher than the native application made by Apple?
  5. Adaptable, flexible, scalable platform. While insisting Adobe, Flash on mobile phones remains a goal too far, meanwhile build interfaces for the desktop or the mobile is quite real today on the two platforms.

Is there hope for Flash? Of course, but not in the platform development of applications or in building web sites made of 100% with this plugin. I think that Flash works well for games and animation elements for certain very particular, very far away from this “solution for anything” that Adobe (or Macromedia before being acquired) tried to sell for years.

Javascript scalable applications

Posted By Venu Thomas

Today I was flipping through reading one of the presentations by Nicholas Zakas, specifically the “Scalable Javascript Applications Architecture“.  Although not the first thing I read on the subject, I enjoyed the clarity with which Nicholas explains. I will try to record the impressions taken in case anyone can help.

1) Theory of modules

The theory of modules (as Nicholas calls it) tells us that one way to create an application that is scalable and easy to maintain, this should be composed of modules.

What are modules?

A module (in our terms) is one application that is part of a larger structure. Each has a job and only takes care of it.

JavascriptScalableApplications
(See Picture)
(I enjoyed this picture gives a clear picture of the meaning of magnitude).

Code

Core.register(&quot;hello-world&quot;, function(sandbox){
 // Private Variables
 var strPriv = &quot;Private&quot;;

 //  Public Methods
 return {
   init: function(){
     try{
      sandbox.console(&quot;start the module&quot;);
     } catch(ex) {
      alert(&quot;sandbox not found&quot;);
     }
   },
   destroy: function(){
    // Destructor
   }
 };
});

Here’s an example of a module that recorded with Core.register() we will see later.
Looking at the form we see that the first parameter informs the module name and the second specifies the functionality of the module. This function receives as parameter sandbox (Also see below).
This feature will return an object with at least two methods init() and destroy() that comprise the options available in the module.
init() will be treated as the builder of the module and will be executed when the module is generated. On the other hand destroy() will be treated as the destroyer of the module running when the module is removed.

Sandbox

In software development environment called the Sandbox to test isolated where the experts on running applications. In this case, practically based on the same and that each of the modules used an isolated environment for other modules.
Code

var Sandbox = function() {
   var strPrivate = &quot;Private&quot;;

   return {
     alert: function(str){
       alert(str + strPrivate);
     },
     console: function(str) {
       console.log(str);
     }
 }
};

As we see the Sandbox, this is an element that offers a number of ways in which we interact with the application. For example, could be used to interact with the DOM of the application using a JS framework (or not) could implement a simple version and checked to make Ajax requests or validate forms, …. All this is available from the modules.
This module should only worry about what the Sandbox allowed without worrying about what lies beneath it, thus facilitating the development and functionality of each module.
Example:

// Add method notify () to Sandbox
var Sandbox = function() {
  ....
   notify: function(opt){
     // Checks prior
     // .....
     $(&quot;#notify #title&quot;).text(opt.title);
     $(&quot;#notify #content&quot;).html(opt.content);
   }
  ....
};

// Use the method notify () of the Sandbox from the module.
Core.register(&quot;hello-world&quot;, function(sandbox){
   // Private Variables
   ver ver = &quot;1.0&quot;;

   return {
    init: function(){
      try{
        sandbox.notify({
          title: &quot;Hello World v.&quot; + ver,
          content: 'This is a &lt;strong&gt;Test&lt;/strong&gt;.&lt;br /&gt;To demonstrate the use of modules'
        });
      } catch(ex) {
        alert(&quot;sandbox not found&quot;);
      }
    },
    destroy: function(){
     // Destructor
     }
   };
});

In the example we see that at the start of our module, we call the method notify() from sandbox without worrying about what will make this method.
The method after a series of previous validations, simply add a title and content to an element #notify using jQuery.
Thus, the Sandbox filter made between the module and the framework controlling what this intends to do about our application.

The Core

In the above we have seen a variable Core that seems to be the cornerstone of all this. This is a small script that allows modules to register and associate a new instance of the SandBox to each of them every time you run .

var Core = function(){
   // Private Variable
   var modules = {};

   // Instance Creams
   function createInstance(moduleID){
    var instance = modules[moduleID].creator(new Sandbox(this)),
    name, method;

    if (!debug) {
      for (name in instance){
        method = instance[name];
        if (typeof method == &quot;function&quot;) {
          instance[name] = function(name, method) {
            return function(){
              try { return method.apply(this, arguments);    }
              catch(ex) { log(1, name + &quot;(): &quot; + ex.message);    }
            }
          }
        }
      }
    }
  return instance;
 }

 //  Public method
 return {
   register: function(moduleID, creator) {
     modules[moduleID] = {
       creator: creator,
       instance: null
     };
   },
   start: function(moduleID) {
     modules[moduleID].instance = createInstance(moduleID);
     modules[moduleID].instance.init();
   },
   stop: function(moduleID){
     var data = modules[moduleID];
     if (data.instance) {
       data.instance.destroy();
       data.instance = null;
     }
   },
   startAll: function(){
     for (var moduleID in modules) {
       if (modules.hasOwnProperty(moduleID)) {
         this.start(moduleID);
       }
     }
   },
   stopAll: function() {
     for (var moduleID in modules) {
       if (modules.hasOwnProperty(moduleID)) {
         this.stop(moduleID);
       }
     }
   }
 };
}();

As we see it is a small script (this is a base, can be extended depending on the needs of the project) that allows us to build the modules we want for every application.
Example

Core.register(&quot;....&quot;, function(sandbox){});
Core.register(&quot;....&quot;, function(sandbox){});
Core.register(&quot;....&quot;, function(sandbox){});
Core.register(&quot;....&quot;, function(sandbox){});
...

// Start all modules
Core.startAll();

WordPress 2.9 will have embedded image editing

Posted By Venu Thomas

WordPress_2_9_ImageEdit_160909

One of many to highlight aspects of WordPress is the way we listen to users and incorporate their ideas into the core content management system. Version 2.9, still no launch date, will have a basic image editor, product of a survey on file management features by the development team.

The options currently being tested are: crop, rotate 90 degrees, flip horizontally or vertically and resize the image. May apply to one or more of the commonly used sizes, so it will be easy to choose a specific area for thumbnails. The amendments are supported both at the time of loading, and accessing the multimedia library.

If we consider that any Web service allows us to edit a simple avatar, WordPress is clear that he could not miss a similar choice. The way in which part of the package, requiring no special plugins or server configurations will be useful for all types of bloggers. Novices may perform these actions without having to seek common tools for this. In contrast, more advanced time-saving, and always will be able to install or use more complete aggregate external programs.

Link Via WPEngineer

Page 1 of 1212345...Last »