Archive for the ‘Microsoft’ Category

Automatic control in ASP.NET MVC

Thursday, September 2nd, 2010

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

Sunday, August 22nd, 2010

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!! ;-)

More javascript on the web: Microsoft Ajax CDN

Thursday, September 17th, 2009

ASP_Ajax

A few days ago said the possibility of using the infrastructure of Google to host JavaScript libraries for our applications. Well, now that Microsoft has launched a similar service, Microsoft Ajax CDN , A content distribution network where we can download the runtime libraries of scripts that we use in our applications.

Or in other words, we can make free use of these libraries, without limitation of bandwidth and regardless of whether or not for commercial purposes. Just be referenced from your code:

?View Code ASPNET
<script src="http://ajax.microsoft.com/ajax/jquery-1.3.2.min.js" 
        type="text/javascript"></script>

The main advantage of this method is the speed with which these files will be served, since it uses the infrastructure of the Redmond giant, while the cache is shared with other websites that are also used. It also provides the ability to use scripting to Web sites that do not have permission to upload files (such as platform blogger)

Unlike the Google service, since this CRC only time we can find the libraries that are officially part of the Microsoft development platform, such as those typical of ASP.NET Ajax, jQuery and those plugins that are added. The address http://www.asp.net/ajax/cdn/ can see the complete list of libraries, with their corresponding addresses download.

Additionally, Scott Guthrie said in his blog that the new control ScriptManager that come with ASP.NET 4.0 includes a property called EnableCdn which will activate the download of the Ajax libraries and all those necessary for the operation of controls, directly from their servers.

AjaxCDN_EnableCdn_160909

The drawbacks, as the same as the Google service: If you do not have network connectivity in development time, we really have it raw.

More information: http://www.asp.net/ajax/cdn/

Linq to NHibernate, Version 1.0

Thursday, September 10th, 2009

A few weeks ago, Oren Eini (Ayende Raihan or, as is often referred to) communicated the release of version 1.0 of the Linq provider for NHibernate, a feature highly demanded by users since the advent of integrated query language. NET.

Although it will be included as part of NHibernate product in future versions, have decided to release the current release of the supplier as separate package so you can start to be used from now. It is being tested in many applications in production for several years, and apparently the performance is just right.

And how can help the supplier, if you’re user of NHibernate? The following example from Caffeinated Coder demonstrates how to query database can be simplified and made more readable using Linq and also benefit from strong typing, intellisense and compile-time checks:

Using NHibernate API:

public IList<Call> GetCallsByDate(DateTime beginDate, int interpreterId)
{
    ICriteria criteria = Session.CreateCriteria(typeof(Call))
        .CreateAlias("Customer", "Customer")
        .Add(Restrictions.Gt("StartTime", beginDate))
        .Add(
            Restrictions.Or(
                Restrictions.Lt("EndTime", DateTime.Now), Restrictions.IsNull("EndTime"))
            )
        .Add(Restrictions.Eq("Interpreter.Id", interpreterId))
        .AddOrder(Order.Desc("StartTime"))
        .AddOrder(Order.Desc("Customer.Name"));
        return criteria.List<Call>() as List<Call>;
}

Using Linq:

public IList<Call> GetCallsByDateWithLinq(DateTime beginDate, int interpreterId)
{
    var query = from call in Session.Linq<Call>()
        where call.StartTime > beginDate
            && (call.EndTime == null || call.EndTime < DateTime.Now )
            && call.Interpreter.Id == interpreterId
        orderby call.StartTime descending, call.Customer.Name
        select call;

    return query.ToList();
}

You can download both binaries and source code from the SourceForge project page.

Code in C# to create a backup of a database in SQL server and restore it

Wednesday, August 19th, 2009

Here they left a code in C # very useful when making your applications with databases in SQL server can support the database and restore it.

Support code for a button:

private void btnBackUp_Click(object sender, EventArgs e)
{
    bool bBackUpStatus = true;

    Cursor.Current = Cursors.WaitCursor; 

     if (Directory.Exists(@"c:\SQLBackup"))
        {
            if (File.Exists(@"c:\SQLBackup\wcBackUp1.bak"))
            {
                if (MessageBox.Show(@"Do you want to replace it?", "Back", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    File.Delete(@"c:\SQLBackup\wcBackUp1.bak");
                }
                else
                    bBackUpStatus = false;
            }
        }
        else
            Directory.CreateDirectory(@"c:\SQLBackup");

        if (bFileStatus)
        {
            //Connect to DB
            SqlConnection connect;
            string con = "Data Source = localhost; Initial Catalog=dbWiseCodes ;Integrated Security = True;";
            connect = new SqlConnection(con);
            connect.Open();
            //----------------------------------------------------------------------------------------------------

            //Execute SQL---------------
            SqlCommand command;
            command = new SqlCommand(@"backup database dbWiseCodes to disk ='c:\SQLBackup\wcBackUp1.bak' with init,stats=10", connect);
            command.ExecuteNonQuery();
            //-------------------------------------------------------------------------------------------------------------------------------

            connect.Close();

            MessageBox.Show("The support of the database was successfully performed", "Back", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
}

Code for a button to restore:


private void btnRestore_Click(object sender, EventArgs e)
{

    Cursor.Current = Cursors.WaitCursor;

    try
    {
        if (File.Exists(@"c:\SQLBackup\wcBackUp1.bak"))
        {
            if (MessageBox.Show("Are you sure you restore?", "Back", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                //Connect SQL-----------
                SqlConnection connect;
                string con = "Data Source = localhost; Initial Catalog=master ;Integrated Security = True;";
                connect = new SqlConnection(con);
                connect.Open();
                //-----------------------------------------------------------------------------------------

                //Excute SQL----------------
                SqlCommand command;
          command = new SqlCommand("use master", connect);
            command.ExecuteNonQuery();
                command = new SqlCommand(@"restore database dbWiseCodes01 from disk = 'c:\SQLBackup\wcBackUp1.bak'", connect);
                command.ExecuteNonQuery();
                //--------------------------------------------------------------------------------------------------------
                connect.Close();

                MessageBox.Show("Has been restored database", "Restoration", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        else
            MessageBox.Show(@"Do not make any endorsement above (or is not in the correct path)", "Restoration", MessageBoxButtons.OK, MessageBoxIcon.Information);

    }
    catch (Exception exp)
    {
        MessageBox.Show(exp.Message);
    }

}

The promotional video for Office 2010

Monday, July 13th, 2009

The series of promotional videos for Office 2010 trying to launch the software as the plot of a film of action, are fun.

There’s a part where you see the tomb of Clippy, the Office tool from which it is often mocked, he has been absent in recent versions of Office software.

It also includes an interview to find the missing sources. However, the woman tells him in captivity are among “Arial” and “Wingdings”


Video: Office 2010: The Movie [02:15 min]

Microsoft has said it will have a preview of the techniques of software this month. For more information visit Office 2010: The Movie Web site

Microsoft Silverlight 3.0 comes out

Friday, July 10th, 2009

Today released the official version of Silverlight 3, the solution that Microsoft intends to steal the Adobe Flash site to offer to them a richer navigation experience with the greatest support to the new multimedia technologies.

Silverlight 3 introduces over 50 new features, including support 3D accelerated GPU, video H.264 and support outside of the browser which will allow developers to create applications, like Adobe AIR.

Is already available here for Windows, OS X and … oh … no, wait … that’s all.

Link: via Microsoft

LINQ to SQL changes in VS 2010 & .NET 4.0

Wednesday, June 17th, 2009

For some time did not read anything about LINQ To SQL, and the truth is that I had raised was going with this extension of LINQ in Visual Studio 2010 and. NET 4.0 … well, the fact is that work has continued in LINQ To SQL and brings a lot of developments. NET 4.0. You can access all the news in this link.

via Damieng

Microsoft Web Platform Installer & Windows Web Application Gallery !

Monday, June 15th, 2009

Among the initiatives that Microsoft has to facilitate the design and creation of Web applications, this week we find two important components focused on that idea: the Web Platform Installer and the Windows Application Web Gallery. In the case of the Web Platform Installer, we find that Microsoft continues to evolve this utility you can install at a stroke a lot of ingredients we might need to build our web applications. In the Windows Application Web Gallery, we have a resource center where people can find applications and free technology. NET and PHP available for download. But let us see in detail each of these applications.

Web Platform Installer


As I said, Microsoft has just released the first beta of version 2.0 of the Web Platform Installer, which allows us to form a unified set of components that make up the stack of a typical web platform, and all this in just 1 MB. Among the components included (and whose installation is fully customizable), we have:

* Internet Information Services (IIS) 5.1 on Windows XP SP3.
* IIS 6.0 on Windows Server 2003 SP2.
* IIS 7.0 on Windows Vista SP1 and Windows Server 2008.
* SQL Server 2008 Express.
* .NET Framework 3.5 SP1.
* Visual Web Developer 2008 Express Edition.
* IIS Extensions including:
o IIS 7 Media Services 3.0.
o IIS7 Administration Pack.
o Database Manager for IIS7.
o WebDav 7.5.
o FTP 7.5.
o FastCGI for PHP support on IIS6.
o URL Rewrite.
o IIS 7 Application Routing.
o Web Deployment Tool for IIS.S.
* ASP.NET and features such as ASP.NET MVC.
* Silverlight Tools for Visual Studio.
* The Community Version of PHP v5.2.9.

Windows Web Application Gallery


In this case we have a portfolio of applications and ASP.NET PHP fully tested as DotNetNuke, DasBlog, Graffiti, Drupal, WordPress, phpBB (incidentally, another proof of the shift to open source that Microsoft is doing) for lists download and install.

.NET: Checking whether an Internet connection is available

Wednesday, May 20th, 2009

The method using ping checks whether there is an internet connection or not?

In C#.NET

The following namespace is required:

using System.Net.NetworkInformation;
/// <Summary>
/// Checks whether an Internet connection is available.
/// </Summary>
/// <Returns>
/// True / false
/// </Returns>
/// Site: WiseCodes.Com

public static bool wcCheckInternetConnectionStatus()
{
 Ping pingSender = new Ping();

 try
 {
PingReply pReply = pingSender.Send("www.microsoft.com", 100);

 return pReply.Status == IPStatus.Success;
 }
 catch
 {
 return false;
 }
}

Link: System.Net.NetworkInformation Namespace (Via MSDN)

Happy Programming!! ;-)