This software is free

image

 

This is an MVC add-on to add a messaging system to any MVC application. It costs me 0$ to make this program ( not yet finished, but free source at http://messagemvc.codeplex.com/  and the related posts are at http://msprogrammer.serviciipeweb.ro/category/howto/asp-net-mvc/mvc-4/mvc-messaging-system-mvc-4-asp-net-mvc-howto/ )

Home Computer – already done for browsing the internet.

Download Visual Studio Express – free .

Download Sql Server Express – free.

Download latest bits of EF 4.2 – to work with SqlServer Compact too – free.

(Connection to internet : 25 $ – but was already done for browsing the internet)

Installing and configuring software on my PC – 0 $.

All I have done is to sit on my home desk and tapping into the keyboard. But this is does not costs , right?

Making, Planning, testing, deploying – 0$.

[quote from=http://www.petapixel.com/2012/01/10/this-photograph-is-not-free/ ]

So if you’re a magazine, website, corporation, sports team, or advertiser developer who wishes to use this photo  software , please don’t   come and ask to use it for free, or in exchange for credit or “exposure”.

[/quote]

Do not give feedback . Just rant about how bad code smells ,about how OOP and SOLID and Design Patterns are not made clear and how Testing is not properly handled. After all, it is free , right?

Usual Methods to transfer data from Page To Page in ASP.NET MVC

Preamble:

In ASP.NET ( like in PHP and other Web frameworks) there are 2 clear entities: Server ( code on the WebServer ) and Client( the HTML interpreted by the browser and javascript).

Server and Client shares same cookies – means Client and Client both can read and write cookies.

Transfer from the Client to Server happens when

a) you click a link : the information to transfer is query string . That means, http://…/a?x=y&a=b will send information y ( associated to key x) and b( associated to key a). This is called a GET

b) you press a submit button to send a FORM : the information is values of select and input. This is called a POST.

c) you send information via javascript ( including AJAX) . Usually this can involve a PUT, a GET, or other ( see REST ).

d) Creating/Modifying and send cookies. The sending happens automatically by the browser .

Transfer from the Server to Client

a)sending text(HTML)/binary data. . The interpretation is done by the browser( how to display html, how to display send file …)

b) Creating/Modifying and send cookies . Browser will do automatically this.

ASP.NET WebForms way:

For ASP.NET Webforms the modalities to transfer are detailed by Peter Bromberg , http://www.eggheadcafe.com/tutorials/asp-net/e653f028-01fb-4d0e-843b-058deae562a2/eight-different-ways-to-transfer-data-from-one-page-to-another-page.aspx .

ASP.NET MVC way:

I want to discuss from ASP.NET MVC perspective. In MVC we have 2 distinct objects: VIEW and ACTION. Both happens to run on the Server .

  • The ACTION can return a VIEW or ( or a redirect to) another ACTION or simply a FILE
  • The VIEW processes a Model ( and a ViewBag/ViewData) and sends the text( HTML) data to the Client .

Instead of PAGES , we will discuss of VIEWS – because the VIEWS sends HTML data to the Client.

So, to transfer data between View1 to View2 in MVC is reduced to this:

a) Page1 transfer data to the server ACTION1( by a,b,c,d methods in the Preamble )

b) The Action receives the values as his parameters ( by binding) and can do this:

b1) Return a different View ( using some logic :

if( a )

return View1(Model1);

else

return View2(Model1);

b2) Returning a Redirect to ACTION2 ( that return View2) or simply return the result of this action

return RedirectToAction(Action2(<parameters>)); //Used in Post/Request/GET, http://en.wikipedia.org/wiki/Post/Redirect/Get

return Action2(<parameters>);

Resuming: Transfer betweem PAGE to PAGE in ASP.NET MVC is really transfering from ACTION to ACTION , besides the cookie that can be transferred directly by the browser.

9 Modalities to transfer data from Page to Page in ASP.NET MVC

Enough theory, let’s do some code. We have a Model to transfer named ModelTransfer

public class ModelTransfer
    {
        public int Age { get; set; }
        public string Name { get; set; }


    }

We have the first View1( Index) and a second View2(Transfer) that will server as an example. Also, we will have the more ACTIONS – one for each example of transfer – all are using the TRANSFER action as an ultimate resort do see the View.

Method1 : Transfer directly to the second View/Action .

<a href='@Url.Action("Transfer", new { Age = 42, Name = "Andrei Ignat" })'>click me</a>
public ActionResult Transfer(ModelTransfer m)

Method2 Index sends POST data to a [HttpPost] Index action, that performs some calculations and return a redirect.Usefull in PRG

@using (Html.BeginForm()) { 
<input type="text" id="Age" name="Age" value="42" />
<input type="text" id="Name" name="Name"  value="Andrei Ignat"/>
<input type="submit" value="Click me" />
}

 [HttpPost]
        public ActionResult Index(ModelTransfer m)
        {
            //save to the database the data 

            //this is for transferring alert data - such an "Completed saving" message to the user 
            TempData["displayalert"] = " this is from Index POST action!";
            //used in PRG 
            return RedirectToAction("Transfer", new ModelTransfer() { Age = m.Age, Name = m.Name });            
        }

Method3: No data send. The ServerAction just make some data to be transferred to the Transfer view, by TempData

<a href='@Url.Action("ServerAction")'>click me</a>
 public ActionResult ServerAction()
        {
            //You can put also into the Session / Application /Cache depending on your specifications
            TempData["MyModel"]=new ModelTransfer(){ Age = 42, Name = "Andrei Ignat"};
            TempData["displayalert"] = "this is from Server action!";
            
            return RedirectToAction("Transfer");
        }

Method4: No data send. The ServerAction just make some data to be transferred to the Transfer view, by Cache

Method5: No data send. The ServerAction just make some data to be transferred to the Transfer view, by Session

Method6: No data send. The ServerAction just make some data to be transferred to the Transfer view, by Application

Method7: No data send. The ServerAction just make some data to be transferred to the Transfer view, by HttpContext Items

Method8: By Cookies

<a href='@Url.Action("TransferCookies")'>click me</a>
 HttpCookie cook = new HttpCookie("Transfer");
            //usually you put here more , but now I do not want to interfere with other methods
            cook.Expires = DateTime.Now.AddSeconds(1);
            cook.Value = "from transfer cookies";
            Response.Cookies.Add(cook);
            return RedirectToAction("Transfer");

Method9: By Javascript /Ajax.
It is an entire post by itself and you can see here:
http://msprogrammer.serviciipeweb.ro/2011/12/05/jquery-ajax-request-and-mvcdetailed/

Summary

In this post you have seen 9 methods to transfer data in MVC. As a bonus, the page dispolays also a message with Javascript( usefull for messaging like “Data Saved to database” messages to the user.
The code source you will find here:

Transfer Data Page to Page
It is made with Razor and MVC3 – but you can replace Razor with aspx and MVC3 with MVC2 also.

If you think I can improve this post, please leave some comment.

Notes:

I used here hard coding values. Please learn about T4MVC and Html.EditorFor !

To learn more about ASP.NET MVC visit http://asp.net/mvc.

Default TempDataProvider is based on Session. There is one more , based on cookies.

Please do the exercises to gain self knowledge about MVC

friday links 12

  1. Find & Purchase Data Subscriptions | Windows Azure Marketplace
  2. Would A Ponzi By Any Other Name Smell As Bad? | ZeroHedge
  3. Troy Hunt: ASP.NET session hijacking with Google and ELMAH
  4. Troy Hunt: Free eBook: OWASP Top 10 for .NET developers
  5. StructureMap and ASP.NET MVC 3 – Getting Started
  6. CuBox
  7. Unit Testing Myths and Practices
  8. This Photograph Is Not Free
  9. Richard Stallman Was Right All Along
  10. Programming Isn’t Fun Any More
  11. Matt Wrock’s Blog | Microsoft blogging platform gains 33% performance boost after adopting RequestReduce
  12. Matt Wrock’s Blog | Adopt RequestReduce and see immediate Yslow and Google Page Speed score improvements not to mention a faster site!
  13. The Joel Test: 12 Steps to Better Code – Joel on Software
  14. Developer declares ‘I am done with the Freemium Business Model’ | ITworld
  15. University accuses Oracle of extortion, lies, ‘rigged’ demo in lawsuit | The Industry Standard – InfoWorld
  16. calvin.jpg (JPEG Image, 900×628 pixels)
  17. NuGet Package of the Week #10 – New Mobile View Engines for ASP.NET MVC 3, spec-compatible with ASP.NET MVC 4 – Scott Hanselman
  18. The Seven Habits of Spectacularly Unsuccessful Executives – Forbes
  19. Everything for free, always: how Facebook ads show us the sad state of the Internet
  20. Eight Different Ways to Transfer Data from One Page to Another Page
  21. Stop using AutoMapper in your Data Access Code | Blog | DevTrends
  22. Visual Representation of SQL Joins – CodeProject®
  23. I, Interface – CodeProject®
  24. MVC Techniques with JQuery, JSON, Knockout and C# – CodeProject®
  25. The 11 Best Science Books of 2011 | Brain Pickings
  26. Alexander Beletsky’s Development Blog: Using ASP.NET MVC Validation Mechanism without ASP.NET MVC
  27. Amazon.com: The Flinch eBook: Julien Smith: Kindle Store
  28. Best Practices for Handling Transient Conditions in SQL Azure Client Applications | Windows Azure Customer Advisory Team (CAT)
  29. jQuery UI Development & Planning Wiki / Template-Comparison
  30. ASP.NET MVC 3 and the @helper syntax within Razor – ScottGu’s Blog
  31. High-Performance ASP.NET Caching — Visual Studio Magazine
  32. Free Databases in the Window Azure Marketplace — Visual Studio Magazine
  33. Duck Programming
  34. Writing an automatic debugger in 15 minutes (yes, a debugger!) « TripleEmcoder
  35. Creating Bookmarklets for Fun and Profit | Think Vitamin
  36. Math doesn’t suck, you do.
  37. – tatiyants.com
  38. A geek with a hat » Why programmers work at night
  39. ASP.NET MVC + Selenium + IISExpress
  40. SQL Azure Performance and Elasticity Guide – TechNet Articles – Home – TechNet Wiki
  41. 6 Books Every Programmer Should Own
  42. 10 Websites On How To Be A Better Programmer
  43. A Professor explained Marketing to MBA students « Pulkit Arora
  44. 91 Ways to become the Coolest Developer in the World « Pulkit Arora
  45. Orchard Project
  46. Extensions – Ninject
  47. Chapter 1 – Welcome to the Library
  48. Microsoft in 2011: How 13 Big Developments Shaped the Tech Giant
  49. HTML EMAIL BOILERPLATE v 0.5 updated 11/5
  50. Conditional Filters in ASP.NET MVC 3
  51. ASP.NET MVC Diagnostics Using NuGet
  52. Conversion from type ‘Object’ to type ‘String’ is not valid. : The Official Microsoft ASP.NET Forums
  53. How I Lost, Regained and then Turned Down an MVP Award – .NET & Funky Fresh – Devlicio.us – Just the Tasty Bits
  54. Projects | code.nasa.gov
  55. Progressively enable the mobile web with ASP.NET MVC 4, HTML5, and jQuery Mobile | BUILD2011 | Channel 9
  56. Code First Migrations: Beta 1 ‘With-Magic’ Walkthrough (Automatic Migrations) – ADO.NET team blog – Site Home – MSDN Blogs
  57. Code First Migrations: Beta 1 Released – ADO.NET team blog – Site Home – MSDN Blogs
  58. Five Things You Should Stop Doing in 2012 – Dorie Clark – Harvard Business Review
  59. Signs that you are a bad programmer (Bad Programmers)
  60. This is why I don’t give you a job – Andor Jakab
  61. A Shiny New Me • HTML5 Boilerplate In Visual Studio 2010
  62. 9GAG – Can live with them can’t f**k without them

Hydrating

My first Nuget project: Hydrating.  Also a Codeplex project : http://hydrating.codeplex.com/ 

It can re-make an object by adding items of “property/value”

It comes in 2 flavors: .NET 2.0 ( reflection ) and .NET 4  ( expression).

Sample Usage:

Sample usage:
var Model = new HydrateGeneric<MyModel>();
Model.AddNewProperty("OneProp", "bb");
Model.AddNewProperty("newData.StartDate", DateTime.Now.AddDays(1).ToString());
Model.AddNewProperty("newData.SecondProp", "AB");
Model.AddNewProperty("newData.aOne.ThirdProp", "XXX");
var data = Model.NewObject();
Console.WriteLine(data.newData.SecondProp);
Console.WriteLine(data.newData.StartDate);
Console.WriteLine(data.newData.aOne.ThirdProp);

 

It comes from a Paulo Morgado idea from http://msmvps.com/blogs/paulomorgado/archive/tags/ExpressionTrees/default.aspx . However, his initialization does not specify property name – so it’s rather error prone if you do not specify properties + values in right order. I have somewhat improved by

 

Model. AddNewProperty("OneProp", "bb");

 

Enjoy!

http://hydrating.codeplex.com/

https://nuget.org/packages/Hydrate

Chosen and Jquery and MVC

In the MVC forums I have seen a reference to Chosen. From the description here:
“Chosen is a JavaScript plugin that makes long, unwieldy select boxes much more user-friendly.”
It look beautifool – and I see the opportunity to improve my toolbox. I said: “I will do in 10 minutes”. Well, it did take longer – but not so long.

I will make an example my tutorial mvc and ajax – since it does not require any database.

So I download the source from https://github.com/harvesthq/chosen/ , put the .js in Scripts folder, the .css in Contents folder and registered in JqueryMVCRazor\JqueryMVCRazor_Web\Views\Shared\_Layout.cshtml

<link href="@Url.Content("~/Content/chosen.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/chosen.jquery.min.js")" type="text/javascript"></script>

Here is the code : ( from JqueryMVCRazor\JqueryMVCRazor_Web\Views\Shared\EditorTemplates\EditEmployeeViewModel.cshtml ):

 @{
     var idcombo = "#"+ ViewData.TemplateInfo.GetFullHtmlFieldId("cmbemp" + Model.Employee.IdEmployee);
     }<script>
     $(document).ready(function () {

         $("@idcombo").chosen({ no_results_text: "No results matched"});

     });

 </script>

And I said, this will be all.

Not so: see the picture – the names does not show up:

image

First I was thinking that it does not select the item. After several attempts, I realize the “…” ( three dots) – that means the width was not enough.
Next move, since I was in the javascript mood, was to add some javascript to adjust the width to fit:

So the code becomes:

$("@idcombo").chosen({ no_results_text: "No results matched" });
$("@idcombo").width("350");

No difference. So I tried the opposite way:

$("@idcombo").width("350");
$("@idcombo").chosen({ no_results_text: "No results matched" });

Now it matches:
image

And , thinking about a bit, it is better right in the Dropdown declaration :

@Html.DropDownList("cmbemp" + Model.Employee.IdEmployee, new SelectList(Model.DepartmentList, "IDDepartment", "NameDepartment", Model.Employee.Department.IdDepartment),new{ style="width:350px;"})

Summary:

Integration of Chosen with MVC dropdown is rather simple. Add the .js, the .css, register in the page, add $(“@idcombo”).chosen() declaration and do not forget the width of the dropdown ( select )

Source code here
Later edit: Please add also

to the header

First version of Messaging system

image

Realized the first version. When you logon on the system, the application sends you an email and you can see it.

Lots of thing done – however, the testing is not complete.

Logging was the difficult part- since I want to work with various loggers( LOG4NET, NLOG, MS TRACE, and so on). I required to a duck typing from  DeftTech. See logging assembly for more details.

You can download the files from http://messagemvc.codeplex.com/– however, you may want to wait for a NuGET version.

If you want to help me further , please send me an email via http://messagemvc.codeplex.com/.

Andrei Ignat weekly software news(mostly .NET)

* indicates required

Please select all the ways you would like to hear from me:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.