Pages

Thursday, December 13, 2012

Using dhtmlx scheduler w/ jQuery and C# webservice (asmx)

Include all needed css and js files:

<link href="../css/dhtmlxscheduler.css" rel="Stylesheet" type="text/css" media="screen" />

<script src="../js/dhtmlxscheduler.js" type="text/javascript"></script>
<script src="../js/dhtmlxscheduler_timeline.js" type="text/javascript"></script>
<script src="../js/dhtmlxscheduler_all_timed.js" type="text/javascript"></script>
<script src="../js/dhtmlxscheduler_tooltip.js" type="text/javascript"></script>
<script src="../js/dhtmlxscheduler_active_links.js" type="text/javascript"></script>

CSS for dhtmlxscheduler:
/* ######### css for dhtmlxscheduler (required) ######### */    
  html, body{
    margin:0px;
    padding:0px;
    height:100%;
    overflow:hidden;
  } 
  .white_cell{
    background-color:white;
  }
  .green_cell{
    background-color:#95FF95;
  }
  .yellow_cell{
    background-color:#FFFF79;
  }
  .red_cell{
    background-color:#FF5353;
  }
 
  /* tooltip (dhtmlxscheduler extenstion) */
  .one_line{
    white-space:nowrap;
    overflow:hidden;
    padding-top:5px; padding-left:5px;
    text-align:left !important;
  }

JS for displaying data:
$(document).ready(function() {
  /* ######### dhtmlxscheduler config ######### */
  scheduler.config.start_on_monday = false;
  scheduler.config.multi_day = true;
  scheduler.locale.labels.timeline_tab = "Timeline";
  scheduler.locale.labels.section_custom = "Section";
  scheduler.config.details_on_create = true;
  scheduler.config.details_on_dblclick = true;
  scheduler.config.xml_date = "%n/%d/%Y %H:%i";
  scheduler.config.readonly_form = true;
  scheduler.config.readonly = true;
  scheduler.config.show_loading = true;
  scheduler.config.all_timed = "short"; // only events < 24 hours will be displayed as usual ones

  /* ######### tooltip ######### */
  scheduler.templates.tooltip_date_format = scheduler.date.date_to_str("%n/%d/%Y %H:%i");
  scheduler.templates.tooltip_text = function(start, end, event) {
    var tooltipTxt = "<b>Ref #:</b> " + event.RefNo + "<br/>";                
        tooltipTxt += "<b>Title:</b> " + event.Title + "<br/>";
        tooltipTxt += "<b>Start Date:</b> " +  scheduler.templates.tooltip_date_format(start) + "<br/>";
        tooltipTxt += "<b>End Date:</b> " + scheduler.templates.tooltip_date_format(end) + "<br/>";

    return tooltipTxt;
  };

  /* ######### custom css per event ######### */
  scheduler.templates.event_class = function(start, end, event) {
    return event.CssClass; // CssClass is an event property
  };

  /* ######### custom behavior when clicking an event ######### */
  scheduler.attachEvent("onClick", function(event_id, native_event_object) {
    window.open(scheduler.getEvent(event_id).URL);
  });

  scheduler.init("scheduler_here", null, "month");

  /* ######### load data from web service (initial) ######### */
  $.ajax({
    type: "GET",
    url: "Your_WebService.asmx/GetData",
    dataType: 'json', // datatype returned by the webservice
    contentType: "application/json; charset=utf-8",
    data: {
      selectedYear: "'" + scheduler.getState().date.getFullYear() + "'", // the year displayed by the calendar
      selectedMonth: "'" + scheduler.getState().date.getMonth()+ "'" // the month displayed by the calendar
    },
    success: function(doc) {
      scheduler.parse(doc.d, "json");
    }
  });

  /* ######### load data from web service (on view change) ######### */
  scheduler.attachEvent("onViewChange", function(mode, date) {
    $.ajax({
      type: "GET",
      url: "Your_WebService.asmx/GetData",
      dataType: 'json', // datatype returned by the webservice
      contentType: "application/json; charset=utf-8",
      data: {
        selectedYear: "'" + date.getFullYear() + "'", // the year displayed by the calendar
        selectedMonth: "'" + date.getMonth()+ "'" // the month displayed by the calendar
      },
      success: function(doc) {
        scheduler.clearAll(); // clear all data and then load new data
        scheduler.parse(doc.d, "json");      
      }
    });
  });
});

HTML for dhtmlxscheduler:
<div id="scheduler_here" class="dhx_cal_container" style="width:100%; height:100%;">
  <div class="dhx_cal_navline">
    <div class="dhx_cal_prev_button">&nbsp;</div>
    <div class="dhx_cal_next_button">&nbsp;</div>
    <div class="dhx_cal_today_button"></div>
    <div class="dhx_cal_date"></div>   
 
    <div class="dhx_cal_tab" name="day_tab" style="right:204px;"></div>
    <div class="dhx_cal_tab" name="week_tab" style="right:140px;"></div>
    <div class="dhx_cal_tab" name="timeline_tab" style="right:280px;"></div>
    <div class="dhx_cal_tab" name="month_tab" style="right:76px;"></div>
  </div>
  
  <div class="dhx_cal_header"></div>
  <div class="dhx_cal_data"></div>  
</div>

(Web service) Struct for event:
public struct MyEvent
{
  public string Id;
  public string RefNo;
  public string text; // (fixed) naming convention to be used by dhtmlxscheduler
  public string CssClass;
  public string start_date; // (fixed) naming convention to be used by dhtmlxscheduler
  public string end_date; // (fixed) naming convention to be used by dhtmlxscheduler
  public string URL;
  public string Title;
}

(Web service) Return list of events:
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
[WebMethod(Description = "Return Events.")]
public List<MyEvent> GetData(string selectedMonth, string selectedYear)
{
  List<MyEvent> calendarEvents = new List<MyEvent>();

  // sample of single event to return
  MyEvent calendarEventDetails = new MyEvent();
  calendarEventDetails.Id = "1";
  calendarEventDetails.RefNo = "#1";
  calendarEventDetails.text = "Sample Event";
  calendarEventDetails.CssClass = "myCssClass";
  calendarEventDetails.start_date = "12/12/2012 12:12";
  calendarEventDetails.end_date = "12/21/2012 12:12";
  calendarEventDetails.URL = "ViewPage.aspx?Id=" + calendarEventDetails.Id;
  calendarEventDetails.Title = "Sample Event Title";

  // add to list
  calendarEvents.Add(calendarEventDetails);

  // return list
  return calendarEvents;
}

Know more about DHTMLX Scheduler

Tuesday, October 16, 2012

Make a TextBox 'ReadOnly'

TxtBxRemarks.Attributes.Add("readonly", "readonly");

Wednesday, September 12, 2012

Using jQuery FullCalendar and C# .NET (JSON)

Create a web service that will supply the data to the jQuery FullCalendar

On the web service, create a 'calendar' object
public class CalendarEvent
{
  public string Id;
  public string Title;
  public string StartDate;
  public string EndDate;
}

Create the web service method that will supply the data
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
[WebMethod(Description = "Return Calendar Events")]
public List GetCalendarEvents()
{
  List calendarEvents = new List();
  
  // get data from the database
  businessclass biz = new businessclass();  
  SqlDataReader sqlReaderCalendarEvents = biz.ReturnAllActivities();

  if (sqlReaderCalendarEvents.HasRows)
  {
    while (sqlReaderCalendarEvents.Read())
    {
      CalendarEvent calendarEventDetails= new CalendarEvent();
      
      calendarEventDetails.Id = sqlReaderCalendarEvents.GetInt32(sqlReaderCalendarEvents.GetOrdinal("RequestID")).ToString();
      calendarEventDetails.Title = Server.HtmlDecode(sqlReaderCalendarEvents.GetString(sqlReaderCalendarEvents.GetOrdinal("Title")));
              
      calendarEventDetails.StartDate = sqlReaderCalendarEvents.GetString(sqlReaderCalendarEvents.GetOrdinal("ActivityStartDate"));
      calendarEventDetails.EndDate = sqlReaderCalendarEvents.GetString(sqlReaderCalendarEvents.GetOrdinal("ActivityEndDate"));
      // add the 'calendar' object to the list of 'CalendarEvent' object
      calendarEvents.Add(calendarEventDetails);
    }
  }

  sqlReaderCalendarEvents.Close();

  // return the list of 'CalendarEvent' object
  return calendarEvents;
}

On your fullcalendar object, call the web service
$('#calendar').fullCalendar({
  events: function(start, end, callback) {
    $.ajax({
      type: "GET",                        
      url: "WebService.asmx/GetCalendarEvents",
      dataType: 'json', // datatype returned by the webservice
      contentType: "application/json; charset=utf-8",
      data: {
        // requires UNIX timestamps
        start: Math.round(start.getTime() / 1000),
        end: Math.round(end.getTime() / 1000)
      },                        
      success: function(doc) {
        var events = [];

        // loop through each event and make an array of events
        $.each(doc.d, function(index, calendarEventItem) {                    
          events.push({
            title: calendarEventItem.Title,
            start: calendarEventItem.StartDate,
            end: calendarEventItem.EndDate,
            className: calendarEventItem.CssClass,
            url: calendarEventItem.URL
          });
        });

        callback(events);
      }
    });
  }
}); 

Thursday, August 30, 2012

Fix for 401 errors when getting data via C# webservice for AJAX

Application wide:
In your web.config, add the following lines.
<system.web>
  <webServices>
    <protocols>
      <add name="HttpGet" />
      <add name="HttpPost" />
    </protocols>
  </webServices>
</system.web>

Code level:
Add the following before your webservice method.
[ScriptMethod(UseHttpGet = true)]

Example:
[ScriptMethod(UseHttpGet = true)]
[WebMethod(Description = "webservice description.")]
public List GetItems()
{
  // more codes
}

Friday, August 3, 2012

Get the quotient using addition and subtraction only.

private string getQuotient(int dividend, int divisor)
{
  string result = "";
  int wholeNumber = 0;
            
  // loop until the dividend will result a positive integer
  while ((dividend > 0) && (dividend >= divisor))
  {
    dividend -= divisor;
    wholeNumber++;
  }

  result = wholeNumber.ToString() + " r. " + dividend.ToString();
            
  return result;
}

Tuesday, July 24, 2012

Using jQuery FullCalendar and C# .NET (XML)

Create a web service that will supply the data to the jQuery FullCalendar

On the web service, create a 'calendar' object
public class CalendarEvent
{
  public string Id;
  public string Title;
  public string StartDate;
  public string EndDate;
}

Create the web service method that will supply the data
[WebMethod(Description = "Return Calendar Events")]
public List GetCalendarEvents()
{
  List calendarEvents = new List();
  
  // get data from the database
  businessclass biz = new businessclass();  
  SqlDataReader sqlReaderCalendarEvents = biz.ReturnAllActivities();

  if (sqlReaderCalendarEvents.HasRows)
  {
    while (sqlReaderCalendarEvents.Read())
    {
      CalendarEvent calendarEventDetails= new CalendarEvent();
      
      calendarEventDetails.Id = sqlReaderCalendarEvents.GetInt32(sqlReaderCalendarEvents.GetOrdinal("RequestID")).ToString();
      calendarEventDetails.Title = Server.HtmlDecode(sqlReaderCalendarEvents.GetString(sqlReaderCalendarEvents.GetOrdinal("Title")));
              
      calendarEventDetails.StartDate = sqlReaderCalendarEvents.GetString(sqlReaderCalendarEvents.GetOrdinal("ActivityStartDate"));
      calendarEventDetails.EndDate = sqlReaderCalendarEvents.GetString(sqlReaderCalendarEvents.GetOrdinal("ActivityEndDate"));
      // add the 'calendar' object to the list of 'CalendarEvent' object
      calendarEvents.Add(calendarEventDetails);
    }
  }

  sqlReaderCalendarEvents.Close();

  // return the list of 'CalendarEvent' object
  return calendarEvents;
}

On your fullcalendar object, call the web service
$('#calendar').fullCalendar({
  events: function(start, end, callback) {
    $.ajax({
      type: "POST",                        
      url: "WebService.asmx/GetCalendarEvents",
      dataType: 'xml', // datatype returned by the webservice
      data: {
        // requires UNIX timestamps
        start: Math.round(start.getTime() / 1000),
        end: Math.round(end.getTime() / 1000)
      },                        
      success: function(doc) {
        var events = [];

        // loop through each event in the xml and make an array of events
        $(doc).find('CalendarEvent').each(function(index) {
          events.push({
            title: $(this).find("Title").text(),
            start: $(this).find("StartDate").text(),
            end: $(this).find("EndDate").text()
          });
        });                            

        callback(events);
      }
    });
  }
}); 

Friday, January 13, 2012

Simple Calendar

Set-up the variables:
<?php
  $monthNames = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); 

  if (!isset($_REQUEST["year"])) { 
    $_REQUEST["year"]  = date("Y"); 
  }
  
  $cYear  = $_REQUEST["year"];
               
  $prev_year = $cYear - 1;  
  $next_year = $cYear + 1;

  // list the holidays
  $holidays = array(
    array(1,23),    // jan
    array(),        // feb
    array(),        // march
    array(5,6,9),   // apr
    array(1),       // may
    array(12),      // june
    array(),        // july
    array(21,27),   // aug
    array(),        // sept
    array(),        // oct
    array(1,2,30),  // nov
    array(25,30,31) // dec
  );
?>

Create the calendar:
<div style="text-align:center;">
   <table style="width:848px; margin-left:auto; margin-right:auto;">
   <tr>
      <td style="text-align:left; width:33.3%">
         <a href="<?php echo $_SERVER["PHP_SELF"] . "?year=" . $prev_year; ?>">Previous</a>
      </td>
      <td style="text-align:center; width:33.4%">
         <strong><?php echo $cYear; ?></strong>
      </td>
      <td style="text-align:right; width:33.3%">
         <a href="<?php echo $_SERVER["PHP_SELF"] . "?year=" . $next_year; ?>">Next</a>
      </td>
   </tr>
   </table>   
   
   <div style="width:848px; height:696px; margin-left:auto; margin-right:auto;">   
   <?php  
      $ctr = 1;
     
      foreach($monthNames as $monthName)
      {
   ?>
         <div id="calendar_div" name="calendar_div" style="float:left; border:solid 1px #000; height:230px;">
         <table style="width:210px;">
            <tr>
               <td align="center">
                 <table width="100%" border="0" cellpadding="2" cellspacing="2">
                  <tr align="center">
                    <td colspan="7" style="color:#fff; background-color:#999;"><strong><?php echo $monthName; ?></strong></td>
                  </tr>
                  <tr>
                    <td style="color:#fff; background-color:#999; text-align:center;"><strong>S</strong></td>
                    <td style="color:#fff; background-color:#999; text-align:center;"><strong>M</strong></td>
                    <td style="color:#fff; background-color:#999; text-align:center;"><strong>T</strong></td>
                    <td style="color:#fff; background-color:#999; text-align:center;"><strong>W</strong></td>
                    <td style="color:#fff; background-color:#999; text-align:center;"><strong>T</strong></td>
                    <td style="color:#fff; background-color:#999; text-align:center;"><strong>F</strong></td>
                    <td style="color:#fff; background-color:#999; text-align:center;"><strong>S</strong></td>
                  </tr>

                  <?php
                     // The mktime() function returns the Unix timestamp for a date
                     // syntax: mktime(hour,minute,second,month,day,year,is_dst) 
                     $timestamp = mktime(0,0,0,$ctr,1,$cYear);
                     
                     // formats a local time/date
                     // syntax: date(format,timestamp) 
                     $maxday    = date("t",$timestamp);
                     
                     // returns an array that contains date and time information for a Unix timestamp
                     // syntax: getdate(timestamp)                  
                     $thismonth = getdate ($timestamp);               
                     
                     // The returning array contains ten elements with relevant information needed when formatting a date string:
                     // [seconds] - seconds
                     // [minutes] - minutes
                     // [hours] - hours
                     // [mday] - day of the month
                     // [wday] - day of the week
                     // [year] - year
                     // [yday] - day of the year
                     // [weekday] - name of the weekday
                     // [month] - name of the month                  
                     $startday  = $thismonth['wday'];

                     for ($i=0; $i<($maxday+$startday); $i++) {      
                     
                        // highlight the days that are "holidays"
                        if(in_array(($i - $startday + 1),$holidays[$ctr-1])) {
                           $str = "style='background-color: red; color: #fff;'";
                        }
                        else{
                           $str = "";
                        }
                       
                        // check if is the start of the week, if yes, create new row
                        if(($i % 7) == 0 ) {
                           echo "<tr>\n";
                        }
                        
                        if($i < $startday) {
                           echo "<td></td>\n";
                        }
                        else{
                           echo "<td align='center' valign='middle' height='20px' $str>". ($i - $startday + 1) . "</td>\n";
                        }
                        
                        if(($i % 7) == 6 ){ 
                           echo "</tr>\n";
                        }
                     }  
                   ?>
                 </table>
               </td>
            </tr>
         </table>
         </div>
   <?php 
         $ctr++; 
      } 
   ?>
   <br style="clear: both;" />
   </div>   
</div> 

Preview:


Attached Files:

Further reading: