1.09.2012

C# String Formatting


This example shows how to format DateTime using String.Format method. All formatting can be done also using DateTime.ToString method.

Custom DateTime Formatting
There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed),t (P.M or A.M) and z (time zone).
Following examples demonstrate how are the format specifiers rewritten to the output.
[C#]
// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone

You can use also date separator / (slash) and time sepatator : (colon). These characters will be rewritten to characters defined in the current DateTimeForma­tInfo.DateSepa­rator andDateTimeForma­tInfo.TimeSepa­rator.
[C#]
// date separator in german culture is "." (so "/" changes to ".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE)

Here are some examples of custom date and time formatting:
[C#]
// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt);            // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt);    // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt);  // "Sunday, March 9, 2008"

// two/four digit year
String.Format("{0:MM/dd/yy}", dt);            // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"

Standard DateTime Formatting

In DateTimeForma­tInfo there are defined standard patterns for the current culture. For example property ShortTimePattern is string that contains value h:mm tt for en-US culture and value HH:mm for de-DE culture.
Following table shows patterns defined in DateTimeForma­tInfo and their values for en-US culture. First column contains format specifiers for the String.Format method.
SpecifierDateTimeFormatInfo propertyPattern value (for en-US culture)
tShortTimePatternh:mm tt
dShortDatePatternM/d/yyyy
TLongTimePatternh:mm:ss tt
DLongDatePatterndddd, MMMM dd, yyyy
f(combination of D and t)dddd, MMMM dd, yyyy h:mm tt
FFullDateTimePatterndddd, MMMM dd, yyyy h:mm:ss tt
g(combination of d and t)M/d/yyyy h:mm tt
G(combination of d and T)M/d/yyyy h:mm:ss tt
mMMonthDayPatternMMMM dd
yYYearMonthPatternMMMM, yyyy
rRRFC1123Patternddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
sSortableDateTi­mePatternyyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
uUniversalSorta­bleDateTimePat­ternyyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
  (*) = culture independent
Following examples show usage of standard format specifiers in String.Format method and the resulting output.
[C#]
String.Format("{0:t}", dt);  // "4:05 PM"                         ShortTime
String.Format("{0:d}", dt);  // "3/9/2008"                        ShortDate
String.Format("{0:T}", dt);  // "4:05:07 PM"                      LongTime
String.Format("{0:D}", dt);  // "Sunday, March 09, 2008"          LongDate
String.Format("{0:f}", dt);  // "Sunday, March 09, 2008 4:05 PM"  LongDate+ShortTime
String.Format("{0:F}", dt);  // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt);  // "3/9/2008 4:05 PM"                ShortDate+ShortTime
String.Format("{0:G}", dt);  // "3/9/2008 4:05:07 PM"             ShortDate+LongTime
String.Format("{0:m}", dt);  // "March 09"                        MonthDay
String.Format("{0:y}", dt);  // "March, 2008"                     YearMonth
String.Format("{0:r}", dt);  // "Sun, 09 Mar 2008 16:05:07 GMT"   RFC1123
String.Format("{0:s}", dt);  // "2008-03-09T16:05:07"             SortableDateTime
String.Format("{0:u}", dt);  // "2008-03-09 16:05:07Z"            UniversalSortableDateTime

1.06.2012

Yii Caching example

In order to use caching in yii framework you need define in main.php file and choose type of caching. Here are some examples.

Normal data caching
  1. // data cache
  2. public function actionCache()
  3. {
  4.     $cache = Yii::app()->cache;
  5.     //get cache
  6.     $time = $cache->get('cache_key');
  7.     //if cache is gone.
  8.     if (false === $time){  
  9.       //set cache
  10.       $cache->set('cache_key',time(),30);
  11.       $time = $cache->get('cache_key');
  12.     }
  13.     echo $time;
  14. }


Fregment data caching
  1. // fregment data cache
  2. public function actionCache()
  3. {
  4.   if ($this->beginCache('cache_key',
  5.   array('duration'=>60,
  6.         'dependency'=>array(
  7.       'class'=>'system.caching.dependencies.CDbCacheDependency',//you must have db set here
  8.       'sql'=>'SELECT COUNT(*) FROM  `user`',//you must have db set here
  9.   ),
  10.   'varyByParam'=>array('id'),//cache by $_GET['id']
  11.   ))){
  12.       echo 'cache_key'.time();
  13.       echo @$_GET['id'];
  14.       echo ' <hr /> ';
  15.       $this->endCache();
  16.   }
  17. }


Page Cache
  1. public function filters()
  2. {
  3.     return array(
  4.         array('COutputCache + PageCache', 'duration'=>30,'varyByParam'=>array('id')),
  5.     );
  6. }
  7. public function actionCache()
  8. {
  9.     $this->render('pageCache');
  10. }

It's easy to use, just to be a bit change. More about yii caching visit this: http://www.yiiframework.com/doc/guide/1.1/en/caching.overview

Android ListAdapter example


If you want to use a ListView, you will have to supply it with a ListAdapter to allow it to display any content. A few simple implementations of that adapter are already available in the SDK:
These implementations are perfect for displaying very simple lists. But if your list is just a little more complicated than that, you will need to write your own custom ListAdapter implementation. In most cases it's useful to subclass ArrayAdapter which already takes care of managing a list of objects. Now you only have to tell it how to render each object in the list. Do this by overriding thegetView(int, View, ViewGroup) method of the ArrayAdapter class.
Example of a ListView containing Youtube search results in the form of images and text
The images need to be on-the-fly downloaded from the internet. Let's create a class which represents items in the list:

  1. public class ImageAndText {
  2.     private String imageUrl;
  3.     private String text;
  4.     public ImageAndText(String imageUrl, String text) {
  5.         this.imageUrl = imageUrl;
  6.         this.text = text;
  7.     }
  8.     public String getImageUrl() {
  9.         return imageUrl;
  10.     }
  11.     public String getText() {
  12.         return text;
  13.     }
  14. }

Now, let's create an implementation of a ListAdapter that is able to display a list of these ImageAndTexts.

  1. public class ImageAndTextListAdapter extends ArrayAdapter<ImageAndText> {
  2.     public ImageAndTextListAdapter(Activity activity, List<ImageAndText> imageAndTexts) {
  3.         super(activity, 0, imageAndTexts);
  4.     }
  5.     @Override
  6.     public View getView(int position, View convertView, ViewGroup parent) {
  7.         Activity activity = (Activity) getContext();
  8.         LayoutInflater inflater = activity.getLayoutInflater();
  9.         // Inflate the views from XML
  10.         View rowView = inflater.inflate(R.layout.image_and_text_row, null);
  11.         ImageAndText imageAndText = getItem(position);
  12.         // Load the image and set it on the ImageView
  13.         ImageView imageView = (ImageView) rowView.findViewById(R.id.image);
  14.         imageView.setImageDrawable(loadImageFromUrl(imageAndText.getImageUrl()));
  15.         // Set the text on the TextView
  16.         TextView textView = (TextView) rowView.findViewById(R.id.text);
  17.         textView.setText(imageAndText.getText());
  18.         return rowView;
  19.     }
  20.     public static Drawable loadImageFromUrl(String url) {
  21.         InputStream inputStream;
  22.         try {
  23.             inputStream = new URL(url).openStream();
  24.         } catch (IOException e) {
  25.             throw new RuntimeException(e);
  26.         }
  27.         return Drawable.createFromStream(inputStream, "src");
  28.     }
  29. }

The views are inflated from an XML file called "image_and_text_row.xml":

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.              android:orientation="horizontal"
  4.              android:layout_width="fill_parent"
  5.              android:layout_height="wrap_content">
  6.         <ImageView android:id="@+id/image"
  7.                   android:layout_width="wrap_content"
  8.                   android:layout_height="wrap_content"
  9.                   android:src="@drawable/default_image"/>
  10.         <TextView android:id="@+id/text"
  11.                  android:layout_width="wrap_content"
  12.                  android:layout_height="wrap_content"/>
  13. </LinearLayout>

This ListAdapter implementation renders the Image And Texts in the ListView like you would expect. The only thing is that this only works for a very small list which doesn't require scrolling to see all items. If the list of ImageAndTexts gets bigger you will notice that scrolling isn't as smooth as it should be (in fact, it's far off!).

1.03.2012

Using ViewFlipper in Android App

Suppose you want to display a news bar in your activity. this news bar displays a single news item at a time then flips and shows next item and so on, then your choice would be Android's ViewFlipper.

ViewFlipper inherits from frame layout, so it displays a single view at a time.
consider this layout:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.    android:orientation="vertical"
  4.    android:layout_width="fill_parent"
  5.    android:layout_height="fill_parent"
  6.    >
  7. <TextView
  8.    android:layout_width="fill_parent"
  9.    android:layout_height="wrap_content"
  10.    android:text="@string/hello"/>
  11.     <Button
  12.    android:layout_width="wrap_content"
  13.    android:layout_height="wrap_content"
  14.    android:text="Flip"
  15.    android:id="@+id/btn"
  16.    android:onClick="ClickHandler"/>
  17.     <ViewFlipper
  18.    android:layout_width="fill_parent"
  19.    android:layout_height="fill_parent"
  20.    android:id="@+id/flip">
  21.     <TextView
  22.    android:layout_width="fill_parent"
  23.    android:layout_height="wrap_content"
  24.    android:text="Item1"/>
  25.     <TextView
  26.    android:layout_width="fill_parent"
  27.    android:layout_height="wrap_content"
  28.    android:text="Item2"/>
  29.     <TextView
  30.    android:layout_width="fill_parent"
  31.    android:layout_height="wrap_content"
  32.    android:text="Item3"/>
  33.     </ViewFlipper>
  34. </LinearLayout>


Just a ViewFlipper container that contains three text views

Now we want to flip the views when the button is clicked.

  1. public void onCreate(Bundle savedInstanceState) {
  2.     super.onCreate(savedInstanceState);
  3.     setContentView(R.layout.main);
  4.     btn=(Button)findViewById(R.id.btn);
  5.     flip=(ViewFlipper)findViewById(R.id.flip);
  6. }
  7. public void ClickHandler(View v)
  8. {
  9.     flip.showNext();
  10. }


If we want to flip in reverese direction we could use flip.showPrevious() instead. If you want to flip to a specific view do the following: flip.setDisplayedChild(indexOfView) replace indexOfView with the integer representing the index of the view you want to switch to.

We can add animations to the child views when they appear or disappear:
  1. public void onCreate(Bundle savedInstanceState) {
  2.     super.onCreate(savedInstanceState);
  3.     setContentView(R.layout.main);
  4.     btn=(Button)findViewById(R.id.btn);
  5.     flip=(ViewFlipper)findViewById(R.id.flip);
  6.     //when a view is displayed
  7.     flip.setInAnimation(this,android.R.anim.fade_in);
  8.     //when a view disappears
  9.     flip.setOutAnimation(this, android.R.anim.fade_out);
  10. }

We can also set the ViewFlipper to flip views automatically when the button is clicked:

  1. public void ClickHandler(View v)
  2. {
  3.     //specify flipping interval
  4.     flip.setFlipInterval(1000);
  5.     flip.startFlipping();
  6. }

We can stop the flipping by calling flip.stopFlipping(); method or we can set the flipper to flip autommatically when the activity starts by changing our code.

  1. public void onCreate(Bundle savedInstanceState) {
  2.     super.onCreate(savedInstanceState);
  3.     setContentView(R.layout.main);
  4.     btn=(Button)findViewById(R.id.btn);
  5.     flip=(ViewFlipper)findViewById(R.id.flip);
  6.     flip.setInAnimation(this,android.R.anim.fade_in);
  7.     flip.setOutAnimation(this, android.R.anim.fade_out);
  8.     flip.setFlipInterval(1000);
  9.     flip.setAutoStart(true);    
  10. }

More about this control you can read by this url: http://developer.android.com/reference/android/widget/ViewFlipper.html