Friday, December 31, 2010

New Year Eve : 2011

Wish you happy new year to you and your family. Hope you all have a wonderful and loving year. Welcome to Year 2011.

Thursday, December 30, 2010

Skype Adds Video Calling to iPhones, iPad, iPod touch

Skype today announced that the new version of its iPhone application adds video call support, allowing users to make video calls over 3G and Wi-Fi networks. This means that users of the iPhone, iPad, and iPod touch are now able to make and/or receive free video calls with one another, as well as with anyone else running Skype software that supports video calling.

Silverlight Programming: RadComboBox Virtualization

Telerik RadControls' API gives you the ability to configure the RadComboBox to support virtualization, which reduces the memory footprint of the application and speeds up the loading time thus enhancing additionally the UI performance. Some times its required to load thousands of items in a RadComboBox. By default the control creates RadComboBoxItem containers for each data item, so it might take some time to open the drop-down. To resolve the problem you just have to change the RadComboBox's ItemsPanel with VirtualizingStackPanel:

Here is the snippet of code block

<telerik:RadComboBox HorizontalAlignment="Left" TextSearchMode="StartsWith"
IsFilteringEnabled="True" OpenDropDownOnFocus="True" Width="200" 
IsEditable="True" IsDropDownOpen="False" Name="AccountDropDownList" 
SelectedValuePath="customer_number" DisplayMemberPath="customer_name" >
  <telerik:RadComboBox.ItemsPanel>
       <ItemsPanelTemplate>
        <VirtualizingStackPanel />
      </ItemsPanelTemplate>
  </telerik:RadComboBox.ItemsPanel>
</telerik:RadComboBox>

Hope this is useful Nerd smile

Silverlight Programming : “Operation not supported on read-only collection”

Recently when I was trying to bind data to a Combo box conditionally I got this message saying "Operation not supported on read-only collection". Though I am clearing items in the collection and binding the ItemsSource I got this error. So I have set ItemSource to null before I clear the items. It worked well for me. Here is the sample snippet for doing this.

CarrierAccountDropDownList.ItemsSource = null;
CarrierAccountDropDownList.Items.Clear();
CarrierAccountDropDownList.ItemsSource = e.Result;
Happy Coding Coffee cup

Tuesday, December 28, 2010

Working with the ASP.NET Global.asax file

The Global.asax file, sometimes called the ASP.NET application file, provides a way to respond to application or module level events in one central location. You can use this file to implement application security, as well as other tasks.

Overview

The Global.asax file is in the root application directory. While Visual Studio .NET automatically inserts it in all new ASP.NET projects, it's actually an optional file. It's okay to delete it—if you aren't using it. The .asax file extension signals that it's an application file rather than an ASP.NET file that uses aspx.

The Global.asax file is configured so that any direct HTTP request (via URL) is rejected automatically, so users cannot download or view its contents. The ASP.NET page framework recognizes automatically any changes that are made to the Global.asax file. The framework reboots the application, which includes closing all browser sessions, flushes all state information, and restarts the application domain.

 

Programming

The Global.asax file, which is derived from the HttpApplication class, maintains a pool of HttpApplication objects, and assigns them to applications as needed. The Global.asax file contains the following events:

  • Application_Init: Fired when an application initializes or is first called. It's invoked for all HttpApplication object instances.
  • Application_Disposed: Fired just before an application is destroyed. This is the ideal location for cleaning up previously used resources.
  • Application_Error: Fired when an unhandled exception is encountered within the application.
  • Application_Start: Fired when the first instance of the HttpApplication class is created. It allows you to create objects that are accessible by all HttpApplication instances.
  • Application_End: Fired when the last instance of an HttpApplication class is destroyed. It's fired only once during an application's lifetime.
  • Application_BeginRequest: Fired when an application request is received. It's the first event fired for a request, which is often a page request (URL) that a user enters.
  • Application_EndRequest: The last event fired for an application request.
  • Application_PreRequestHandlerExecute: Fired before the ASP.NET page framework begins executing an event handler like a page or Web service.
  • Application_PostRequestHandlerExecute: Fired when the ASP.NET page framework is finished executing an event handler.
  • Applcation_PreSendRequestHeaders: Fired before the ASP.NET page framework sends HTTP headers to a requesting client (browser).
  • Application_PreSendContent: Fired before the ASP.NET page framework sends content to a requesting client (browser).
  • Application_AcquireRequestState: Fired when the ASP.NET page framework gets the current state (Session state) related to the current request.
  • Application_ReleaseRequestState: Fired when the ASP.NET page framework completes execution of all event handlers. This results in all state modules to save their current state data.
  • Application_ResolveRequestCache: Fired when the ASP.NET page framework completes an authorization request. It allows caching modules to serve the request from the cache, thus bypassing handler execution.
  • Application_UpdateRequestCache: Fired when the ASP.NET page framework completes handler execution to allow caching modules to store responses to be used to handle subsequent requests.
  • Application_AuthenticateRequest: Fired when the security module has established the current user's identity as valid. At this point, the user's credentials have been validated.
  • Application_AuthorizeRequest: Fired when the security module has verified that a user can access resources.
  • Session_Start: Fired when a new user visits the application Web site.
  • Session_End: Fired when a user's session times out, ends, or they leave the application Web site.

The event list may seem daunting, but it can be useful in various circumstances.

A key issue with taking advantage of the events is knowing the order in which they're triggered. The Application_Init and Application_Start events are fired once when the application is first started. Likewise, the Application_Disposed and Application_End are only fired once when the application terminates. In addition, the session-based events (Session_Start and Session_End) are only used when users enter and leave the site. The remaining events deal with application requests, and they're triggered in the following order:

  • Application_BeginRequest
  • Application_AuthenticateRequest
  • Application_AuthorizeRequest
  • Application_ResolveRequestCache
  • Application_AcquireRequestState
  • Application_PreRequestHandlerExecute
  • Application_PreSendRequestHeaders
  • Application_PreSendRequestContent
  • {{{{code executed}}}}
  • Application_PostRequestHandlerExecute
  • Application_ReleaseRequestState
  • Application_UpdateRequestCache
  • Application_EndRequest

A common use of some of these events is for security. The Global.asax file is the central point for ASP.NET applications. It provides numerous events to handle various application-wide tasks such as user authentication, application start up, application error and dealing with user sessions etc. You should be familiar with this optional file to build robust ASP.NET-based applications.

Monday, December 27, 2010

Get Current Year, Month and Future date

declare @fdate datetime
set @fdate = '12/20/2012'
-- current month, current year, fut date
-- you can change the date param with your choice
SELECT CAST(CAST(DATEPART(MONTH,GETDATE()) as varchar(2))+ '-' 
 + CAST( DATEPART(DAY,@fdate) as varchar(2)) +'-' 
 + CAST( DATEPART(YEAR,GETDATE()) as varchar(4)) as datetime) as newdate

Wednesday, December 22, 2010

Facebook.NET

Facebook.NET provides a .net library for use in developing Facebook applications and accessing Facebook APIs. The library primarily geared around and optimized for developing ASP.NET-based Web applications, both FBML and IFrame-based Facebook applications through an intuitive API and small set of server controls. It does support the use of the Facebook API from desktop applications as well, and will eventually enable Silverlight application usage.
The library is built on .NET 2.0, but should run on future versions of the .NET framework as well. Applications using Facebook.NET can be written in either C# or VB.NET.

Download from here

Tuesday, December 21, 2010

SQL SERVER DATA TYPES

What's the difference between CHAR and VARCHAR data types and when do I use them?

CHAR and VARCHAR data types are both non-Unicode character data types with a maximum length of 8,000 characters.  The main difference between these 2 data types is that a CHAR data type is fixed-length while a VARCHAR is variable-length.  If the number of characters entered in a CHAR data type column is less than the declared column length, spaces are appended to it to fill up the whole length.

Another difference is in the storage size wherein the storage size for CHAR is n bytes while for VARCHAR is the actual length in bytes of the data entered (and not n bytes).

You should use CHAR data type when the data values in a column are expected to be consistently close to the same size.  On the other hand, you should use VARCHAR when the data values in a column are expected to vary considerably in size.

What's the difference between NCHAR and NVARCHAR data types and when do I use them?

NCHAR and NVARCHAR data types are both Unicode character data types with a maximum length of 4,000 characters.  The main difference between these 2 data types is that an NCHAR data type is fixed-length while an NVARCHAR is variable-length.  If the number of characters entered in an NCHAR data type column is less than the specified column length, spaces are appended to it to fill up the whole length.

Another difference is in the storage size wherein the storage size for NCHAR is two times n bytes while for NVARCHAR is two times the number of characters entered (in bytes).

You should use NCHAR data type when the data values in a column are expected to be consistently close to the same size.  On the other hand, you should use NVARCHAR when the data values in a column are expected to vary considerably in size.

What's the difference between CHAR and NCHAR data types and when do I use them?

CHAR and NCHAR data types are both character data types that are fixed-length.  Below is the summary of the differences between these 2 data types:

  CHAR(n) NCHAR(n)

Character Data Type

Non-Unicode Data

Unicode Data

Maximum length 8,000 4,000
Character Size 1 byte   2 byte
Storage Size   n bytes   2 x n bytes

You would use NCHAR data type for columns that store characters from more than one character set or when you will be using characters that require 2-byte characters, which are basically the Unicode characters such as the Japanese Kanji or Korean Hangul characters

What's the difference between VARCHAR and NVARCHAR data types and when do I use them?

VARCHAR and NVARCHAR data types are both character data types that are variable-length.  Below is the summary of the differences between these 2 data types:

  VARCHAR(n) NVARCHAR(n)

Character Data Type

Non-Unicode Data

Unicode Data

Maximum length 8,000 4,000
Character Size 1 byte   2 byte
Storage Size actual length (in bytes)   2 x actual length (in bytes)

You would use NVARCHAR data type for columns that store characters from more than one character set or when you will be using characters that require 2-byte characters, which are basically the Unicode characters such as the Japanese Kanji or Korean Hangul characters.

What's the difference between TINYINT, SMALLINT, INT and BIGINT data types and when do I use them?

TINYINT, SMALLINT, INT and BIGINT are all the same in the sense that they are all exact number data types that use integer data.  The difference between these data types are in the minimum and maximum values that each can contain as well as the storage size required by each data type, as shown in the following table:

Data Type Min Value Max Value Storage Size
tinyint 0 255 1 byte
smallint -2^15 (-32,768) 2^15 - 1 (32,767) 2 byte
int -2^31 (-2,147,483,648) 2^31 - 1 (2,147,483,647) 4 byte
bigint -2^63 (-9,223,372,036,854,775,808) 2^63 - 1 (9,223,372,036,854,775,807) 8 byte

Choosing which of these data types to use depends on the value you want to store for the column or variable.  The rule of thumb is to always use the data type that will require the least storage size.  Don't always use INT as your data type for whole numbers if you don't need to.  If you simply need to store a value between 0 and 255 then you should define your column as TINYINT.

What's the difference between NUMERIC and DECIMAL data types and when do I use them?

There is no difference between NUMERIC and DECIMAL data types.  They are synonymous to each other and either one can be used.  DECIMAL/NUMERIC data types are numeric data types with fixed precision and scale.

In declaring a DECIMAL or NUMERIC data type, p, which is the precision, specifies the maximum total number of decimal digits that can be stored, both to the left and to the right of the decimal point.  The precision must be a value from 1 through the maximum precision of 38.  The s is the scale and it specifies the maximum number of decimal digits that can be stored to the right of the decimal point.  Scale, which defaults to 0 if not specified, must be a value from 0 to the precision value.

The following table specifies the storage size required based on the precision specified for the NUMERIC or DECIMAL data type:

Precision Storage Size
1 - 9 5 bytes
10 - 19 9 bytes
20 - 28 13 bytes
29 - 38 17 bytes

What's the difference between FLOAT and REAL data types and when do I use them?

FLOAT and REAL data types are both approximate number data types for use with floating point numeric data.  Floating point data is approximate; not all values in the data type range can be precisely represented.  The differences between these 2 data types are in the minimum and maximum values each can hold as well as the storage size required, as specified in the following table:

Data Type

n Min Value Max Value Precision Storage Size
float [(n)] 1-24 -1.79E + 308 1.79E + 308 7 digits 4 bytes
  25-53 -1.79E + 308 1.79E + 308 15 digits 8 bytes
real   -3.40E + 38 3.40E + 38 7 digits 4 bytes

For FLOAT data type, the n is the number of bits used to store the mantissa in scientific notation and thus dictates the precision and storage size and it must be a value from 1 through 53.  If not specified, this defaults to 53.  In SQL Server, the synonym for REAL data type is FLOAT(24).  If your data requires only a maximum of 7 digits precision, you can either use the REAL data type or FLOAT data type with 24 as the parameter (FLOAT(24)).

What's the difference between SMALLDATETIME and DATETIME data types and when do I use them?

A datetime data type is date and time data from January 1, 1753 through December 31, 9999, to an accuracy of one three-hundredth of a second (equivalent to 3.33 milliseconds or 0.00333 seconds).  Values are rounded to increments of .000, .003, or .007 seconds.

On the other hand, a smalldatetime data type is a date and time data from January 1, 1900, through June 6, 2079, with accuracy to the minute.  smalldatetime values with 29.998 seconds or lower are rounded down to the nearest minute; values with 29.999 seconds or higher are rounded up to the nearest minute.

Values with the datetime data type are stored internally by Microsoft SQL Server as two 4-byte integers.  The first 4 bytes store the number of days before or after the base date, January 1, 1900.  The base date is the system reference date.  Values for datetime earlier than January 1, 1753, are not permitted. The other 4 bytes store the time of day represented as the number of milliseconds after midnight.

The smalldatetime data type stores dates and times of day with less precision than datetime.  SQL Server stores smalldatetime values as two 2-byte integers.  The first 2 bytes store the number of days after January 1, 1900.  The other 2 bytes store the number of minutes since midnight. Dates range from January 1, 1900, through June 6, 2079, with accuracy to the minute.

Data Type

Min Value Max Value Accuracy Storage Size
smalldatetime January 1, 1900 June 6, 2079 up to a minute 4 bytes
datetime January 1, 1750 December 31, 9999 one three-hundredth of a second 8 bytes

smalldatetime is usually used when you don't need to store the time of the day such as in cases of effectivity dates and expiration dates.  datetime  is used if the time of the day is needed and up to the second accuracy is required.

What's the difference between SMALLMONEY and MONEY data types and when do I use them?

MONEY and SMALLMONEY are both monetary data types for representing monetary or currency values.  The differences between these 2 data types are in the minimum and maximum values each can hold as well as in the storage size required by each data type, as shown in the following table:

Data Type

Min Value Max Value Storage Size
smallmoney -214,748.3648 214,748.3648 4 bytes
money -2^63 (-922,337,203,685,477.5808) 2^63 (-922,337,203,685,477.5808) 8 bytes

How do I store a boolean value in SQL Server?

In SQL Server, there's no boolean data type.  The nearest data type that can be used in place of boolean data is the BIT data type, which is an integer data type that can accept a value of 1, 0 or NULL value only.

Monday, December 20, 2010

WCF OperationContractAttribute with example

The OperationContractAttribute, also defined in the System.ServiceModel namespace, can be applied only to methods. It should declare to the method which belongs to a Service contract. Operation contract can be declared with below named parameters that provide control over the service description and message formats.

Name Specifies a different name for the operation instead of using the default, which is the method name.Action Controls the action header for messages to this operation.

ReplyAction Controls the action header for response messages from this operation.

IsOneWay Indicates whether the operation is one-way and has no reply. When operations are one-way, ReplyAction is not supported.

ProtectionLevel Enables the Service contract to specify constraints on how messages to
all operations in the contract are protected on the wire, that is, whether they are signed and encrypted.

IsInitiating Indicates whether invoking the operation initiates a new session between the caller and the service.

IsTerminating Indicates whether invoking the operation terminates an existing session between the caller and the service

Here is Sample WCF Class for reference.

// C#
[ServiceContract(Namespace = "")]
public class CrudContract
{
    [OperationContract(IsOneWay = true, Action = "urn:crud:insert")]
    void ProcessInsertMessage(Message message);
    [OperationContract(IsOneWay = true, Action = "urn:crud:update")]
    void ProcessUpdateMessage(Message message);
    [OperationContract(IsOneWay = true, Action = "urn:crud:delete")]
    void ProcessDeleteMessage(Message message);
    // The catch-all operation:
    [OperationContract(IsOneWay = true, Action = "*")]
    void ProcessUnrecognizedMessage(Message message);
}

Hope this is useful Party smile

Wednesday, December 15, 2010

“CleanRiaClientFilesTask" task failed unexpectedly

Recently few of our developers and me got this error while building my Silverlight application. I got this error while checking in the code and merge my code changes.

Error Details.

Error    38    The "CleanRiaClientFilesTask" task failed unexpectedly.
System.ArgumentException: Illegal characters in path.

To resolve this we need to do two simple steps.

Step 1: Go to this location in your system or your Framework install directory, for me its C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files. Clean all the temporary files under this location and leave the root folder empty.

Step 2: Go to your project location and Delete all the files in \obj folder. Basically all the files are stored in the \obj folder created by ria services.

Now clean the project and try building again. It worked for me. Hope this will help you. Good luck Hot smile

Thursday, December 09, 2010

Iterating through Generic List in C#

Recently I need to loop through a Generic list and bind the result to a Combobox. Here is how you can do this in C#

List<CCDSDateResult> list = new List<CCDSDateResult>();
for (int i = 0; i < e.Result.Count; i++)
{
    if (e.Result.ToList()[i].ccds_date.ToString().Length > 0)
    {
        // Write your logic..to add item in the list
        list.Add(new CCDSDateResult(DateTime.Parse(e.Result.ToList()[i].ccds_date.ToString())));
    }
}
// adding a empty record to the list
list.Insert(0, new CCDSDateResult());
this.OrderComboBox.ItemsSource = list.ToList();

Hope this is useful. Thumbs up

Exporting to Excel from Telerik Gridview in Silverlight

Here is the sample code for exporting Telerik Gridview in silverlight.

private void btnExportOrders_Click(object sender, RoutedEventArgs e)
{
   // Checking whether grid has rows
    if (OrderGrid.Items.Count > 0)
    {
          string extension = "xls";
          string selectedItem = "Excel";
          ExportFormat format = ExportFormat.ExcelML;
          SaveFileDialog dialog = new SaveFileDialog();
          dialog.DefaultExt = extension;
          dialog.Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, selectedItem);
          dialog.FilterIndex = 1;
          if (dialog.ShowDialog() == true)
          {
              using (Stream stream = dialog.OpenFile())
              {
                GridViewExportOptions options = new GridViewExportOptions();
                options.Format = format;
                options.ShowColumnHeaders = true;
                options.Encoding = Encoding.UTF8;
                options.ShowColumnHeaders = true;
               // name of the grid which you want export      
                OrderGrid.Export(stream, options);
               }
           }
     }
     else
      {
         // User friendly Message
          MessageBox.Show("There are no records to export.", "Export Warning!", MessageBoxButton.OK);
      }
 }

This export code will also support different formats like CSV,Text and HTML. All you need to change is the enum type for ExportFormat to above formats and the extension. Its easy and simple. Good luck Winking smile

Silverlight: MessageBox with Title, OK, and Cancel Buttons

A message box is a dialog box that is used to display an alert or a message. A message box can have a title and multiple options such as Yes/No or  OK/Cancel. A message box can also have some input control to take input from a user.

The MessageBox class in WPF represents a modal message box dialog, which is defined in the System.Windows namespace. The Show static method of the MessageBox is the only method that is used to display a message box. The Show method returns a MessageBoxResult enumeration that has values OK, Cancel, Yes, and No. We can use MessageBoxResult to find out what button was clicked on a MessageBox and take an appropriate action.

The following code snippet creates a MessageBox with a message, a title, and two OK and Cancel buttons.

 MessageBoxResult result = MessageBox.Show("Are you sure you want to delete this Deposit?",
                                    "Delete", MessageBoxButton.OKCancel);
      if (result == MessageBoxResult.OK)
      {
         // do if your result is OK
      } 
      else
      {
         // do if result is cancel
      }

Hope this help Smile

Sunday, December 05, 2010

T-SQL: Change tables owner to dbo with sp_changeobjectowner

Sometimes there is a need to change all tables in the database to be owned by dbo for maintenance or to fix up accidental errors. All tables owned by dbo schema is usually best practices in the database application development with MSSQL.

The following small SQL code snippet goes through all user tables in the database and changes their owner to dbo. It usessp_changeobjectowner system stored procedure

DECLARE tabcurs CURSOR
FOR
    SELECT 'dips.' + [name]
      FROM sysobjects
     WHERE xtype = 'u'
OPEN tabcurs
DECLARE @tname NVARCHAR(517)
FETCH NEXT FROM tabcurs INTO @tname
WHILE @@fetch_status = 0
BEGIN
    EXEC sp_changeobjectowner @tname, 'dbo'
    FETCH NEXT FROM tabcurs INTO @tname
END
CLOSE tabcurs
DEALLOCATE tabcurs

Hope this is useful..

Javascript Tip: Close Pop-up - Refresh Parent

Sometimes we need to force parent refresh on closing pop-up window which was opened from this parent window. There are many ways to make it work, however the most elegant way will be using location.href

function Refresh() 
{
    window.opener.location.href = window.opener.location.href;
    window.close();
}

Smile

ASP.NET Tip: Render Control into HTML String

How to get string representation of ASP.NET control or in other words render it into string instead of let it be rendered on the page. Here is the sample code to Render control

using System.Text;
using System.IO;
using System.Web.UI;
public string RenderControl(Control ctrl) 
{
    StringBuilder sb = new StringBuilder();
    StringWriter tw = new StringWriter(sb);
    HtmlTextWriter hw = new HtmlTextWriter(tw);
    ctrl.RenderControl(hw);
    return sb.ToString();
}

Saturday, December 04, 2010

How to Create Dynamically a Property Class from T-SQL

Some times we need to write huge classes with properties, its time consuming and boring . Here is a work around how you can do this from T-SQL.

use master
go
Declare @tableName varchar(50)
SET @tableName = 'bangaram'
SELECT case when sc.isnullable<>0 AND st.name NOT LIKE 'varchar' AND st.name NOT LIKE 'text' then  
'private System.Nullable<'+REPLACE(REPLACE(REPLACE(REPLACE(st.name,'varchar','string'),'bit','bool'),'datetime','DateTime'),'text','string')+ '> _'  +sc.name +';
 public System.Nullable<'+REPLACE(REPLACE(REPLACE(REPLACE(st.name,'varchar','string'),'bit','bool'),'datetime','DateTime'),'text','string')+ '> '+sc.name
else 
'private '+REPLACE(REPLACE(REPLACE(REPLACE(st.name,'varchar','string'),'bit','bool'),'datetime','DateTime'),'text','string')+ ' _'  +sc.name +';
 public '+REPLACE(REPLACE(REPLACE(REPLACE(st.name,'varchar','string'),'bit','bool'),'datetime','DateTime'),'text','string')+ ' '+sc.name  
  end ,
        '{
            get { return this._'+sc.name+'; }
            set { if ((this._'+sc.name+' != value)) { this._'+sc.name+' = value; } }
        }'
FROM Syscolumns sc INNER JOIN Systypes st on st.xtype=sc.xtype
WHERE sc.id in(SELECT id FROm sysobjects WHERE name=@tableName)
ORDER BY sc.id

Replace @tablename with your table name in your database table. One more thing I have give @tablename size as varchar(50) increase if your tablename is bigger. That’s all you need to do apart from little bit of formatting..Good luck guys. Have fun..Smile