Date Util Class

 

Here I am going to post some common date utility functions.
These are most common functions which is required while playing with date Object
. fingerscrossed
1:  public class DateUtil    
2:  {     
3:  public static const millisecondsPerDay:int = 1000 * 60 * 60 * 24;    
4:  public static function parseDate(date:Date,dateFormat:String):String{   
5:      
6:      var fr:DateFormatter=new DateFormatter();   
7:      fr.formatString=dateFormat;   
8:      return fr.format(date);   
9:  }   
10:     
11:  public static function parseDateString(dateString:String):Date{   
12:      return new Date(Date.parse(dateString));   
13:  }   
14:     
15:     
16:  public static function compare (date1 : Date, date2 : Date) : Number{   
17:      var date1Timestamp : Number = date1.getTime ();   
18:      var date2Timestamp : Number = date2.getTime ();   
19:      var result : Number = -1;   
20:      if (date1Timestamp == date2Timestamp){    
21:         result = 0;   
22:      }  else if (date1Timestamp > date2Timestamp){   
23:         result = 1;   
24:      }   
25:     
26:      return result;   
27:  }   
28:     
29:  public static function getDaysDifference(startDate:Date,endDate:Date ):int {   
30:         var daysInMilliseconds:int = 1000*60*60*24;   
31:         return ( (endDate.time - startDate.time) / daysInMilliseconds );   
32:  }   
33:     
34:  public static function getDaysBetweenDates(date1:Date,date2:Date):int{   
35:        var count:int = 0;   
36:        if(date1 > date2) {   
37:        return count;   
38:  }   
39:  while(date1.toDateString() != date2.toDateString()){   
40:      date1 = addDays(date1,1);   
41:      //count only week days   
42:     if ( date1.day > 0 && date1.day < 6 ) {   
43:     count++;   
44:    }   
45:  }   
46:  return count;   
47:  }   
48:     
49:  // Add number of days in date   
50:  public static function addDays(date:Date,days:Number):Date{   
51:       if(date!=null){   
52:      var time:Number = date.getTime();   
53:      var offsetInMill:Number = days * millisecondsPerDay;   
54:      var newDate:Date = new Date();   
55:      newDate.setTime(time+offsetInMill);   
56:      return newDate;   
57:     }   
58:     return null;   
59:  }   
60:     
61:  // Subtract number of days in date   
62:  public static function subtractDays(date:Date,days:Number):Date{   
63:       if(date!=null){   
64:           var time:Number = date.getTime();   
65:           var offsetInMill:Number = days * millisecondsPerDay;   
66:           var newDate:Date = new Date();   
67:           newDate.setTime(time-offsetInMill);   
68:           return newDate;   
69:      }   
70:        return null;   
71:  }   
72:  // convert date object into string format separated by -   
73:  // dd-mm-yyyy   
74:  public static function convertDateToString(date:Date):String {   
75:     var month:Number = date.month + 1;   
76:     var dateString:String = date.date.toString() + '-'+month.toString()+'-'+date.fullYear.toString();   
77:     return dateString;   
78:  }   
79:     
80:  public static function daysInMonth(mon:Number):Number {   
81:      switch (mon) {   
82:      case 0:   
83:          return 31;   
84:      break;   
85:      case 1:   
86:          return 28;   
87:      break;   
88:      case 2:   
89:         return 31;   
90:      break;   
91:     case 3:   
92:        return 30;   
93:     break;   
94:    case 4:   
95:       return 31;   
96:    break;   
97:    case 5:   
98:       return 30;   
99:    break;  
100:    case 6:  
101:       return 31;  
102:    break;  
103:    case 7:  
104:        return 31;  
105:    break;  
106:    case 8:  
107:         return 30;  
108:    break;  
109:    case 9:  
110:        return 31;  
111:    break;  
112:    case 10:  
113:        return 30;  
114:    break;  
115:     case 11:  
116:         return 31;  
117:    break;  
118:   }  
119:       return 1;  
120:    }  
121:  } 














Server-side logging using BlazeDS API

  1. Configuring server-side logging

    Configure server-side logging in the logging section of the Flex services-config.xml configuration file. After you edit services-config.xml, restart the BlazeDS server.

    The following example shows a configuration that sets the logging level to Debug:

  2. <logging>
        <target class="flex.messaging.log.ConsoleTarget" level="Debug">
            <properties>
                <prefix>[BlazeDS]</prefix>
                <includeDate>true</includeDate>
                <includeTime>true</includeTime>
                <includeLevel>true</includeLevel>
                <includeCategory>true</includeCategory>
            </properties>
            <filters>
                <pattern>Endpoint.*</pattern>
                <pattern>Service.*</pattern>
                <pattern>Configuration</pattern>
  3.             <pattern>Client.*</pattern>
            </filters>
        </target>
    </logging>



The available levels include All, Debug, Error, Info, None, and Warn.



you can specify flex.messaging.log.ConsoleTarget (default) to log

messages to the standard output,or the flex.messaging.log.ServletLogTarget 
to log messages to the default logging mechanism for servlets for 
your application server.

 


  1. Thanks
  2. Neeraj

How to get session and httpheader info using BlazeDS

 BlazeDS api has flex.messaging.FlexContext utility class that exposes the current execution context on the BlazeDS server. It provides access to FlexSession and FlexClient instances associated with the current message being processed. It also provides global context by accessing MessageBroker, ServletContext, and ServletConfig instances.

The following example shows a Java class that calls FlexContext.getHttpRequest() to get an HTTPServletRequest object and calls FlexContext.getFlexSession() to get a FlexSession object.

 

import flex.messaging.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SessionRO {

public HttpServletRequest request;
public FlexSession session;

public SessionRO() {
request = FlexContext.getHttpRequest();
session = FlexContext.getFlexSession();
}

public String getSessionId() throws Exception {
String s = new String();
s = (String) session.getId();
return s;
}

public String getHeader(String h) throws Exception {
String s = new String();
s = (String) request.getHeader(h);
return h + "=" + s;
}
}



 




  1. Thanks


  2. Neeraj smile_regular

Export Datagrid to CVS/Excel

Althought we can export datagrid to Excel sheet using as3xls library, but if
datagrid column length is more then 256 character then it will get truncate.
so I deside to export in cvs formate.I have created custom AS class, to export
datagrid you have to create object of that class by passing datagrid id and
dataprovider as a contructor argument.and call createCSV()method.

package
{
import com.as3xls.xls.ExcelFile;
import com.as3xls.xls.Sheet;

import flash.events.*;
import flash.net.*;
import flash.utils.*;

import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.controls.DataGrid;
import mx.controls.dataGridClasses.DataGridColumn;

public class ExportToExcelorCVS
{
private var _grid:DataGrid;
private var _dataProvider:ArrayCollection;

public function ExportToExcelorCVS(grid_:DataGrid, dataProvider_:ArrayCollection)
{
_grid = grid_;
_dataProvider = dataProvider_;
}


protected function handleIOError(event:Event):void {
Alert.show("Cannot write to file.please make sure the file is closed", "Export Error");
}

public function createCSV(filename_:String = "export.csv"):void
{
var finalCSVString:String = "";
var csvLine:String = "";
var column:DataGridColumn;
var cellString:String = "";
var isCellExist:Boolean = false;
for each (column in _grid.columns) {
if (column.visible) {
cellString = column.headerText;
csvLine += (csvLine == "" ? "" : ",") + "\"" + cellString + "\"";
}
}
finalCSVString += (finalCSVString == "" ? "" : "\n") + csvLine;

for each(var rowItem:Object in _dataProvider)
{
csvLine = "";

for each (column in _grid.columns)
{
isCellExist = false;
if(column.visible)
{
if(column.dataField && rowItem.hasOwnProperty(column.dataField) && rowItem[column.dataField] != null)
{
cellString = rowItem[column.dataField];
isCellExist = true;

}
// add cell to row line
if(isCellExist){
csvLine += (csvLine == "" ? "" : ",") + "\"" + cellString + "\"";
}
}
}
finalCSVString += (finalCSVString == "" ? "" : "\n") + csvLine;
}

var csvBytes:ByteArray = new ByteArray();
csvBytes.writeUTFBytes(finalCSVString);

var csvFile:FileReference = new FileReference();
csvFile.addEventListener(IOErrorEvent.IO_ERROR, handleIOError);
csvFile.save(csvBytes,filename_);
}

}
}

Neeraj

Create SWF without “-service” compiler argument

I found many flex blazeDs Example on net.every example use -service complie time argument,where we have to pass service-config.xml file path.
basically using this file we are setting channels.
here you can find alternative way to set channels.

 

 

package com

{
     import mx.messaging.ChannelSet;
     import mx.messaging.channels.AMFChannel;
     import mx.messaging.channels.SecureAMFChannel;

     public class ChannelUtil
     {
           private static var myAmf:AMFChannel;
           private static var mySecureAmf:SecureAMFChannel;
           private static var myPollingAmf:AMFChannel;
           private static var myChannelSet:ChannelSet;

          public static function getChannelSet():ChannelSet{
          if(!myChannelSet){
                   myChannelSet = new ChannelSet();

                   myAmf = new AMFChannel();
                   myAmf.uri = "/webapp/messagebroker/amf";
                  
                  mySecureAmf = new SecureAMFChannel();
                  mySecureAmf.uri = "/webapp/messagebroker/amfsecure";

                  myPollingAmf = new AMFChannel();
                  myPollingAmf.pollingEnabled = true;
                  myPollingAmf.pollingInterval = 4;
                  myPollingAmf.uri = "/webapp/messagebroker/amfpolling";

                  

                  myChannelSet.addChannel(myAmf);
                  myChannelSet.addChannel(mySecureAmf);
                  myChannelSet.addChannel(myPollingAmf);
        }
       return myChannelSet;
    }
}
}

 

Remoteobject.channelSet = ChannelUtil.getChannelSet();

 

Neeraj

ProgressBar using TitleWindow popup

 

 

<?xml version="1.0" encoding="utf-8"?>
<mx:titlewindow title="Progressing .... " width="420" height="100" mx="http://www.adobe.com/2006/mxml" alpha="1" cornerradius="6" horizontalalign="center" verticalalign="middle">
                  <mx:progressbar width="360" height="20" indeterminate="true" trackheight="20" label="" barcolor="#326CB4"/>
</mx:titlewindow>

Steve Jobs: How to live before you die

At his Stanford University commencement speech, Steve Jobs, CEO and co-founder of Apple and Pixar, urges us to pursue our dreams and see the opportunities in life's setbacks -- including death itself

Steve Jobs: How to live before you die | Video on TED.com