Wednesday, October 2, 2013

Create Custom Calendar in MVC

There are several plugins out there that can help you to create a calendar in MVC, JQuery, and other languages, but one disadvantage to all of these is a lack of customization.  In searching the web, I noticed that not many articles have been written about this topic, so here's one example.

This article will help you get started in creating a fully customizable HtmlHelper method to use throughout your application in MVC.  I prefer MVC4, but it will work with version 3 as well.

First, create a static class and name it whatever.  Mine is called DataControls, but it isn't important.  The only reason for the static method is so that you can use it as an MVC helper class in your view.

The class looks like this:

using System;
using System.Globalization;
using System.Text;
using System.Web.Mvc;
public static class DataControls
    {
        public enum DayFormat
        {
            Long, Medium, Short
        }

        public static MvcHtmlString Calendar(
  this HtmlHelper helper,
  DayFormat dayFormat,
  int month, int year)
        {
            DateTime today = DateTime.Now;
            int daysInMonth = DateTime.DaysInMonth(year, month);
            string[] dayNames = new string[] { };
            switch (dayFormat)
            {
                case DayFormat.Medium:
                    dayNames = new string[] { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };
                    break;
                case DayFormat.Short:
                    dayNames = new string[] { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" };
                    break;
                case DayFormat.Long:
                    dayNames = new string[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
                    break;
                default:
                    throw new Exception("Please specify a Day Format.");
            }
            StringBuilder calendar = new StringBuilder();
            calendar.Append(string.Format("

", "calendar"));

            calendar.Append("");
            calendar.Append(" ");
            for (int i = 0; i < dayNames.Length; i++)
            {
                calendar.Append(string.Format("{0}", dayNames[i]));
            }
            calendar.Append("
");            calendar.Append("
");            calendar.Append("");
            for (int i = 1; i <= 42; i++)
            {
                if (i % 7 == 1)
                {
                    calendar.Append(" ");
                }
                calendar.Append("");
                DateTime firstDay = new DateTime(year, month, 1);
                int firstDayOfWeek = (int)CultureInfo
        .InvariantCulture.Calendar.GetDayOfWeek(firstDay);
                if (i > firstDayOfWeek && (i - firstDayOfWeek) <= daysInMonth)
                {
                    calendar.Append(i - firstDayOfWeek);
                }
                calendar.Append("
");                if (i % 7 == 7)
                {
                    calendar.Append("
");                }
            }
            calendar.Append("
");            calendar.Append("
");            return MvcHtmlString.Create(calendar.ToString());
        }
    }

In a nutshell, we are creating a table that allows us to specify a format for month names, and then doing a loop to determine what day of week each day falls on, as well as how many days occur in the selected month and year.  If you don't care about the format of the days, you don't have to use the enum, but I like to allow for customization.

Once this is created, you can simply call this function inside of your razor view by calling:

(This would generate a calendar for January of 2013)
@Html.Calendar(DataControls.DayFormat.Medium, 1, 2013)

Obviously, you'd want to create a filter mechanism for displaying months and years to the user so they could select a month and year, but that is outside of the scope of this article.  Personally, I created an array and displayed dropdowns in my page for them to select from, but just as easily, you could create custom links for them to select from as well.  Use your imagination.

Good luck with this, and if you have any questions, feel free to contact me via my homepage at: Joshua Blackstone.Com or comment below.

Thanks.

Thursday, August 15, 2013

MVC Pass Different Model to Partial View

Did a quick search and couldn't find this information anywhere online, so here goes.

Here's my scenario.

I Create new MVC project. (I'm using v4, but it would apply in earlier as well), and choose Internet Application. AccountModels.cs is created in my models folder.

There are 2 classes I'm concerned about. UserProfile and RegisterModel.

My scenario involves saving reuse and creating a partialview for creating and editing the user information. A fairly common scenario in web development. So I create the partialview, and use the Model Declaration of UserProfile. I include all information inside of this that will be reused among the 2 views. In my situation, the password and confirm password are the fields I'm not re-using, so those won't be included in my partialview.

So my views look like:

_UserInfo (Partial View):

@model UserProfile

    @Html.LabelFor(m => m.UserName)
    @Html.TextBoxFor(m => m.UserName)


RegisterPage:

...
Registration Form
       


               @Html.Partial("_UserInfo", Model)

                    @Html.LabelFor(m => m.Password)
                    @Html.PasswordFor(m => m.Password)
               
    ...

    But wait!  This generates an error msg stating that the model type is not the same.  How do I pass a valid model type in so that my controller can still read the data back?

    At the top of the RegistePage, I add the following:

    @model RegisterModel
    @{
        ViewBag.Title = "Register";
        UserProfile user = new UserProfile();
    }

    and change my RegisterPage to pass in user instead of Model, such as:

    @Html.Partial("_UserInfo", user)

    That's it!  Now I can reuse this in an edit profile page and simply use UserProfile as my model type, and pass it into the partialview like:

    @Html.Partial("_UserInfo", Model)

    and the partialview will render it with no problems.



    Thursday, December 1, 2011

    Using JQuery ProgressBar with Long ASP.NET Process

    OK, so maybe others have figured this out, but if so, they haven't written about it. Wanted to use the JQuery Progressbar to display progress results for a long ASP.NET Process.

    First thing was to download a theme from the ThemeRoller site, http://jqueryui.com/themeroller/, and add the jquery library to my project.

    Next, you must create a class to process the status of a ThreadStart Result in ASP.NET. For details on doing this, you can read the Microsoft Documentation, located at: .

    Next, you will need two pages, one for creating the long process, one for showing the progress of the item.

    The majority of the work can be found in the sample code, found at: http://www.joshuablackstone.com/Examples/LongProcess.zip, but the key for me was how to show the progress in the progress bar. First, create your div, such as:

    <div class="progress" rel="0" runat="server" id="progressBar"></div>, and then the code to post the value to the progress bar is set with this function:

    function pageLoad(sender, args) {
    if (args.get_isPartialLoad()) {
    $("div.progress").each(function () {
    var element = this;
    $(element).progressbar({
    value: parseInt($(element).attr("rel"))
    });
    });
    }
    }

    The reason for the section (if (args.Get_isPartialLoad)) is because an update panel is triggering a timer every two seconds to get the latest value from the threadstart.

    So then, you run the process, which sends the user to the progress page, where they will see a jquery themed progress bar showing progress for the long process, and redirects to a page of your choice when complete.

    Cool.

    Wednesday, September 22, 2010

    JSON Fetch Random Record

    Searched everywhere for this one. Hopefully it will help someone else out...

    I was looking for a way to filter a JSON dataset by an ID number. Here goes...


    1. Step 1 : Create your JSON Data.


      var item = [
      { "id": "0", "language": "English"},
      { "id": "1", "language": "Spanish"},
      { "id": "2", "language": "French"},
      { "id": "3", "language": "Hungarian"}
      ];

    2. Step 2 : Function to find Unique Value:


      I cant take credit for this one. I found this at : http://stackoverflow.com/questions/604935/how-can-i-filter-json-for-unique-key-name-value-pairs. Here it is...

      function getDistinct(o, attr) {
      var answer = {};
      $.each(o, function(index, record) {
      answer[index[attr]] = answer[index[attr]] || [];
      answer[index[attr]].push(record);
      });
      return answer;
      }

    3. Step 3: Create Random Number

      var randNo = Math.floor(Math.random() * 4); (with 4 being the same number of records contained in the JSON Dataset).

    4. Step 4: Return unique record items


      $(function() {
      $.each(getDistinct(markers, "id"), function(groupName, recordArray) {
      var firstRecord = recordArray[randNo];
      $('
    5. ').html(firstRecord.language).appendTo('#results');
      });
      });




    Finally, the body simply contains an unordered list with an id of results to contain the information.

    Friday, September 17, 2010

    ASP.NET Routing 4.0 Handle Error

    OK, so this took a lot of searching, but this worked. Not sure why it isn't put into the Web.Config file initially, or that there isn't more documentation, as this had me going nuts. Anyways, if you get a 404 error on the ASP.NET 4.0 routing feature when you deploy to IIS7.0, take a look at this. I bet it will get you going...

    http://www.gildnersolutions.com/post/2010/04/21/ASPNET-40-URL-problem-with-IIS7.aspx

    Tuesday, July 13, 2010

    Javascript In or Out of Office

    Wanted to create a standard tool to determine if a business is in or out of the office. Fairly standard stuff, but here it is if anyone can use it.


    Needed to check for 3 things.


    1. Holidays

    2. Weekends

    3. Business Hours (in this case 8 to 5)




    Anyways, here's the script that results in a boolean value to determine whether or not the office is open.


    var d = new Date();
    var day = d.getDay();
    var h = d.getHours();
    var y = d.getYear();

    var holidays = ['1/1/' + y,
    '1/21/' + y,
    '2/18/' + y,
    '5/26/' + y,
    '7/4/' + y,
    '9/1/' + y,
    '10/13/' + y,
    '11/11/' + y,
    '11/27/' + y,
    '12/25/' + y,
    '12/31/' + y];

    function isWeekend() {
    if (day == 0 || day == 6) {
    return true;
    }
    else
    {
    return false;
    }
    }

    function isOffHours() {
    if (h < 8 || h > 17) {
    return true;
    }
    else {
    return false;
    }
    }

    function businessClosed() {
    var today = (d.getMonth() + 1) + '/' + d.getDate() + '/' + y;
    if (isWeekend() == true || (jQuery.inArray(today, holidays)) > 0 || isOffHours() == true) {
    return true;
    }
    else {
    return false;
    }
    }

    $(function () {
    if (businessClosed() == true) {
    alert('Sorry, we are closed!');
    }
    else {
    alert('Open for Business!');
    }
    });


    If you want to download, it can be found HERE.

    Thursday, June 17, 2010

    C# vs VB - The debate continues...

    Just getting my feet wet with C#, after being a VB developer for awhile, realizing that C# is getting all of the jobs. With that being said, have run into a few difficulties in converting over, and I'll list a couple here, to be added to as I go along. Consider this a newbie's version of headaches you may face when switching to C#...




    1. In VB, if you want to locate an element inside of a control, you would use:

      Dim control as CONTROLTYPE = CType(CONTAINER.FindControl("ControlID"), CONTROLTYPE)


      In C#, you would write the same expression as:

      CONTROLTYPE control = (CONTROLTYPE)CONTAINER.FindControl("ControlID");

    2. In VB, if you want to place an IIf statement inside of a Label Control, you're free to do so. Simply use

      <%#IIf(Convert.ToString(EXPRESSION)=Something, True, False)%>

      However, when you attempt to use this in C#, you will get an error, as IIf isn't recognized.

      Here's the fix:

      <%# (Convert.ToString(EXPRESSION) == Something ? True : False)%>.

    3. Of Course, & is not recognized, it is replaced by +.

    4. I know when I was creating a VB Side HTML Message, or if I was creating a very long string, I would use '& vbCrLf _'. However, in C#, this changes a bit. Declare your String, and append it just as you would in JS. Example?


      string A = "";

      A += "This is a string ";
      A += " and the second line of the string...";



    I will modify this as I go, but if you are like me, and have done VB this whole time, I would recommend taking any current sites you have done, and redo them from scratch in C#. Get Hung Up? Use THIS as a last resort, it's a pretty good tool.


    Good Luck!

    Wednesday, June 9, 2010

    Thank You Ryan Grove - Finally a Script Loader that works painlessly!

    Finally was able to make my homepage not CRAWL due to a lazy script loader that I found. Prior to this, either security was too tight from GoDaddy or it was just made for Image Files. Anyways, check this out...


    http://wonko.com/post/painless_javascript_lazy_loading_with_lazyload

    Tuesday, June 8, 2010

    Use Google Calendar as Datasource for Holiday Notifications

    I wanted to see how difficult it would be to do a simple notification on my site of any basic holidays that occurred on any given day. Sure, it would be simple enough to simply create an array to hold the data in js, and display if the date matched, but I figured I would use a JSON Feed to display the data instead. Turns out Google Calendar has just the thing in their Holiday Calendar Feed.

    http://www.google.com/calendar/feeds/en.usa%23holiday%40group.v.calendar.google.com/public/basic

    If you go to this feed, you'll notice there is a lot of information that needs to be parsed down to use it, so after some fiddling, I came up with the following YQL Feed:

    select entry.title.content, entry.summary.content from xml where url='http://www.google.com/calendar/feeds/en.usa%23holiday%40group.v.calendar.google.com/public/basic' AND entry.content.content LIKE '% + year + %'

    with year being a new Date().getYear() value.

    Anyways, here's the script. It simply displays a message in a Div if today falls on one of the holidays.

    $(function () {
    var d = new Date();
    var year = d.getYear();
    var shortDay = (d.toDateString()).slice(4, 10);
    var query = "select entry.title.content, entry.summary.content from xml where url='http://www.google.com/calendar/feeds/en.usa%23holiday%40group.v.calendar.google.com/public/basic' AND entry.content.content LIKE '%" + year + "%'";
    $.getJSON(
    "http://query.yahooapis.com/v1/public/yql?q=" + encodeURIComponent(query) + "&format=json&callback=?",
    function (data) {
    $.each(data.query.results,
    function (index, item) {
    for (i = 0; i < item.length; i++) {
    var each = item[i];
    var date = ((each.entry.summary).slice(9, 16).replace(',', ''));
    if (jQuery.trim(date) == jQuery.trim(shortDay)) {
    $('<h6></h6>').html('Today is ' + each.entry.title + '!').appendTo('#holidays');
    }
    }
    });
    });
    });

    You can feel free to download this script if you would like to use it.

    http://www.joshuablackstone.com/Scripts/HappyHolidays.js.

    Friday, June 4, 2010

    Using YQL and Google Translate to Translate Text

    Had a little time to play, so I wanted to see what I could do to internationalize (I think that's a word :) ) my site. I noticed in YQL there was a GoogleTranslate Table, so after some trial and error, found out that with:

    select * from json where url='http://www.google.com/uds/Gtranslate?context=22&langpair=%7C" + lang + "&v=1.0&q=" + encodeURIComponent(str) + "'

    with the variables being, of course, lang for language symbol (i.e. en for english, de for dutch, etc.) and str for Text String to be translated. Plug that into a YQL Json function and you're set, well, almost...

    Why not also scrape the items from the Google Site to use for a Combo Box to select a language from? If you go to: http://translate.google.com, you will see a combo box next to TranslateInto. To Get the data from that, simply use this query as your JSON String:

    http://query.yahooapis.com/v1/public/yql?q=select%20option%20from%20html(0)%20where%20url%3D%22http%3A%2F%2Ftranslate.google.com%22%20and%0D%0A%20%20%20%20%20%20xpath%3D'%2F%2Fselect%5B%40class%3D%22tllangdropdown%22%5D'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=?

    Plug that into the YQL Console, and you will find that you can get the value and Content for items to plug into a combo box of your own.

    Finally, wire up the dropdown that was created with an event similar to:

    $("#DROPDOWNNAME").change(function () {
    translateText($(str).html(), this.value);
    });

    And you're all done.

    I realize this was a very brief explaination, but for the full script simply go to:

    http://www.joshuablackstone.com/Scripts/GTranslate.js.

    Thursday, May 20, 2010

    Access True Wildcard Form Search

    Needed to build a searchform in MS Access which will allow searching of one or multiple fields. I know that in Sql, this can be accomplished by using:

    SELECT * FROM Table where IsNull([ID],'') LIKE IsNull('%' + @ID + '%','%')

    However, Access doesn't recognize this as a valid statement, so back to the drawing board...

    Eventually I came up with this solution...

    IIf(IsNull([Forms]![Form]![Control]),[FieldName],LIKE "*" & [Forms]![Form]![Control] & "*")

    With Form being the Form name, and Control being the Control Name.

    In a nutshell, this is saying If IsNull(Form Control) Is True, i.e., If no value was put into the search form for this field, then simply show all items in that field. Otherwise, show all items that are LIKE (Wildcard Search) the search criteria.

    Hope this helps someone else...

    Friday, April 23, 2010

    YQL create states Dropdown List

    OK, a very simple one today.

    Using YQL's upcoming.state table, you can create a simple dropdown list to store either the State name or the State Abbreviation.

    HTML Page:

    Create a select element, and give it an id of ddlStates.

    The jQuery Script:

    $(function () {
    var query = "select code, name from upcoming.state where country_id = 1 and id <= 51";
    $.getJSON(
    "http://query.yahooapis.com/v1/public/yql?q=" + encodeURIComponent(query) + "&format=json&callback=?",
    function (data) {
    $.each(data.query.results,
    function (index, item) {
    for (i = 0; i < item.length; i++) {
    var each = item[i];
    var stateName = each.name.toUpperCase();
    var stateCode = each.code.toUpperCase();
    $('<option></option>').val(stateName).html(stateCode).appendTo("#ddlStates");
    }
    });
    });
    });

    You'll note here I simply changed it to Uppercase, and used the value of State Name, while displaying the state code.

    Download Script at: http://www.joshuablackstone.com/Scripts/StatesDropdown.js

    And all this time I was storing the data in a database... Ugh...

    Thursday, April 22, 2010

    Using YQL create Food Network Search

    More YQL, gotta love how easy they have made this!!

    I have found that Food Network can be quite good at making boring foods, well... not so boring. Wondered what it would take to search their system from another webpage. They don't have a feed for you, so what to do? YQL's html table...

    Go to the YQL Console, and enter:

    select h3 from html where url="http://www.foodnetwork.com/search/delegate.do?fnSearchString=FOODITEM&fnSearchType=site" and
    xpath='//div[@class="result-item"]'

    as your query. You'll notice it breaks it down to a simple array of h3 elements.
    From there, simply create an array and show the results in an unordered list.

    HTML Page:


    1. Add jQuery to your Page

    2. Create a textbox called txtSearch

    3. Create a button called btnSearch

    4. Create an unordered list called searchResults



    JS Code:

    function searchRecipes(search) {
    $('#searchResults').empty();
    $.getJSON(
    "http://query.yahooapis.com/v1/public/yql?q=select%20h3%20from%20html(5)%20where%20url%3D%22http%3A%2F%2Fwww.foodnetwork.com%2Fsearch%2Fdelegate.do%3FfnSearchString%3D" + search + "%26fnSearchType%3Dsite%22%20and%0D%0A%20%20%20%20%20%20xpath%3D'%2F%2Fdiv%5B%40class%3D%22result-item%22%5D'&format=json&callback=?",
    function (data) {
    $.each(data.query.results,
    function (index, item) {
    for (i = 0; i < item.length; i++) {
    var each = item[i];
    var link = (each.h3.a.href).replace('/', 'http://www.foodnetwork.com/');
    $('<li></li>').html('' + each.h3.a.content + '').appendTo('#searchResults');
    }
    });
    });
    }

    $("#btnSearch").click(function () {
    var searchText = document.getElementById('txtSearch').value;
    if (searchText == "") {
    alert('You must first enter a food to search!');
    }
    else {
    searchRecipes(searchText);
    }
    });

    There you have it. Enter a food to search in the textbox, click on btnSearch, and a list of recipes are found. Only returns 12, as that is how the site is setup, but its a nice basic example of yql page scraping...

    Oh, by the way, if you want a copy of the script, feel free to download at:

    http://www.joshuablackstone.com/Scripts/Searches/FoodNetwork.js

    Tuesday, March 16, 2010

    White Pages API Sample

    I was looking on the web, and found that there are few if any real samples available for the White Pages People and Reverse Number Searches.

    I've posted a simple example that has 2 search forms. The first one is a simple people search that takes the name and the zip code as parameters and displays the results below.

    The second search was simpler, as I simply ask for a 10 digit phone number and it displays the results found below as well. You can optionally pass a state code in place of the area code, but I figured i'd keep it simple for now.

    If anyone is interested in checking it out, there is source code and a working example available at:

    Sample with Source.

    Hope this helps someone out...

    Sunday, March 14, 2010

    NYTimes Json Feeds

    Just getting started at this, but I'm planning on working now with the New York Times JSON API that is provided.

    Looks like this is a very solid api, that allows for feeds from entertainment, to current Congress members, to much, much more...

    Just signed up for my membership and requested an API by going to: NY Times Registration

    A quick example that I just used for testing...

    $.getJSON(
    "http://api.nytimes.com/svc/news/v2/all/recent.json?api-key=XXX",
    function(data) {
    $.each(data.results,
    function(index, item) {
    var myItem = $("<ul></ul>");
    $("<li></li>").html(item.headline).appendTo(myItem)
    .wrap("<a target='_blank' href='" + item.url + "')></a>");
    myItem.appendTo("#results");
    });
    });
    });

    Send that to a div called 'results', and you're done.

    Sunday, March 7, 2010

    YQL Basic JSON Yahoo News Feed

    Just getting started with YQL and JSON Feeds, must say im impressed...

    A quick script to pull the top stories from yahoo news in a JSON Feed

    $.getJSON(
    "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20rss%20where%20url%3D%22http%3A%2F%2Frss.news.yahoo.com%2Frss%2Ftopstories%22&format=json&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json&callback?",
    function(data) {
    $.each(data.query.results.item,
    function(index, item) {
    var myItem = $("

    ");
    $("").html(item.title).attr("href", item.link).appendTo(myItem);
    $("
    ").appendTo(myItem);
    myItem.appendTo("#MYDIVID");
    });
    }
    );

    That's all it takes...

    Thursday, March 4, 2010

    Post Server Side without Postback

    I was reading from the following article:

    http://disturbedbuddha.wordpress.com/2008/01/08/executing-server-side-code-from-javascript/

    and realized that this opened up some possibilities for me. Hopefully it can for you as well.
    It discusses the use of combining both Javascript and Server-Side Code. I took his example a step further.
    Lets say that you want to validate a user form, but you don't want to have a postback to the server during the validation. Javascript would be the preference here, and it could look similar to the following:

    if
    (document.formname.elementname.value == "") {
    var results = document.getElementById('resultslabel');
    results.innerHTML = ("Please put in a name.");
    return false;
    }

    and the control to validate would simply be a standard html button:

    <input type=button onclick=formCheck(); value=Submit />

    However, let's say that you want to include a server-side event after the validation is complete. I tried first to simply add a onserverclick event handler to the button, but it posted back everytime regardless of the client status. I tried using an Update Panel, with a standard asp.net button control, same thing. This hack solved the trick. I added an ASP.NET Button, called it Button2, such as:

    <asp:Button ID=Button2 runat=server style=display:none; onclick=Button2_Click />
    (note the style tag...), and added a Server-side event handler to Button2.

    Now, simply add the line:

    document.getElementByID('Button2').click();

    after the if condition in your javascript code.
    Easier than I thought...

    JSON Flickr Feed from Username

    I needed to find a way to show flickr pictures for a Portal, and chose to hide the username in a hidden field to retrieve once it was given in registration. It's simple to use a JSON feed to retrieve a user's items if you know the User ID, but it's an extra step to acquire the User ID from the Username.

    Solution: the Flickr findByUsername function
    The first method requires a Flickr API Key. You can get this by going to: The App Garden. After you have signed up for an API, you can then proceed.

    First, in the body, I created a hidden field called 'flickrUsername'. Then, i created a div called 'photoResults' to house the data.

    Next, the jquery script:

    $(function(){

    var name = $('#hiddenFieldID');
    if (name == ""){
    $("#photoResults").html("Missing Flickr Username!");
    }
    else {
    var userID;
    $.getJSON("http://api.flickr.com/services/rest/?method=flickr.people.findByUsername&username=" + name + "&api_key=fa70b734cfb2cd4858f509230aba0328&format=json&jsoncallback=?", function(data) {
    userID = data.user.id;
    $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?id=" + userID + "&lang=en-us&format=json&jsoncallback=?", function(data) {
    $.each(data.items, function(i, item) {
    $("<img/>").attr("src", item.media.m).appendTo("#photoResults");
    });
    });
    });
    }

    This will then display an array of that particular user's images.