Arturito.net

Come to The Dark Side, We Have Cookies!

How to Switch Between HTTP and HTTPS in ASP.NET MVC2 And Allow AJAX Requests From Site Master.

without comments

In order to serve the request throught SSL in ASP.NET MVC2 we can simple use Action attribute [RequireHttps]:

		//LoginController
        [RequireHttps]
        public ActionResult Index()
        {
            return View();
        }

Let’s say I served a login form here. Then the user logs in.

		//LoginController
        [RequireHttps]
        [HttpPost]
        public ActionResult Index(LoginModel model)
        {
            if (model != null && model.Username == "arturito")
                 return RedirectToAction("List", "Home");
            else
                return RedirectToAction("Login");
        }

Note that the redirection ( RedirectToAction(“List”, “Home”) ) is taking us to HomeController List action.
However the action List in HomeController is not decorated in [RequireHttps] so it should return to HTTP.

        //HomeController
		public ActionResult List()
        {
            return View();
        }

BUT IT DOESN’T!
You will remain in HTTPS.

Jeff Widmer worked out a great solution and posted it in his article.
In his solution we have BaseController and we are overriding OnAuthorization method

    public class BaseController : Controller
    {
            protected override void OnAuthorization(AuthorizationContext filterContext)
            {

                //the RequireHttpsAttribute set on the Controller Action will handle redirecting to Https.
                // We just need to handle any requests that are already under SSL but should not be.
                if (Request.IsSecureConnection)
                {
                    Boolean requireHttps = false;
                    requireHttps = filterContext.ActionDescriptor.GetCustomAttributes(typeof(RequireHttpsAttribute), false).Count() >= 1;

                    //If this request is under ssl but yet the controller action
                    // does not require it, then redirect to the http version.
                    if (!requireHttps && !filterContext.IsChildAction)
                    {
                        UriBuilder uriBuilder = new UriBuilder(Request.Url);

                        //change the scheme
                        uriBuilder.Scheme = "http";
                        uriBuilder.Port = 80;

                        filterContext.Result = this.Redirect(uriBuilder.Uri.AbsoluteUri);
                    }
                }

                base.OnAuthorization(filterContext);
            }

    }

But there is one problem left!

Let’s say that all pages served through HTTP and HTTPS use the same site master page which contains a link or the form that creates ajax request.
As an example let’s look at this simple action:

		// Home Controller
        [HttpPost]
        public ActionResult Ajax()
        {
            return Content("This is Ajax");
        }

This works great from HTTP page!

How to Switch Between HTTP and HTTPS in ASP.NET MVC2 And Allow AJAX Requests From Site Master.

How to Switch Between HTTP and HTTPS in ASP.NET MVC2 And Allow AJAX Requests From Site Master.

….but when we call the same action from HTTPS page it doesn’t work!
How to Switch Between HTTP and HTTPS in ASP.NET MVC2 And Allow AJAX Requests From Site Master.

Why? This is called crossdomain ajax request, which by default is not allowed for security reasons. There are some methods/libraries/proxies to achieve this but it is not very common yet.

If we decorate it with [RequireHttps] attribute:

		// Home Controller
		[RequireHttps]
        [HttpPost]
        public ActionResult Ajax()
        {
            return Content("This is Ajax");
        }

This action becomes available only if requested from the page served through HTTPS. We can no longer call it from the page served through http.

Well then, let’s allow to perform all ajax request from pages served by both HTTP and HTTPS:

protected override void OnAuthorization(AuthorizationContext filterContext)
            {

                //the RequireHttpsAttribute set on the Controller Action will handle redirecting to Https.
                // We just need to handle any requests that are already under SSL but should not be.
                if (Request.IsSecureConnection)
                {
                    Boolean requireHttps = false;
                    requireHttps = filterContext.ActionDescriptor.GetCustomAttributes(typeof(RequireHttpsAttribute), false).Count() >= 1;

                    // Allow Ajax request from both http and https pages
                    if (Request.IsAjaxRequest())
                    {
                        base.OnAuthorization(filterContext);
                        return;
                    }

                    //If this request is under ssl but yet the controller action
                    // does not require it, then redirect to the http version.
                    if (!requireHttps && !filterContext.IsChildAction)
                    {
                        UriBuilder uriBuilder = new UriBuilder(Request.Url);

                        //change the scheme
                        uriBuilder.Scheme = "http";
                        uriBuilder.Port = 80;

                        filterContext.Result = this.Redirect(uriBuilder.Uri.AbsoluteUri);
                    }
                }

                base.OnAuthorization(filterContext);
            }

    }

Now whether we are on login page (HTTPS) or any other page (HTTP) we can create ajax requests in the site master without decorating ajax actions with additional attributes or messing around
with url scheme in the Views.

Here is a downloadable example:  http://www.mediafire.com/?0d6dn6w489yalgo

GL

Written by arturito

August 5th, 2011 at 4:12 pm

ASP.NET MVC 2 Highlight Selected Menu Item on the Site Master Without Session

with 6 comments

ASP.NET MVC2 makes so many things so easy to program but there are some basic things that are just not there and they should be.
I will be talking about a basic functionality that is a must these days.
I am talking about a menu and highlighting selected menu item.

Let’s see the problem:

I have 3 links and with each click I would like to add apropiate css class to mark my menu item as selected.

ASP.NET MVC 2 Highlight Selected Menu Item on the Site Master Without Session

I have follwed an article on bobby’s blog.
So with this great extension it does work really well:

  public static class HtmlExtensions
    {
        public static MvcHtmlString ActionMenuItem(this HtmlHelper htmlHelper,
        String linkText, String actionName, String controllerName)
        {
            var tag = new TagBuilder("li");
            if (htmlHelper.ViewContext.RequestContext.IsCurrentRoute(
            null, controllerName, actionName) ||
            htmlHelper.ViewContext.RequestContext.IsParentRoute(
            controllerName, actionName))
            {
                tag.AddCssClass("active");
            }
            tag.InnerHtml = htmlHelper.ActionLink(linkText, actionName, controllerName).ToString();

            return MvcHtmlString.Create(tag.ToString());
        }
    }

In the place of menu we stick this:

<%= Html.ActionMenuItem("Home", "Index", "Home") %>

However, there was a one little thing missing in it that I needed to have on my web.

ASP.NET MVC 2 Highlight Selected Menu Item on the Site Master Without Session

In the About link I have a link to Biography . (Biography controller and Index action)
Since the Biography page is a part of About section I would like the “About” menu item to remain highlighted.
The solution above doesn’t work in that case.
So I decided to modify it a bit.

Let’s start from the extension:

    public static class HtmlExtensions
    {
        public static MvcHtmlString ActionMenuItem(this HtmlHelper htmlHelper, String linkText, String actionName, String controllerName)
        {
            var tag = new TagBuilder("li");

            if (htmlHelper.ViewContext.RequestContext.IsCurrentRoute(null, controllerName, actionName) ||
                htmlHelper.ViewContext.RequestContext.IsParentRoute(controllerName, actionName))
            {
                tag.AddCssClass("active"); // stick class active
            }
            else
            {
                tag.AddCssClass("inactive"); // stick class inactive
            }

            tag.InnerHtml = htmlHelper.ActionLink(linkText, actionName, controllerName).ToString();

            return MvcHtmlString.Create(tag.ToString());
        }
    }
 

We also neeed Request Extensions:

    public static class RequestExtensions
    {
        public static bool IsCurrentRoute(this RequestContext context, String areaName)
        {
            return context.IsCurrentRoute(areaName, null, null);
        }

        public static bool IsCurrentRoute(this RequestContext context, String areaName, String controllerName)
        {
            return context.IsCurrentRoute(areaName, controllerName, null);
        }

        public static bool IsCurrentRoute(this RequestContext context, String areaName, String controllerName, params String[] actionNames)
        {
            var routeData = context.RouteData;
            var routeArea = routeData.DataTokens["area"] as String;
            var current = false;

            if (((String.IsNullOrEmpty(routeArea) && String.IsNullOrEmpty(areaName)) || (routeArea == areaName)) &&
                 ((String.IsNullOrEmpty(controllerName)) || (routeData.GetRequiredString("controller") == controllerName)) &&
                 ((actionNames == null) || actionNames.Contains(routeData.GetRequiredString("action"))))
            {
                current = true;
            }

            return current;
        }

        public static bool IsParentRoute(this RequestContext context, String controller, String action)
        {
            var routeData = context.RouteData;
            UrlModel returnUrl = null;
            UrlModel requestUrl = new UrlModel { Action = routeData.GetRequiredString("action"), Controller = routeData.GetRequiredString("controller") };
            UrlModel linkUrl = new UrlModel { Action = action, Controller = controller };

            var urls = UrlMap.GetDictionary();
            urls.TryGetValue(requestUrl, out returnUrl);

            if (returnUrl != null && returnUrl.Equals(linkUrl))
                return true;
            else
                return false; ;
        }
    }
 

And now the important part the UrlMap


    public static class UrlMap
    {
        public static Dictionary GetDictionary()
        {
            Dictionary urls = new Dictionary();
            urls.Add(new UrlModel { Controller = "Biography", Action = "Index" }, new UrlModel { Controller = "About", Action = "Index" });
            urls.Add(new UrlModel { Controller = "Contact", Action = "GetInTouch" }, new UrlModel { Controller = "Contact", Action = "Index" });
            return urls;
        }
    }

Here I specify that if Biography/Index is called please mark it the same as About/Index.

Don’t forget to create UrlModel class

public class UrlModel
    {
        public string Action { get; set; }
        public string Controller { get; set; }

        public override bool Equals(object obj)
        {
            return Equals(obj as UrlModel);
        }
        public bool Equals(UrlModel obj)
        {
            return obj != null && obj.Action == this.Action && obj.Controller == this.Controller;
        }
        public override int GetHashCode()
        {
            return (Action + Controller).GetHashCode();
        }
    }

Now you can stick HtmlHelper with menu in any place on the site.

    <ul id="menu">
        <%= Html.ActionMenuItem("Home", "Index", "Home") %>
        <%= Html.ActionMenuItem("About", "Index", "About") %>
        <%= Html.ActionMenuItem("Contact", "Index", "Contact") %>
    </ul>

and add as amny Url Mapsas you like:

 public static Dictionary GetDictionary()
        {
            Dictionary urls = new Dictionary();
            urls.Add(new UrlModel { Controller = "Biography", Action = "Index" }, new UrlModel { Controller = "About", Action = "Index" });
            urls.Add(new UrlModel { Controller = "Contact", Action = "GetInTouch" }, new UrlModel { Controller = "Contact", Action = "Index" });
            return urls;
        }

Here is how it looks: ASP.NET MVC 2 Highlight Selected Menu Item on the Site Master Without Session


ASP.NET MVC 2 Highlight Selected Menu Item on the Site Master Without Session


ASP.NET MVC 2 Highlight Selected Menu Item on the Site Master Without Session

Here is a complete solution to download: http://www.mediafire.com/?0xabi855suro2rl

GL!

Written by arturito

August 3rd, 2011 at 6:03 pm

iPhone 3G 4.2.1 Wifi Not Working Unable to Join Network Error

with one comment

You need to install or upgrade Flash Player to view this content, install or upgrade by clicking here.

 

 

 

Written by arturito

July 25th, 2011 at 5:43 pm

Posted in iPhone,Uncategorized

iPhone 3G 4.2.1 Accelerometer Not Working

without comments

You need to install or upgrade Flash Player to view this content, install or upgrade by clicking here.

 

Written by arturito

July 25th, 2011 at 5:36 pm

Posted in iPhone

CKeditor A potentially Dangerous Request.Form Value Was Detected From The Client

with 4 comments

This solution does not require to use:
<httpRuntime requestValidationMode=”2.0″/> in web.config
or add attribute [ValidateInput(false)] to your action.

I’m using MVC2 ASP.NET 4.0 and Enitity Framework

Here we go:

1. In CKeditor config.js file


CKEDITOR.editorConfig = function (config) {
config.language = 'en',
ignoreEmptyParagraph = true;};

2. In your aspx page  include:

<script type="text/javascript" src="<%= Url.Content("~/Content/scripts/wysiwyg/ckeditor.js")%>"></script>

3. Now let’s say that your View is strongly typed.

<% using (Html.BeginForm()) {%>
   <%: Html.ValidationSummary(true) %>
   <fieldset>
   <legend>Fields</legend>
            <div>
                <%: Html.TextBoxFor(model => model.Title) %>
                <%: Html.ValidationMessageFor(model => model.Title) %>
            </div>
            <div>
                <%: Html.LabelFor(model => model.Descripcion) %>
            </div>
            <div>
                <%-- Instead of
                <%: Html.TextBoxFor(model => model.Description) %>
                 use: --%>
                <textarea id="Description" name="Description" rows="2">
                     <%= Model.Description %>
                </textarea>
                <%: Html.ValidationMessageFor(model => model.Description) %>
            </div>
            <p>
                <input type="submit" value="Save" />
           </p>
   </fieldset>
 <% } %>

<script type="text/javascript">
    CKEDITOR.replace('Description', { toolbar: '1', htmlEncodeOutput: true});
</script>

4. Your action will look this:

[HttpPost]
public ActionResult Create(MyModel model)        {

if (ModelState.IsValid)            {
     // use System.Net.WebUtility.HtmlDecode() to store unencoded HTML
     model.Description =  System.Net.WebUtility.HtmlDecode(model.Description);
     var entity = EntityAssemblerService.MyModelToEntity(model);
     var result = _repository.Add(entity);
     _repository.Save();
    return View(model);
}
else  {
return View(model);
}
}

Good Luck

Written by arturito

May 26th, 2011 at 1:07 pm

Local and Remote PHP Debuging in NetBeans with Xdebug on Google Chrome (just like in Visual Studio)

with 8 comments

Have you ever wonder how to debug your php projects just like it is done in Visual Studio?Well it is not that simple as in Visual Studio.NET where you just click “Debug” and all is set for you. You need to install and configure couple of things but that’s about it.
In this tutorial we are going to set xdebug for php on Ubuntu server and we are going to use Google Chrome as a browser in our debugging process.

Let’s setup server. Log in to your ubuntu box.
1. Install xdebug for php

sudo aptitude install php5-xdebug
sudo /etc/init.d/apache2 restart

2. Check installation

php -v

arturito@hokage:~$ php -v
PHP 5.3.3-1ubuntu9.3 with Suhosin-Patch (cli) (built: Jan 12 2011 16:08:14)Copyright (c) 1997-2009 The PHP GroupZend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies    with Xdebug v2.1.0, Copyright (c) 2002-2010, by Derick Rethans

3.  Edit php.ini

sudo nano /etc/php5/apache2/php.ini

4. Stick these lines in:

zend_extension="/usr/lib/php5/20090626+lfs/xdebug.so"
xdebug.remote_enable=on
xdebug.remote_host=localhost

5. Install Google Chrome xdebug extension:

https://chrome.google.com/webstore/detail/eadndfjplgieldjbigjakmdgkmoaaaoc

6. In Chrome go to Tools>Extensions

7. Click on Options and add domains you want to be able to debug

8. Open NetBeans and go to Tools > Options > PHP

9. Now create new project as a test  and set the breakpoint.

10. Hit Ctrl + F5

Your browser will hang.

and you will be able to step through the code

Additional:

If your webserver is not installed on your machine but it is on the separate one you should set xdebug.remote_host to the IP of your development machine.
For example I run ubuntu with apache in virtual box so I set
xdebug.remote_host=192.168.1.5
where 192.168.1.5 is the IP of my Windows host OS where I have NetBeans installed.

Written by arturito

May 21st, 2011 at 1:12 pm

Posted in PHP

Apple TV 2G Untethered Jailbreak And XBMC Installation iOS 4.3 working

with 31 comments


This tutorial is out of date
. It worked for people who had Apple TV 2 with 4.1.1 and accidentally updated to 4.2.1.

Please follow these instructions instead:

http://arturito.net/2011/04/09/apple-tv-2g-untethered-jailbreak-and-xbmc-installation-ios-4-3-with-sn0wbreeze/

 

 

—————————————————————————————————————————————————————————

 

My friend accidently updated his Apple TV 2G to version 4.2.1 (2100) iOS 4.3 which removed jailbreak and XBMC I put for him before with version 4.1.1.

I wrote this tuorial: http://arturito.net/2011/04/09/apple-tv-2g-untethered-jailbreak-and-xbmc-installation-ios-4-3-with-sn0wbreeze/
which deals with iOS 4.3 and installs XBMC. All installs well but…. we all got audio device error and could not play MKV files.

I turned to Seas0nPass and PwngeTool but it had the same problem.

But thanks to users comments especially Fluxx and Czechmarty I managed to fix it.

I still don’t know how I managed to restore to previous version without SHSH blobs ………but I did. I assume that if Apple TV firmware version shows 4.2.1 (2100) the iOS must be 4.3.

I asked question on XBMC forums in order to confirm that.
http://arturito.net/2011/04/12/apple-tv-2g-untethered-jailbreak-and-xbmc-installation-ios-4-3-working/

All replies I got confirmed that 4.2.1 (2100) for ATV2 is iOS 4.3.1

Well let’s start:

Download:

1. iTunes 10.2.1 – might work with newer version but this is waht I tried and worked for me.
http://www.oldapps.com/itunes.php?old_itunes=71

2. Apple TV Fimrware 41.1 (iOS 4.2.1)
http://appldnld.apple.com/AppleTV/061-9978.20101214.gmabr/AppleTV2,1_4.2.1_8C154_Restore.ipsw

3. Uninstall your current version of iTunes and install version 10.2.1

4. Fire iTunes, connect Apple TV with USB cable only.  Let Windows install all drivers.

 

5. Once you see Apple TV in iTunes  hold Shift and click Restore.

6. Select AppleTV2,1_4.2.1_8C154_Restore.ipsw and wait until it completes

7. Go to this post

http://arturito.net/2011/02/14/apple-tv-2-untethered-jailbreak-on-windows-and-xbmc-media-centre-installation/
and jump to point 1 (Running GreenPois0n)

Written by arturito

April 12th, 2011 at 1:00 pm

Posted in Apple TV 2

Apple TV 2G Untethered Jailbreak And XBMC Installation iOS 4.3 With Sn0wBreeze

with 65 comments

UPDATE 07.03.2012

This post is out-of date:
Please check:

http://arturito.net/2012/03/07/how-to-jailbreak-apple-tv-2g-4-4-4-and-install-xbmc-untethered/

UPDATE: 10.01.2012

As you can see this post is quite old now so this method might not work for you as Apple keeps updating their Apple TV 2G.
Please find out first which version of Apple TV 2G you have. To get this info check this one:

http://arturito.net/2011/11/30/how-to-find-firmware-version-of-apple-tv-2g-software-and-system-version/ 

If your System Version is greater than 4.3 instructions in  this tutorial won’t work for you. Shortly I will be posting an update.
If your System Version is 4.3 you can go ahead:

In one of my previous post I explained how to jailbreak Apple TV 2G and install XBMC on it.

http://arturito.net/2011/02/14/apple-tv-2-untethered-jailbreak-on-windows-and-xbmc-media-centre-installation/

This has been some time ago and it worked for Apple TV2G version 4.1.1 and below. I used GreenP0ison RC6.
Since then Apple has release version 4.2.1 (iOS 4.3) and GreenP0ison can’t do the jailbreak of this version.  I’ve heard that Sn0w Breeze can jailbreak the latest (4.3) Apple TV 2G software version and I have decided to try it:

What we need is:

1. iTunes installed
2. iREB-r4
3. sn0wbreeze-v2.5.1
4. AppleTV2,1_4.3_8F202_Restore.ipsw

You can google these or simply download zip file with all files apart from iTunes:
http://www.megaupload.com/?d=96Y7FUVR

1. Unpack it all and run iREB-r4. Connect only USB cable.

2. Click on Apple TV2

3. Once in DFU mode you will get this:

4.  Ok so before we go to iTunes and do Restore let’s prepare firmware. Let’s launch Sn0wBreeze :

5. Clicking in the link to download IPSWs didn’t work for me so that’s why we got firmware downloaded before. Click on Browse and point to the firmware file: AppleTV2,1_4.3_8F202_Restore.ipsw

6. Hit Continue and be patient. It might take sometime

7.  In your desktop there should be file called: sn0wbreeze_Apple TV 2-4.3.ipsw. Hit OK.

8. You should get this message:

9. Now got your iTunes and in the right sidebar select Apple TV

10. Hold SHIFT button and press Restore
11. Select sn0wbreeze_Apple TV 2-4.3.ipsw located on your Desktop and wait until the process is complete.
12. Now when you connect Apple TV2G to your TV you should get NitoTV . To install XBMC go to

http://arturito.net/2011/02/14/apple-tv-2-untethered-jailbreak-on-windows-and-xbmc-media-centre-installation/

and jump to step 4.
Before leaving any questions in comments please post your System and Software Version. You can get that information by following this guide:

http://arturito.net/2011/11/30/how-to-find-firmware-version-of-apple-tv-2g-software-and-system-version/ 

Good Luck! :)

Written by guru

April 9th, 2011 at 7:48 pm

Posted in Apple TV 2

How to fix XBMC that quits on Apple TV 2G and disable updates

with 3 comments

If you have NitoTV installed there is a very simple solution:

1. NitoTV>Settings>Update NitoTV

2. NitoTV>Settings>Reboot

3. NitoTV>Install Software> updatesBeGone

4. NitoTV>Settings>Reboot

Silly message will go away :)

Written by guru

March 21st, 2011 at 10:38 pm

Posted in Apple TV 2

How to change time zone on Apple TV 2G

with 5 comments

On the jailbreaked Apple TV 2 login as root using ssh.

find / -name localtime

it should come up with

/private/var/db/timezone/localtime

now got to this directory


cd /private/var/db/timezone/

remove link


rm localtime

and create new one for example in my case Madrid.

ln -s /usr/share/zoneinfo/Europe/Madrid localtime

to get your time zone

check what’s available in

cd /usr/share/zoneinfo/

Reboot and that should be it.

Written by guru

March 21st, 2011 at 10:11 pm

Posted in Apple TV 2