Pages

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:

Thursday, January 12, 2012

Check if it is a valid AJAX request

public function is_ajax()
{
   return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == "XMLHttpRequest");
}

Further Reading:
Do all browsers support PHP's $_SERVER['HTTP_X_REQUESTED_WITH']?

Using CodeIgniter and MySQL Stored Procedure

  1. Create the Product object: Create a file under "application/libraries" named Lproduct.php
    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    class Lproduct {
        private $_id = "";
        private $_category = "";
        private $_category_id = "";
        private $_brand = "";
        private $_brand_id = "";
        private $_product_desc = "";
    
        public function get_id() {
            return $this->_id;
        }
    
        public function set_id($_id) {
            $this->_id = $_id;
        }
    
        public function get_category() {
            return $this->_category;
        }
    
        public function set_category($_category) {
            $this->_category = $_category;
        }
    
        public function get_category_id() {
            return $this->_category_id;
        }
    
        public function set_category_id($_category_id) {
            $this->_category_id = $_category_id;
        }
    
        public function get_brand() {
            return $this->_brand;
        }
    
        public function set_brand($_brand) {
            $this->_brand = $_brand;
        }
    
        public function get_brand_id() {
            return $this->_brand_id;
        }
    
        public function set_brand_id($_brand_id) {
            $this->_brand_id = $_brand_id;
        }
    
        public function get_product_desc() {
            return $this->_product_desc;
        }
    
        public function set_product_desc($_product_desc) {
            $this->_product_desc = $_product_desc;
        }
    }
    
  2. Create the Model: Create a file under "application/models" named mproduct.php
    <?php
    class Mproduct extends CI_Model {
    
        private $_product = null;
    
        public function set_product(Lproduct $product)
        {
            $result = FALSE;
    
            $temp = $product->get_id();
            if ( empty($temp) )
            {
                $data = array(
                    $product->get_product_desc(),
                    $product->get_category_id(),
                    $product->get_brand_id()
                );
    
                try
                {
                    // fix for multi-calls
                    $this->db->reconnect();
    
                    // call the stored procedure
                    $this->db->query("CALL addProduct(?,?,?,@pProdId)", $data);
                    
                    // get the stored procedure returned output
                    $query = $this->db->query('SELECT @pProdId AS product_id');
                    $row = $query->row();
                    if(!empty($row->product_id))
                    {
                        $result = TRUE;
                    }
                }
                catch ( Exception $error_string )
                {
    
                }
            }
            else
            {
                $data = array(
                    $product->get_id(),
                    $product->get_product_desc(),
                    $product->get_category_id(),
                    $product->get_brand_id()
                );
    
                try
                {
                    // fix for multi-calls
                    $this->db->reconnect();
    
                    // call the stored procedure
                    $this->db->query("CALL updateProduct(?,?,?,?,@pResult)", $data);
    
                    // get the stored procedure returned output
                    $query = $this->db->query('SELECT @pResult AS result');
                    $row = $query->row();
                    if(!empty($row->result))
                    {
                        $result = TRUE;
                    }
                }
                catch ( Exception $error_string )
                {
    
                }
            }
    
            $this->_product = $product;
    
            return $result;
        }
    }
    

Monday, January 9, 2012

ArrayList to String

Create the sample data:
ArrayList arrLst = new ArrayList();

string strCommaDelimited = "";

for(int x=0; x<5; x++)
{
arrLst.Add(x);
}


Convert ArrayList to String Array:
string[] tmpStringArray = (string[])arrLst.ToArray(typeof(string));


Convert String Array created to String:
strCommaDelimited = String.Join(",", tmpStringArray);