Sunday, August 22, 2010

ASP.NET - Scraps

If we are not using some techniques and we may forget over the period of time. So I am going to use this blog as my tech memories. So that at any point of stage i can use my blog to review / brush up these.

I think this is a good move in my tech life, I have read lot of articles in my life but i forget over the period of time. I forgot lot of VC++, SQL Server 2000, DB2, linux, Oracle administration techniques.

Triggers in Ajax - In case if we wants to reload the update panel based on a control that resides outside of the update panel, then triggers will be used.

Class Vs Struct - Structures are Value type, Classes are Reference type. Structure cannot have parameterless constructor and not inheritable, however class can.

Extension Methods -Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code. Should have public static access identifier and parameter should have this keyword.
public static bool IsValidEmail(this string input)
{
}
Cache - Page output cache(VaryByParam,VaryByControl,VaryByHeader,VaryByCustom), key based cache, file based cache and time based cache. For more details, check this link
Page Life Cycle - Page Request => start => Initialization => Load => Postback event handling => Rendering => unload


Threading

Threading is a very wast and interesting area in programming. Without actual experience talking about threading is some what not possible. It requires actual implementation.

.NET supports Threading from the beginning and enhances it in each release. Sytem.Threading is the class dedicated for this.

We can create threads for parameter less and parametrized functions. It is very easy in .NET

Threading.Thread th = new Threading.Thread(fn);
th.Start();
//th.Start(1); //this is for parametrized

public void fn()
{
}
public void fn(object val)
{
}

Synchronization
While dealing with Data and thread, sync is very much important. We can use the below methodologies.
Monitor.Enter - It is a static method and Monitor.Exit should be called in the finally block
lock / synclock - this works same as Monitor.Exit but automatically releases the lock if the scope is out.
ReaderWriterLock - It works best where most accesses are reads, while writes are infrequent and of short duration. Multiple readers alternate with single writers, so that neither readers nor writers are blocked for long periods.
ReaderWriterLock.AcquireReaderLock, ReaderWriterLock.AcquireWriterLock, ReaderWriterLock.UpgradeToWriterLock, ReaderWriterLock.DowngradeFromWriterLock, ReaderWriterLock.ReleaseLock
ReaderWriterLockSlim - It is the slimmer version of ReaderWriterLock and the performance is significantly better than the former.

Friday, August 20, 2010

WCF - Part 2

We have learned about the basics in Part1.

In this part just epalins other important things that we need to know about WCF

I have worked on Webservices for a long time and WCF for last 2 to 3 years. When we are working with different technology are different systems, this is the best one to communicate between each other.

WCF Bindings
-BasicHttpBinding
-WSHttpBinding
-WSDualHttpBinding
-WSFederationHttpBinding
-NetTcpBinding
-NetNamedPipeBinding
-NetMsmqBinding

Find the comparison chart here about the Different bindings

Selvakumar's WCF tutorial site is a good resource for beginners and who looking for any help regarding WCF :)

IsInitiating, IsTerminating attributes(OperationContract) provide us the functionality to call methods in a specified order.

SessionMode & InstanceContextMode(PerCall, PerSession, Single) are used for Session and Instance Management.

We can use the "Rename" command on the "Refactor" menu to change the class name in code, svc and config file together. (Finally Problem Solved by MS :) )

Exceptions are handled thro Fault Contract
[ServiceContract]
public interface IMyService
{
[OperationContract]
[FaultContract(typeof(MyApplicationFault))]
void MyMethod();
}

Some Cool links to learn more about WCF
http://msdn.microsoft.com/en-us/netframework/first-steps-with-wcf.aspx http://msdn.microsoft.com/en-us/library/ee354381.aspx http://msdn.microsoft.com/en-us/library/ee958158.aspx

WCF - Part 1

What is WCF? - Windows Communication Foundation and it is part of .NET Framework. WCF is a unified communication framework that combines all Microsofts existing technologies like Remoting, Web Service, MSMQ and so on. We no need learn different type of programming for each above said methodlogies.

Basics
All are talking about ABC of WCF, What it is?
A - Address, Where the service is hosted (URL)
B - Binding, How the service is exposed (Http, Tcp, ...)
C - Contract, What is the Skeleton/Interface/structure of the service

Bindings
We have different binding for each transport type/ methodology. For Http we have some bindings & for tcp we have some bindings. We will see in detail in the next part.

Contracts
Service Contract - Service Class
Operation Contract - Service Methods that are exposed
Data Contract - Classes that holds data and traverse between service and client

Hosting
We can host WCF in the following ways
IIS
WAS - Windows Application Server - Introduced in IIS7
Self hosting - Our own application to host WCF Service
Windows Service

Cool, so now we know the basics of WCF :)

What's New in the .NET Framework 4

Garbage Collection - The .NET Framework 4 provides background garbage collection. This feature replaces concurrent garbage collection in previous versions and provides better performance. Get More information here about GC
Dynamic Language Runtime - System.Dynamic namespace is added to support this.
Covariance and Contravariance
BigInteger and Complex Numbers - System.Numerics namespace is introduced to support this.
File System Enumeration Improvements - Directory.EnumerateDirectories & Directory.EnumerateFiles can be used to loop through the Dirs & Files
Migration issues - For migration issues check the microsft site.
Parallel Computing - The .NET Framework 4 introduces a new programming model for writing multithreaded and asynchronous code that greatly simplifies the work of application and library developers.The new System.Threading.Tasks namespace and other related types support this new model.
C# New Features

  • String.IsNullOrWhiteSpace
  • StringBuilder.Clear
  • Thread.Yield

Web

  • Core services, including a new API that lets you extend caching, support for compression for session-state data, and a new application preload manager (autostart feature).
  • Web Forms, including more integrated support for ASP.NET routing, enhanced support for Web standards, updated browser support, new features for data controls, and new features for view state management.
  • Web Forms controls, including a new Chart control. MVC, including new helper methods for views, support for partitioned MVC applications, and asynchronous controllers.
  • Dynamic Data, including support for existing Web applications, support for many-to-many relationships and inheritance, new field templates and attributes, and enhanced data filtering.
  • Microsoft Ajax, including additional support for client-based Ajax applications in the Microsoft Ajax Library.
  • Visual Web Developer, including improved IntelliSense for JScript, new auto-complete snippets for HTML and ASP.NET markup, and enhanced CSS compatibility.
  • Deployment, including new tools for automating typical deployment tasks.
  • Multi-targeting, including better filtering for features that are not available in the target version of the .NET Framework.

Windows Communication Foundation

  • Configuration-based activation: Removes the requirement for having an .svc file.
  • System.Web.Routing integration: Gives you more control over your service's URL by allowing the use of extensionless URLs.
  • Multiple IIS site bindings support: Allows you to have multiple base addresses with the same protocol on the same Web site.
  • Routing Service: Allows you to route messages based on content.
  • Support for WS-Discovery: Allows you to create and search for discoverable services.
  • Standard endpoints: Predefined endpoints that allow you to specify only certain properties.
  • Workflow services: Integrates WCF and WF by providing activities to send and receive messages, the ability to correlate messages based on content, and a workflow service host.
  • WCF REST features: Web HTTP caching, Web HTTP formats support, Web HTTP services help page, Web HTTP error handling, Web HTTP cross-domain JavaScript support

IDE

  • Improved Intellisense
  • Multi monitor support
  • Call hierarchy for methods

C# - What I learned newly over the years

Mutable & Immutable - String is a muttable(whenever we alter a string, new string object created) and StringBuilder is Immutable

Generics - This is the best one that introduced with 2.0 and it helps to maximize code reuse, type safety, and performance. It is commonly used for collection purpose. It is in System.Collections.Generic. So better to avoid classes present in System.Collections (Arraly List and hastable). Know about Generics more visit here

HashTable & Dictionary - These 2 objects holds key-value pair.The Dictionary class has the same functionality as the Hashtable class. A Dictionary of a specific type (other than Object) has better performance than a Hashtable for value types because the elements of Hashtable are of type Object and, therefore, boxing and unboxing typically occur if storing or retrieving a value type.

Partial Class - It helps us to have the same class in multiple files. This is very useful when multiple persons are working in same class and to differentiate definition & implementation in different files.

Using - This is good feature for GC

Type Casting and Comparison Using "as" and "is" -
DataGridItem item = mycontrol.Parent as DataGridItem;
if (item is DataGridItem){ }


Extension Methods
static class ExtensionSample
{
public static decimal Triple( this decimal d ) { return d*3; }
}


LINQ

It is efficient when we use with objects and dataset. for example to randomly order a list, list = list.OrderBy(emp => Guid.NewGuid()).ToList();

Wednesday, August 18, 2010

SQL Server Tips

Passing Array of values to SP

I have been using dynamic queries when dealing with comma separated values for single parameter.

However now i learned that we can create a function (table valued user defined function) that splits the parameter value by the separator and returns a table.

dbo.sp_sample '12,13,14,15'
dbo.fn_split(@param1, ',')

Getting SP's Return Value

Sometimes we need to retrieve the SP's return values(scalar / set of rows) in some other SP.
for that we can use insert into #tblTemp exec dbo.sp_sample '12,13'

Table Variable Vs Temp Tables

we have been in confusion many times that which one to use table variable or temp table

Go for Table variable if data size is small
Go for Temp table if data size is large, bcoz we can create indexs on temp table that will help when we are dealing with large Daaataaaa (not typo)

Common Tips

Table
  • Use Primary keys & Indexes (too much keys will affect the performance)
  • Use Fill factor based on frequency of data insertion to the table
  • Use Foreign keys and set appropriate null & not null
  • Table name should explain the table purpose
  • use appropriate data types, bit, tinyint, smallint, int, bigint...so on
  • Use Varchar if data length is going to vary
SP

  • Use set nocount on
  • Use nolock in select queries
  • Use proper Where conditions and inner joins
  • Select appropriate columns
  • Try to avoid NOT, <>, IS NULL, IN, UNION, DISTINCT if not necessary
  • Try to avoid Cursors
  • Avoid sp_ prefix, use usp_
  • use query execution plans to tune up your queries
  • SQL 2008 provides lot of inbuild reports that will help us identify long running running queries, most executed queries, connections and so on
  • SQl 2008 intellisence is also another one good feature to like

Tuesday, August 17, 2010

Crystal Reports XI - Export

I have been working with Excel & Word export with ASP.NET using MIME types for a long time...

I got a oppertunity to work with PDF & Excel Export using Crystal Reports XI. Cool, it has lot of flexibility and feature that can help us to export the reports in diffeent formats


EnterpriseService ceEnterpriseService;
InfoStore ceInfoStore;
InfoObjects ceReportObjects;
InfoObject ceReportObject;
Report ceReport;

protected CrystalDecisions.CrystalReports.Engine.ReportDocument reportDocument1;
reportDocument1 = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
reportDocument1.FileName = "";

SessionMgr ceSessionMgr = new SessionMgr();
EnterpriseSession ceSession;

ceSession = ceSessionMgr.Logon(CommonFunctions.GetConFigValue("CrystalUserId"), CommonFunctions.GetConFigValue("CrystalPwd"), CommonFunctions.GetConFigValue("CrystalServerName"), "secEnterprise");
ceEnterpriseService = ceSession.GetService("", "InfoStore");
ceInfoStore = new InfoStore(ceEnterpriseService);
sQuery = "Select * From CI_INFOOBJECTS Where SI_PROGID = 'CrystalEnterprise.Report' AND SI_NAME='" + strReportName + "'";
ceReportObjects = ceInfoStore.Query(sQuery);

if (ceReportObjects.Count > 0)
{
ceReportObject = ceReportObjects[1];
ceReport = ((Report)(ceReportObject));
reportDocument1.Load(ceReportObject, ceSession);


MemoryStream oStream; // using System.IO
oStream = (MemoryStream)reportDocument1.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.BinaryWrite(oStream.ToArray());
Response.End();

}

else
{
Response.Write("No report objects found by query
");
}


}
else
{
Response.Write("No Valid Enterprise Session Found!
");
}

Crystal Reports XI

I have worked on scheduling Crystal reports using ASP.NET, and it is been great learning.

It has lot of cool features exposed. We can set the type of report format we want and even we can customize that.

Steps

1)Open Session
2)Get Report Object
3)Configure new Report (Type, Occurence)
4)Set Parameter


SessionMgr ceSessionMgr = new SessionMgr();
EnterpriseSession ceSession;


ceSession = ceSessionMgr.Logon(AppSettings.GetDatabaseConnectionString("CrystalUserName"), AppSettings.GetDatabaseConnectionString("CrystalPassword"), AppSettings.GetDatabaseConnectionString("CrystalServerName"), "secEnterprise");

if (ceSession != null)
{
ceEnterpriseService = ceSession.GetService("", "InfoStore");
ceInfoStore = new InfoStore(ceEnterpriseService);
strQuery = "Select * From CI_INFOOBJECTS Where SI_PROGID = 'CrystalEnterprise.Report' AND SI_NAME='" + REPORTNAME + "'";
ceReportObjects = ceInfoStore.Query(strQuery);
if (ceReportObjects.Count > 0)
{
ScheduleCrystal(ceReportObjects);
}

}


private void ScheduleCrystal(InfoObjects infoObjects)
{
Report report;
Destination destination;
Smtp smtp;
SmtpOptions smtpOptions;
SchedulingInfo schedulingInfo;
string strFromEmail = "xxx@xx.com";
string strToEmail = string.Empty;
string strSubject = string.Empty;
string strBody = string.Empty;
bool blPDF = false;
string strServerType = string.Empty;
try
{
// if env is dev then DEVEmailAddress otherwise actual analyst mail address
strToEmail = AppSettings.GetDatabaseConnectionString("DEVEmailAddress");

report = (Report)infoObjects[1].GetPluginInterface("Report");
if (blPDF)
{
report.ReportFormatOptions.Format = CeReportFormat.ceFormatPDF;
}
else
{
report.ReportFormatOptions.Format = CeReportFormat.ceFormatExcel;
report.ReportFormatOptions.ExcelFormat.ExportPageHeaderFooter = CeReportHeaderFooterOption.ceReportHeaderFooterOnce;
report.ReportFormatOptions.ExcelFormat.BaseAreaType = CeSectionType.ceDetail;
report.ReportFormatOptions.ExcelFormat.CreatePageBreak = false;
report.ReportFormatOptions.ExcelFormat.ExportAllPages = true;
report.ReportFormatOptions.ExcelFormat.ExportShowGridlines = true;
//report.ReportFormatOptions.ExcelFormat.IsTabularFormat = true;
}
strSubject = "Holdings Report - " + txtReportName.Text.Trim();
strBody = "Holdings Report for the following Tickers and Sectors \n\n";
strBody += "Report Name: " + txtReportName.Text.Trim() + "\n\n";
strBody += "Tickers: " + GetTickers() + "\n\n";
strBody += "Sectors: " + GetSectorNames(GetSectorIds()) + "\n";
SetParameters(report.ReportParameters);
schedulingInfo = infoObjects[1].SchedulingInfo;
//change the below code according to the selection
SetSchedulingTypeandDateTime(ref schedulingInfo);
destination = schedulingInfo.Destination;
smtp = (Smtp)infoObjects.InfoStore.Query("SELECT * FROM CI_SYSTEMOBJECTS WHERE SI_PARENTID=29 AND SI_NAME='CrystalEnterprise.Smtp'")[1].GetPluginInterface("");
smtpOptions = (SmtpOptions)smtp.ScheduleOptions;
foreach (string strEmail in strToEmail.Split(';'))
{
smtpOptions.ToAddresses.Add(strEmail);
}
//smtpOptions.CCAddresses.Add(strFromEmail);
smtpOptions.Subject = strSubject;
smtpOptions.Message = strBody;
smtpOptions.SenderAddress = strFromEmail;
smtpOptions.EnableAttachments = true;
if (blPDF)
{
smtpOptions.Attachments.Add("application/pdf", "NBRHoldingsReport_" + txtReportName.Text.Trim().Replace(" ", "") + ".pdf");
}
else
{
smtpOptions.Attachments.Add("application/vnd.ms-excel", "NBRHoldingsReport_" + txtReportName.Text.Trim().Replace(" ", "") + ".xls");
}
destination.Clear();
destination.Name = "CrystalEnterprise.Smtp";
destination.SetFromPlugin(smtp);
infoObjects.InfoStore.Schedule(infoObjects);
}
catch (Exception ex)
{
//throw;
}
}




private void SetParameters(ReportParameters parameters)
{
string strToEmail = string.Empty;
try
{
ReportParameterSingleValue singleValue;
ReportParameter reportParameter;
//for tickers
reportParameter = parameters[1];
singleValue = reportParameter.CreateSingleValue();
singleValue.Value = GetTickers();
reportParameter.CurrentValues.Clear();
reportParameter.CurrentValues.Add(singleValue);

}
catch (Exception ex){//throw;}
}

Tuesday, July 20, 2010

Select ALL - jQuery

I am so happy that i can achieve things in 1 line of code using jQuery.
To Select all the checkboxes in the grid..
$(":checkbox").each(function() { this.checked = document.getElementById('chkAll').checked; });

To findout atleast one checbox should be selected
var isChecked = false;
$(":checkbox").each(function() { if (this.checked == true) isChecked = true; });

or
if ($(":checkbox:checked").length > 0) {
isChecked = true;

}

Friday, July 16, 2010

jQuery Part3

jQuery has lot of cool features. We can achieve things in less code and we have a library/framework(jQuery) behind us :)

ok...lets see what i have learned today

$(document).scrollTop()
$('#TextArea1').resizable() - This can be used for scrolling and split panes
Lightbox & colorbox - to show image popups

Wednesday, July 14, 2010

JQuery Continued...

This post is continuation of the yesterdays jQuery article. I am listing down the jQuery methods that i learned today.
toggle - instead of using show() and hide() methods we can use toggle() method.
$('#Button2').toggle('slow');
instead of
if ($("#Button2").is(':visible')) {$("#Button2").hide();}
else {$("#Button2").show();}

css class, mouseover, mouseout - addClass & removeClass can be used to add/remove CSS class to the elements as below.
$('#GridView1 tr').hover(function() { $(this).addClass('hover'); }, function() { $(this).removeClass('hover'); })
Plugins - Lot of animation functionality is not included in the jQuery master file due to the size factor. Lot of plugins(http://plugins.jquery.com)available to download.
one of the good plugin for animation is Easing (http://plugins.jquery.com/project/Easing )
Chaining Actions - More than one action can be done by calling jQuery methods one on another.
$('p:last').effect('shake', { times: 5 }, 300).effect('highlight', {}, 3000).hide('explode', {}, 500);


Tuesday, July 13, 2010

Today's snippets

HTC 1 - design fabulous
I have come across this site while reading google news.
Excellent designs by Andrew Kim. Have a look, it is worthy.
http://designfabulous.blogspot.com/

kudos and hats off to you

Xperia X10 software update - OTA
Sony ericsson finally rolled out Over the Air update to speed up Xperia X10.
http://blogs.sonyericsson.com/products/2010/06/30/xperia-x10-software-update%E2%80%A6-over-the-air/

JQuery

I am going through the jQuery: Novice to Ninja book. Find the useful snippets about jQuery below.

jQuery UI - jQuery User Interface, and it comprises a menagerie of useful effects and advanced widgets that are accessible and highly customizable through the use of themes.

It’s Just JavaScript! - Never forget that jQuery is just JavaScript! It may look and act superficially differ-ent—but underneath it’s written in JavaScript

$(document).ready() - Almost everything you do in jQuery will need to be done after the document is ready. It can be represented as just $(function() { alert('Hello World!'); } );

Firebug - Firebug is a particularly useful tool for examining the DOM in your browser

Accessing Grid - Grid rows can be accessed by the below jQuery $("#GridId tr"), firest row can be accessed as $("#GridId tr:first") and nth row can be accessed as $("#GridId tr:eq(n)")

CSS, Styles - Following jQuery can be used to set the grey background color in the odd rows. $("#GridId tr:odd") .css('background-color', 'gray')

This is for today.... Have a nice Programming Day :)