Monday, 10 November 2014

2# Twisted lasers - Reflecting laser beam

For the last couple of evenings (after daily job as developer) I was working on Twisted lasers game, exactly on laser reflection. As a player you have ability to rotate mirror and depends on mirror rotation laser beam will be reflected. 
For laser beam I used line renderer. 
To find out if an object is placed on laser beam I used Physics.LineCast.
If object is mirror we want to instantiate new line renderer where initial position is hit point and destination position depends on laser beam origin direction. 



I know the code is a bit dirty, not optimized and refactored, but this is just initial mock up and hopefully find better solution.

LateUpdate function:

if(myhit.transform.tag == "Mirror")
   {
    // depends on X rotation of mirror object, manipulate laser beam

    this.lineRenderer.SetPosition(1, myhit.transform.position);
    myhit.transform.tag = "OnLaser";
    GameObject lr = Instantiate(this.gameObject, originBeam, transform.rotation) as GameObject;

    Vector3 reflectVector = CalculateReflectVector(myhit.transform, originBeam);

    lr.GetComponent<linerenderer>().SetPosition(0, myhit.transform.position);
    lr.GetComponent<linerenderer>().SetPosition(1, reflectVector);

    lr.GetComponent<laserbeamtriggered>().originBeam = myhit.transform.position;
    lr.GetComponent<laserbeamtriggered>().directionBeam = reflectVector;

    laserBeamAdded = true;

   }

public Vector3 CalculateReflectVector(Transform hitBeam, Vector3 originBeam)
 {
  // Calculate second line renderer Vector 3
  if (originBeam.y < hitBeam.position.y) {
    Debug.Log ("Laser under");
    Debug.Log (hitBeam.transform.eulerAngles.z);
    // origin laser under target
    if ((int)hitBeam.transform.eulerAngles.z == 45) {
      return new Vector3 (hitBeam.transform.position.x + laserOffset, hitBeam.transform.position.y, hitBeam.transform.position.z);
    } else {
      return new Vector3 (hitBeam.transform.position.x - laserOffset, hitBeam.transform.position.y, hitBeam.transform.position.z);
    }
  } else if (originBeam.y > hitBeam.position.y) {
    Debug.Log ("Laser top");
    // origin laser at the top of the target
    if ((int)hitBeam.transform.eulerAngles.z == 45) {
      return new Vector3 (hitBeam.transform.position.x - laserOffset, hitBeam.transform.position.y, hitBeam.transform.position.z);
    } else {
      return new Vector3 (hitBeam.transform.position.x + laserOffset, hitBeam.transform.position.y, hitBeam.transform.position.z);
    }
  } else if (originBeam.x < hitBeam.position.x) {
    // origin laser at right
    if ((int)hitBeam.transform.eulerAngles.z == 45) {
     return new Vector3 (hitBeam.transform.position.x, hitBeam.transform.position.y + laserOffset, hitBeam.transform.position.z);
    } else {
    return new Vector3 (hitBeam.transform.position.x, hitBeam.transform.position.y - laserOffset, hitBeam.transform.position.z);
    }
  }

  else if (originBeam.x > hitBeam.position.x) {
   // origin laser at right
   if ((int)hitBeam.transform.eulerAngles.z == 45) {
    return new Vector3 (hitBeam.transform.position.x, hitBeam.transform.position.y - laserOffset, hitBeam.transform.position.z);
   } else {
    return new Vector3 (hitBeam.transform.position.x, hitBeam.transform.position.y + laserOffset, hitBeam.transform.position.z);
   }
  }
  
  
  // if fails
  return originBeam;
 }

Tuesday, 28 October 2014

Using async and await for Asynchronous calls in C# and VB

We are going to user asynchronous call to get length of web that we requested.

Download : C# or VB

Create new WPF project.



Add textbox and button.


Rename button to runAsyncButton and textbox to resultsWindow.
You can either do that  by adding x:Name property for each element, or click an element and get the properties and change name.
<Button x:Name="runAsyncButton" ... />
<TextBox x:Name="resultsWindow" .../>

Double click on button and click method is generated.

Xaml code for grid should looks similar:



Add this to your click method :
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
   resultsWindow.Clear();
   resultsWindow.Text += "Asynchronous call started";
   runAsyncButton.IsEnabled = false;
   runAsyncButton.Content = "Running...";
   await SumPageSizesAsync();
   runAsyncButton.IsEnabled = true;

   runAsyncButton.Content = "Run";
   resultsWindow.Text += "\n Asynchronous call finished";
}


As you can see method needs to have async keyword to perform as an asynchronous call.
Await keyword on SumPageSizesAsync method works in pair with async and tells method to wait before continuing if method is still being executed. 

We have to write SumPageSizesAsync method:


private async Task SumPageSizesAsync()
{
   List<string> urlList = SetUpURLList();

   foreach(var url in urlList)
   {
      // return contents as a byte array
      Byte[] urlContent = await GetURLContentsAsync(url);

      DisplayResults(url, urlContent);
   }

}


To populate list with url addresses:



private List<string> SetUpURLList()
{
   List<string> urls = new List<string>() { 

   "http://msdn.microsoft.com/library/windows/apps/br211380.aspx",
   "http://msdn.microsoft.com",
   "http://msdn.microsoft.com/en-us/library/hh290136.aspx"
};

return urls;
}


Now we have to write the core method - GetURLContentsAsync.


private async Task<byte> GetURLContentsAsync(string url)
{
   MemoryStream content = new MemoryStream();

   HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);

   // Send request and wait for response

   Task<webresponse> responseTask = webReq.GetResponseAsync();

   using (WebResponse response = await responseTask)
   {
      using (Stream responseStream = response.GetResponseStream())
      {
         await responseStream.CopyToAsync(content);
      }
   }
   return content.ToArray();
}


Final method is DisplayResults.

private void DisplayResults(string url, Byte[] content)
{    
   var bytes = content.Length;  
   resultsWindow.Text += string.Format("\n {0} {1}", url, bytes); 
} 


Run the program.




Saturday, 18 October 2014

Unity 3d frozes when loading or closing project

Occasionally I encounter issue which prevent me from closing Unity 3d or loading new project. After googling I found out that there is a process abd.exe running in the background that cause Unity to behave oddly. If your project is set up to Android project you are likely to have this process running.
More info about adb process can be found here : http://www.file.net/process/adb.exe.html

Simply saying adb is one of the Android SDK processes.

Shut all adb process from task manager panel and that should fix the problem.


Thursday, 9 October 2014

2 Simple rules to improve performance in Unity 3d when writing Scripts

So you created beautiful looking game that run 90 fps on your machine and then your exported it to mobile device and your excitement disappeared once you opened it -slow, lag, unplayable. If you haven't experienced that either you are genius talented video game designer or your game is not very resource demanding. I have been in this situation and my solution was to carefully start optimizing game so it will run much smoother and users that still have few years old devices(like me) can enjoy the game. This is not holy grail unity tutorial, but it definitely helps me in many occasions.

It is very important to think about performance in an early stage when creating video game/app using unity game engine. Some bad design can cause headache in the future, especially when your game gets bigger and more resource demanding.

Of course writing optimised script is not the only way to improve performance in unity games. Another way is to reuse materials, avoid using transparent shader on mobile devices etc.

Due to my experience I found out that those 2 very simple tricks works well.

1. Cache an object when using it often (especially in Update function).


Example.

   void Start ()

   {

       double totalA = 0;

       double totalB = 0;

       int counter = 1000000;

       // Caching our transform

       Transform tr = GetComponent();

       var currentTime = DateTime.Now;

       // First test with cache

       for (int i = 0; i < counter;i++)

       {

           Vector3 vec = tr.position;

           vec.x = 10;

           tr.position = vec;

       }

       totalA = (DateTime.Now - currentTime).TotalMilliseconds;

       // Second test with no cache

       currentTime = DateTime.Now;

       for (int k = 0; k < counter; k++)

       {

           Vector3 vec = transform.position;

           vec.x = 10;

           transform.position = vec;

       }  

       totalB = (DateTime.Now - currentTime).TotalMilliseconds;

       print (totalA);

       print (totalB);

   }

1st loop will perform faster.

2. Use static variables rather than public.


 Static variable belongs to an class rather than object, therefore it is faster to access. Careful as if the same class is being used for the same prefabs(eg enemy), if you kill one enemy, all of them will be dead.  If that approach at least helped you to get extra fps let me know!

Tuesday, 9 September 2014

Implementing API in ASP.NET MVC application

Full project can be downloaded here.

We are going to create simple API that will return either collection of movies or single movie in Json format by default, however depends on browser results might be displayed in XML format.
I focused only on GET method in this tutorial.
 
1. Create new MVC application in Visual Studio.
2. In models create interface IMoviesRepository, class Movie and MoviesRepository

public interface IMoviesRepository
    {
        IQueryable<Movie> GetAll();
        Movie GetById(int id);
        Movie Add(Movie movie);
        bool Edit(Movie movie);
        bool Remove(Guid? id);
    }

public class Movie
    {
        public int movieId { get; set; }
        public string name { get; set; }
        public string releaseYear { get; set; }
    }

public class MovieRepository : IMoviesRepository
    {
        private List<Movie> _listOfMovies = new List<Movie>();

        public MovieRepository()
        {
            _listOfMovies.Add(new Movie { 
                movieId = 1,
                name = "Keyboard massacre", 
                releaseYear = "1999" });

            _listOfMovies.Add(new Movie { 
                movieId = 2, 
                name = "Keyboard massacre 2",
                releaseYear = "2000" });

            _listOfMovies.Add(new Movie { 
                movieId = 3,
                name = "Keyboard massacre 3 ",
                releaseYear = "2001" });
        }

        public IQueryable<Movie> GetAll()
        {
            return _listOfMovies.AsQueryable();
        }

        public Movie GetById(int id)
        {
            return _listOfMovies.Find(m => m.movieId == id);
        }

        public Movie Add(Movie movie)
        {
            throw new NotImplementedException();
        }

        public bool Edit(Movie movie)
        {
            throw new NotImplementedException();
        }

        public bool Remove(Guid? id)
        {
            throw new NotImplementedException();
        }
    }
Create interface first and then MovieRepository that will inherit IMoviesRepository and simply right click on class name and apply Implement Interface.



3. Add new folder to your main project WebApiControllers and add Api Controller. Call itMoviesController.cs.



Add this to your main controller class.


MovieRepository movieRepository;

        public MoviesController()
        {
            this.movieRepository = new MovieRepository();
        } 


Calling default constructor will make sure that all repositories are in place. It is good practice to call all services that will be required for controller - we are making sure that our application is loose coupled. If you are familiar with dependency injection this is quite common concept.

As I mentioned I will focus only on GET method, so replace both GET methods with custom code.

You controller should like this :


public class MoviesController : ApiController
    {
        MovieRepository movieRepository;

        public MoviesController()
        {
            this.movieRepository = new MovieRepository();
        }

        // GET api/movies
        public IQueryable<Movie> Get()
        {
            return movieRepository.GetAll();
        }

        // GET api/movies/5
        public Movie Get(int id)
        {
            return movieRepository.GetById(id);
        }

        // POST api/movies
        public void Post([FromBody]string value)
        {
        }

        // PUT api/movies/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/movies/5
        public void Delete(int id)
        {
        }
    }

4. Run your application now and call localhost:YourPortNumber/api/movies

In my case: http://localhost:53909/api/movies

You should get this results in Chrome:


If you run it in IE you will be asked to save file. By opening it in notepad you get JSON results

[{"movieId":1,"name":"Keyboard massacre","releaseYear":"1999"},{"movieId":2,"name":"Keyboard massacre 2","releaseYear":"2000"},{"movieId":3,"name":"Keyboard massacre 3 ","releaseYear":"2001"}]

5. We could improve GetById method. If movie can not be found we want to return HttpResponseException.

// GET api/movies/5
        public Movie Get(int id)
        {
            var movie = movieRepository.GetById(id);
            if (movie == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return movie;
        }

6. There are few rules that you have to be aware. You have to name your GET method starting with Get. So For instance GetCollectionOfMovies. By calling http://localhost:53909/api/movies you get the same results as if your method would call just Get. There is a way to force user to type full name of your method http://localhost:53909/api/GetCollectionOfMovies and this will require changing routing in Global.asax file. I will mention that in one of next tutorials.

Sunday, 7 September 2014

1# Twisted lasers - Puzzle game - First look

Recently I started working on a puzzle game which main objective is to move laser beam source to designated location by using mirrors that will change the direction of laser. Very easy concept, however there will be more obstacles and more tools to use apart from mirrors.

So far I was able to create a custom grid that can be very easily modified. For instance if game requires 8x8 or 6x6 grid this can be changed by providing correct input for Building Grid script.


// Constant offset value
  xOffSet = (float)10/gridColumns;
  yOffset = (float)10/gridRows;

  firstTile = CreateSingleGridTile(firstPoint, secondPoint, thirdPoint, fourthPoint,  0, 0);
  firstTile.renderer.enabled = false;

  GameObject grid = new GameObject();

  // This method can be used from other Scripts to build extra grids, inventory systems etc
  BuildGrid (ref grid, gridRows, gridColumns, arrayOfTiles, "SingleTile", xOffSet, yOffset, zOffset, firstTile,  firstPoint);

  // Set main beam position

  var positionOfBeamToAppear = arrayOfTiles[xMainBeam, yMainBeam];

  mainLaserBeam.transform.position = new Vector3(positionOfBeamToAppear.transform.position.x -xOffSet/2, positionOfBeamToAppear.transform.position.y - yOffset/2, positionOfBeamToAppear.transform.position.z +zOffset);

  var positionOfLaserTargetToAppear = arrayOfTiles[xLaserTarget, yLaserTarget];
  
  laserTarget.transform.position = new Vector3(positionOfLaserTargetToAppear.transform.position.x -xOffSet/2, positionOfLaserTargetToAppear.transform.position.y - yOffset/2, positionOfLaserTargetToAppear.transform.position.z +zOffset);

 }

 public void BuildGrid (ref GameObject grid,
                        int gridRows,
                        int gridColumns,
                        GameObject[,] arrayOfTiles,
                        string tagName,
                        float xOffSet,
                        float yOffset,
                        float zOffset,
                        GameObject firstTile,
                        Vector3 initialBuildPosition
                        )
 {

  bool nextRow = false;
  for (int row = 0; row < gridRows; row++) {
   for (int column = 0; column < gridColumns; column++) {
    if (row == 0 && column == 0) {
     grid = Instantiate (firstTile, new Vector3 (initialBuildPosition.x, initialBuildPosition.y, initialBuildPosition.z - zOffset), Quaternion.identity) as GameObject;
     arrayOfTiles [row, column] = grid;
     grid.renderer.enabled = true;
    }
    else {
     if (!nextRow) {
      grid = Instantiate (arrayOfTiles [row, column - 1], new Vector3 (arrayOfTiles [row, column - 1].transform.position.x + xOffSet, initialBuildPosition.y, initialBuildPosition.z - zOffset), Quaternion.identity) as GameObject;
     }
     else {
      grid = Instantiate (arrayOfTiles [row - 1, column], new Vector3 (arrayOfTiles [row - 1, column].transform.position.x, arrayOfTiles [row - 1, column].transform.position.y - yOffset, arrayOfTiles [row - 1, column].transform.position.z), Quaternion.identity) as GameObject;
     }
     arrayOfTiles [row, column] = grid;
     grid.renderer.enabled = true;
    }
    // Based on name we can easily find the position of tile
    grid.name = string.Format ("{0}_{1}:{2}", tagName, row, column);
    grid.tag = tagName;
    grid.collider.enabled =true;
   }
   nextRow = true;
  }
 }

 // Update is called once per frame
 void Update () {

 }

 public GameObject CreateSingleGridTile(Vector3 firstPoint,Vector3 secondPoint,Vector3 thirdPoint,Vector3 fourthPoint, int xArrayIndex, int yArrayIndex )
 {
  GameObject gridTile = new GameObject(string.Format("Reference_{0}:{1}", xArrayIndex,yArrayIndex) );

  MeshFilter meshFilter = (MeshFilter)gridTile.AddComponent(typeof(MeshFilter));

  meshFilter.mesh = CreateMesh(firstPoint,secondPoint, thirdPoint, fourthPoint);

  gridTile.AddComponent();

  MeshRenderer renderer = gridTile.AddComponent(typeof(MeshRenderer)) as MeshRenderer;
  renderer.material.shader = Shader.Find ("Mobile/Particles/Additive");

  renderer.material.mainTexture = tileTexture;

  float gridItemWidth = (float)1/gridColumns;
  float gridItemHeight = (float)1/gridRows;

  gridTile.transform.localScale = new Vector3(gridItemWidth,gridItemHeight,+zOffset);

  // Set grid Tile position
  // TODO add variable to calculate the grid difference 

  gridTile.collider.enabled = false;
  return gridTile;

 }


 Mesh CreateMesh(Vector3 firstPoint, Vector3 secondPoint, Vector3 thirdPoint, Vector3 fourthPoint)
 {
  Mesh m = new Mesh();
  m.name = "ScriptedMesh";
  m.vertices = new Vector3[] {
   firstPoint,
   secondPoint,
   thirdPoint,
   fourthPoint
  };
  m.uv = new Vector2[] {
   new Vector2 (0, 0),
   new Vector2 (1, 0),
   new Vector2(1, -1),
   new Vector2 (0, -1)
  };
  m.triangles = new int[] { 0, 1, 2, 0,2,3};
  //m.RecalculateNormals();

  //m.Optimize();
  
  return m;
 }

Tuesday, 29 July 2014

Pararell Universe Planets

After successful reception of Solar System asset that I published to Unity3d store I decided to create some more planets, this time imaginary that might exists somewhere in the universe.

Solar system still available here

First teaser of new planets


Submitting model with entities in MVC using DataTable fails when using pagination

I have uncommon issue today while trying to submit model with entities and using dataTable plugin.
Model was loosing entities data when user used pagination provided by dataTable plugin.

I post question on stackoverflow, unfortunately I did not get any answer but few hours later I found some small hack and it works now.

If anyone is interested I post it on stackoverflow:

http://stackoverflow.com/questions/25017597/submitting-model-with-entities-in-mvc-using-datatable-fails-when-using-paginatio/25020152#25020152


Tuesday, 8 July 2014

Get the values from http query string variables in View in ASP.NET MVC

This method can be used in any view but it is recommended to make sure your ViewModel contains all necessary information. We are going to use this approach in layout page, as normally layout page does not have any model(it can have but then it might get very messy and personally I think for big projects it could be extra constraint).

Consider a situation in which you are interested in values for variables from http request.

http://localhost:49853/Home/Index?searchType=global

In above address we are passing variable searchType. Let's assume that searchType can have 2 different values - local and global.

In your main css file:

#mainNav.global {
  background: #404939; }
  #mainNav.global  nav.nav {
    background: none; }
    #mainNav.global  nav.nav .top {
      background: #404939; }
    #mainNav.global  nav.nav a:hover, #mainNav nav.nav a.active {
      background-color: #7dc243; }
      
      #mainNav.local
      {
          background: #3C7987; }
        #mainNav.localnav.nav {
                  background: none; }
        #mainNav.local nav.nav .top {
                          background: #3C7987; }
        #mainNav.local nav.nav a:hover, #mainNav nav.nav a.active {
                        background-color: #7FDCFF; }

In layout page in _Layout file header section:

<header>
        <div class="content-wrapper">
            <div class="float-left">
                <p class="site-title">@Html.ActionLink("your logo here", "Index", "Home")</p>
            </div>
            <div class="float-right">
                <section id="login">
                    @Html.Partial("_LoginPartial")
                </section>
                @{
                    string searchClass = "global";
                    if (HttpContext.Current.Request.Params["searchType"] == "local") 
                    {
                        searchClass = "local"; 
                    }
                }
                <div id="mainNav" class=@searchClass>
                    <nav class="nav" data-nav>
                        <ul>
                          
                            @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "searchForm" }))
                            {
                                @Html.ActionLink("Global","Index","Home", new { searchType= "global" }, null)
                                @Html.ActionLink("Local","Index", "Home", new { searchType = "local" }, null)
                                <input type="search" name="searchMode" value="" placeholder="Search...">
                                <input type="submit" name="submitBtn" value="Search">
                            }
                        </ul>
                    </nav>
                </div>
               <nav>
                    <ul id="menu">
                        <li>@Html.ActionLink("Home", "Index", "Home")</li>
                        <li>@Html.ActionLink("About", "About", "Home")</li>
                        <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    </ul>
                </nav>
            </div>
        </div>
    </header>
So we are going to toggle class name for navigation bar. If we are in global searchType background color is #7dc243, in local searchType 7FDCFF.

If you are in global searchType your address is :
http://localhost:49853/?searchType=global




In local :

http://localhost:49853/?searchType=local

Thursday, 3 July 2014

Passing object from view to partial view with ViewDataDictionary in ASP.NET MVC

There might be a situation where you have parent model that for instance hold list of objects that you want to pass to partial view. I prefer to not use View Data or ViewBag and make sure that view models I am using always hold information I want to access, but there might be some exceptions.

Take a look at this example

 @Html.Partial("_EditAddress", Model.AddressVM, new ViewDataDictionary { { "statesList", Model.stateList} })

Third parameter in constructor for Partial class is ViewDataDictionary. Using this we can replace ViewData for partial view.
statesList in this example is key and Model.stateList is data that parent Model holds.

To retrieve the data in partial view access it like you would normally access ViewData and cast it to an object you are expecting.

So for instance if we are using dropdownlist helper :

@Html.DropDownListFor(m => m.stateId, new SelectList(ViewData["statesList"] as List<States>, "stateId", "name", "stateId"), "Select state")

Wednesday, 2 July 2014

Get current action and controller name in View in ASP.NET MVC

Being able to get action or controller name on view might come useful when you are using layout for every view(except partial views) in your application.

Layout view
 @if (Request.IsAuthenticated)
                        {
                            <ul>
                                <li>
                                    @Html.ActionLink("Dashboard", "Index", "Home")
                                </li>
                                <li>
                                    @Html.ActionLink("Account", "Manage", "Account")
                                </li>
                                <li>
                                    @Html.ActionLink("GetClients", "Index", "Client")
                                </li>
                                <li>
                                    @Html.ActionLink("Setting", "ListingForOrganisation", "Settings")
                                </li>
                               
                                @if (HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString() == "Client")
                                {
                                <li><span>Add Client</span>
                                    <ul>
                                        <li>
                                            @Html.ActionLink("Temporary client", "AddTemporaryClient", "Client")
                                        </li>
                                        <li>
                                            @Html.ActionLink("Permanent", "AddPermanentClient", "Client")
                                        </li>
                                    </ul>
                                </li>
                                }
                            </ul>
                        }

(HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString() == "Client")
will check if request came from Client controller and if so extra feature will appear.

To get action name replace simply use 
(HttpContext.Current.Request.RequestContext.RouteData.Values["action"].ToString() == "Action name") 



Tuesday, 22 April 2014

Prevent displaying Log In page in partial view on ajax request after session expired in ASP.NET MVC

If you are using partial views with many ajax request, there might be a situation in which user session expires and if you will try to submit form asynchronously via ajax  Log in page will be displayed in partial view(this will occur if you are using authorize attribute on the method you are calling).

Add this method to global.asax.cs file.

 // To use for ajax request when user session expired

protected void Application_EndRequest()
        {
            var context = new HttpContextWrapper(Context);
            // If we're an ajax request, and doing a 302, then we actually need to do a 401
            if (Context.Response.StatusCode == 302 && context.Request.IsAjaxRequest())
            {
                Context.Response.Clear();
                Context.Response.StatusCode = 401;
            }
        }

In main.js file or script section on your main view(cshtml file if using Razor) add this:

var  $document = $(document);

handleAjaxError = function (XMLHttpRequest, textStatus, errorThrown) {
    if (XMLHttpRequest.status == 401) {
        //refresh the page, as we are not longer authorized
        location.reload();
    }
    };
 
Since we already lost session, we want to refresh the page and user will be redirect automatically to Log in page, rather than displaying Log in page in small partial view.

    $document.ajaxComplete(function(event, XMLHttpRequest, AjaxOptions){
        handleAjaxError(XMLHttpRequest);
    }); 

http://api.jquery.com/ajaxComplete/ - More on ajax Complete method

http://stackoverflow.com/questions/3431343/asp-net-mvc-forces-an-ajax-request-be-redirected-to-the-login-page-when-the-form - Inspired by this post

Tuesday, 1 April 2014

Google adsense April Fools joke

After I logged in today to see if google made any April fools joke I discovered one on Ad sense earning page. Regions have been replaced by planets and moons. It might be quite funny at the moment, but in next 30-100 years it might be real.

Saturday, 15 March 2014

Submitting form with partial view in ASP.NET MVC

In this tutorial we want to submit form with partial model.

Download full project here

We are going to have ClientVM that will have partial view with Address model. 
Create new MVC 4 project, choose internet project and Razor.

Create models that we will use in this project.

Models
public class Client
    {
        public Client()
        { 
        }

        public Client(string firstName, string lastName, Guid addressId)
        {
            this.address = new Address();
            this.clientId = Guid.NewGuid();
            this.firstName = firstName;
            this.lastName = lastName;
            this.addressId = addressId;
        }

        public Guid clientId { get; set; }
        public string firstName { get; set; }
        public string lastName { get; set; }
        public Guid addressId { get; set; }
        public virtual Address address { get; set; }
    }

public class Address
{
    public Address()
    { 

    }

    public Address(string houseNumber, string streetName)
    {
    this.addressId = Guid.NewGuid();
    this.houseNumber = houseNumber;
    this.streetName = streetName;
    }

    public Guid addressId { get; set; }
    public string houseNumber { get; set; }
    public string streetName { get; set; }
}

View Models

 public class ClientVM
    {
        public ClientVM()
        { 
            
        }

        public ClientVM(Client client, Address address)
        {
            this.clientId = Guid.NewGuid();
            this.firstName = client.firstName;
            this.lastName = client.lastName;
            this.addressId = client.addressId;
            this.addressPartial = address;
        }

        public Guid clientId { get; set; }
        public string firstName { get; set; }
        public string lastName { get; set; }
        public Guid addressId { get; set; }
        public Address addressPartial { get; set; }

    }


In Home controller we will create ActionResult ClientInfo

public ActionResult ClientInfo()
        {
            // Normally we would get Client from database. For test we use constructors to define new     entries.

            Address address = new Address("25 A", "London street");
            Client client = new Client("Adam", "Bielecki", address.addressId);

            ClientVM viewModel = new ClientVM(client, address);

            return View(viewModel);
        }

and the same method to submit the form:

[HttpPost]
        public ActionResult ClientInfo(ClientVM viewModel)
        {
            return View(viewModel);
        }

In _Layout_cs change 2nd link for menu.

<li>@Html.ActionLink("Submit Partial Model", "ClientInfo", "Home")</li>

so menu tabs should look like that:

<ul id="menu">
                            <li>@Html.ActionLink("Home", "Index", "Home")</li>
                            <li>@Html.ActionLink("Submit Partial Model", "ClientInfo", "Home")</li>
                            <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                        </ul>

Now we have to create 1 view for ClientInfo and 1 partial view for Address.
Compile your project (Shift+Ctrl+B), right click ClientInfo in Home Controller and Add View.

Check Create a strongly-type view, choose ClientVM and scaffold template : Edit.





Right click on shared folder add view and call it _Address. Use the same setting as before, but this time select Address as your model class and check box "Create as a partial view".

Remove form from _Address partial view so it should like that:



@model PartialViewModelSubmission.Models.Address

<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

<h2>Address</h2>

    <fieldset>
        <legend>Address</legend>

        @Html.HiddenFor(model => model.addressId)

        <div class="editor-label">
            @Html.LabelFor(model => model.houseNumber)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.houseNumber)
            @Html.ValidationMessageFor(model => model.houseNumber)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.streetName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.streetName)
            @Html.ValidationMessageFor(model => model.streetName)
        </div>

      
    </fieldset>


Run the application, click Submit Partial Model and submit the form. 
As you can see we get error as Address have not been submitted.



 The reason why it is happening is due to binding issue. Let's fix it.

We will have to create partial class for Address. In Address.cs add this partial class:


public partial class AddressBase
{
   public virtual Address partialAddress { get; set; } 
}

Using virtual type we are going to lazy load Address.

 Modify ClientVM so it looks like that:




public class ClientVM : AddressBase
    {
        public ClientVM()
        { 
            
        }

        public ClientVM(Client client, Address address)
        {
            this.clientId = Guid.NewGuid();
            this.firstName = client.firstName;
            this.lastName = client.lastName;
            //this.addressId = client.addressId;
            //this.addressPartial = address;
            this.partialAddress = address;
            
        }

        public Guid clientId { get; set; }
        public string firstName { get; set; }
        public string lastName { get; set; }
        // public Guid addressId { get; set; }
        // public Address addressPartial { get; set; }
    
}

ClientVM inherit from AddressBase partial class so we can assign address to base.
            this.partialAddress = address;

This is all you have to do for classes, we have to amend views a bit as well.

In ClientInfo we are going to pass ClientVM model to address so change it to :
@Html.Partial("_Address", Model)

In _Address view change model to AddressBase and update scaffolding so it should look like that:

@model PartialViewModelSubmission.Models.AddressBase

<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

<h2>Address</h2>

    <fieldset>
        <legend>Address</legend>

        @Html.HiddenFor(model => model.partialAddress.addressId)

        <div class="editor-label">
            @Html.LabelFor(model => model.partialAddress.houseNumber)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.partialAddress.houseNumber)
            @Html.ValidationMessageFor(model => model.partialAddress.houseNumber)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.partialAddress.streetName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.partialAddress.streetName)
            @Html.ValidationMessageFor(model => model.partialAddress.streetName)
        </div>

      
    </fieldset>
Now run the application again and if you followed everything correctly you should be able to see Address model when you debug.







Sunday, 9 March 2014

How to hide querystring parameter name from an URL generated with Html.ActionLink in ASP.NET MVC

 In View we are going to create link using Html helper :
@Html.ActionLink("Address", "ViewAddress", new { addressId = Guid.NewGuid() })
that will give us :

http://localhost:100/Home/ViewAddress?addressId=5f89a656-e98c-4680-b98f-6a3cf4ede7aa

We want to hide query string addressId and have only :

 http://localhost:100/Home/ViewAddress/5f89a656-e98c-4680-b98f-6a3cf4ede7aa

The solution is to add new map route.

Open RouteConfig.cs file from App_Start folder and add new Map Route:

routes.MapRoute("ListingPreview", "Home/ViewAddress/{addressId}",
                new
                {
                    controller = "Home",
                    action = "ViewAddress",
                    addressId= UrlParameter.Optional
                }
                );

Sunday, 23 February 2014

Setting up Unity3d webplayer on ASP.NET hosting

So I have some issues when I tried to upload web player version of one of my projects to ASP.NET server - arvixe.
After I uploaded webplayer version (html file and unity3d file) I was able to see unity 3d webplayer but nothing was loading. The solution is to add mime type(in my case I was able to do it via cpanel, if you do not have an access it is good to ask admin to do it for you).


The MIME type for Unity webplayer is:
    1. application/vnd.unity
And the file extension for unity webplayer files is:
    1. .unity3d

That fixed the issue for me and I was able to load my project on web.

Monday, 10 February 2014

Project Solar System in Unity 3d - update #1

I have been working recently on project Solar System. The idea is to allow user to view every planet in our solar system, zoom in out, rotate find the distance between planets, difference in mass etc.
I found maps from all the planets and unwrap it on sphere so it represents exact surface of each planet, at least solid once. Jupiter which is gas planet have correct map as well, however Uranus and Neptun won't have detailed map as they are vague. First screenshot - please ignore logic around how the planets are placed, it is just first showcase. In next release I will make sure good ratio is provided.
Any feedback, comments and suggestions are really appreciated.

Available now on Unity 3d store : UNITY 3D





Thursday, 16 January 2014

Space Escape Rush - Mobile game #update 5

For quite good ammount of time I was working on zero gravity corridor for my mobile game.
Not finished and polished yet but some first results can be view below.


Tuesday, 7 January 2014

Futuristic Sci-Fi Doors in Unity 3d available now in asset store!

Unity 3d accept my asset to be submitted to their store. I am very happy about this fact as they have rejected few times my previous assets, which I have to thank them as that motivates me to improve my skills in video gaming industry.

https://www.assetstore.unity3d.com/#/content/14048