Monday, July 20, 2009

C# 4.0: Dynamic Programming



If C# 3.0 was all about Language Integrated Query (LINQ), then C# 4.0 is all about dynamic programming. What exactly does that mean? It means that C# 4.0 brings some of flexibility and declarative style of programming to C#.

But what does that really mean?
To sum it up in one keyword: dynamic.
C# 4.0 is adding a new dynamic keyword which is used as a data type in much the same way the var keyword is used. Why is this important? The biggest reason is that it allows a C# program to use dynamic dispatch to more naturally create objects coming from a dynamic language.
For example, suppose you have a Calculator object declared in C#, meaning it is statically typed. You interact with your object like this:
Calculator calc = GetCalculator();
int sum = calc.Add(10, 20);
That’s pretty simple and straight forward. Now suppose the Calculator is not a statically typed .NET class (or it is a .NET class but you don’t know the specific type of class), you must do something like this:
object calc = GetCalculator();
Type calcType = calc.GetType();
object res = calcType.InvokeMember("Add",
    BindingFlags.InvokeMethod, null,
    new object[] { 10, 20 });
int sum = Convert.ToInt32(res);
That’s not nearly as simple. In fact, it’s downright ugly. There is a lot of non-type-safe calls and reflection going on here that you really shouldn’t have to see.
To take this a step further, if we knew that Calculator was a JavaScript class, you must use similar (but still significantly different) code:
ScriptObject calc = GetCalculator();
object res = calc.Invoke("Add", 10, 20);
int sum = Convert.ToInt32(res);
The reason for the differences in syntax is that there is no unification between the two APIs.
In C# 4.0, you can now use the following syntax:
dynamic calc = GetCalculator();
int sum = calc.Add(10, 20);
If you look at this syntax and the earlier statically typed call, you should notice that the only difference is that in C# we are declaring the data type to be dynamic.

Does this mean that C# is loosing it's roots as a statically typed language or that we should all start moving towards dynamic languages? Absolutely not. What is means is that it is now easier for you to write C# code that talks to objects (or APIs) written in dynamically typed languages. It also means that there is a unified API to talk to any dynamic language. You no longer need to worry about what language you are interoperating with to determine which C# code you must write.
So how does the dynamic keyword work? As I mentioned, it's a keyword in a similar fashion to var. You declare at compile-time the type to be dynamic, but at run-time you get a strongly typed object.

The dynamic keyword is great for writing C# code that consumes a dynamic object, but what about going the other direction and writing C# code that can be called from a dynamic language? You do this by implementing the IDynamicObject interface (or more simply, inheriting from the abstract DynamicObject class) and providing your own implementation for the member lookup and invocation.
Using the features and capabilities of the new dynamic keyword, the IDynamicObject interface, and the fact that the dynamic dispatch can dispatch to both dynamic and static types, C# effectively gets support for duck-typing.


Tuesday, July 14, 2009

Bind CheckedListBox Directly with Datatable in C#

chkListBuilding.Items.Clear();
DataTable dtBuilding = (new BuildingManager()).SelectBuilding();
((ListBox)chkListBuilding).DataSource = dtBuilding;
((ListBox)chkListBuilding).DisplayMember = "BuildingName";
((ListBox)chkListBuilding).ValueMember = "BuildingID";

Check List Box With LINQ + Get Checked IDs Comma Separated

var v = (from b in chkListBuilding.CheckedItems.Cast<listitem>()
select b.Value.ToString());

string BuildingIDs = v.Aggregate(delegate(string item1, string item2)
{
return string.Format("{0}, {1}", item1, item2);
});

Thursday, July 2, 2009

Diffrence Int32.parse, Convert.ToInt32, Int32.TryParse

-------------------Int32.parse(string)-------------------

Int32.Parse (string s) method converts the string representation of a number to its 32-bit signed integer equivalent.
When s is null reference, it will throw ArgumentNullException.
If s is other than integer value, it will throw FormatException.
When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException.

*******
Example
*******

string s1 = "1234";
string s2 = "1234.65";
string s3 = null;
string s4 = "123456789123456789123456789123456789123456789";

int result;
bool success;

result = Int32.Parse(s1); //-- 1234
result = Int32.Parse(s2); //-- FormatException
result = Int32.Parse(s3); //-- ArgumentNullException
result = Int32.Parse(s4); //-- OverflowException


-------------------Convert.ToInt32(string)-------------------

Convert.ToInt32(string s) method converts the specified the string representation of 32-bit signed integer equivalent. This calls in turn Int32.Parse () method.
When s is null reference, it will return 0 rather than throw ArgumentNullException
If s is other than integer value, it will throw FormatException.
When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException

*******
Example
*******

result = Convert.ToInt32(s1); //-- 1234
result = Convert.ToInt32(s2); //-- FormatException
result = Convert.ToInt32(s3); //-- 0
result = Convert.ToInt32(s4); //-- OverflowException



-------------------Int32.TryParse(string, out int)------------------

Int32.Parse(string, out int) method converts the specified the string representation of 32-bit signed integer equivalent to out variable, and returns true if it parsed successfully, false otherwise. This method is available in C# 2.0
When s is null reference, it will return 0 rather than throw ArgumentNullException.
If s is other than integer value, the out variable will have 0 rather than FormatException.
When s represents a number less than MinValue or greater than MaxValue, the out variable will have 0 rather than OverflowException.

*******
Example
*******

success = Int32.TryParse(s1, out result);
//-- success => true; result => 1234
success = Int32.TryParse(s2, out result);
//-- success => false; result => 0
success = Int32.TryParse(s3, out result);
//-- success => false; result => 0
success = Int32.TryParse(s4, out result);
//-- success => false; result => 0

Convert.ToInt32 is better than Int32.Parse, since it return 0 rather than exception. But, again according to the requirement this can be used. TryParse will be best since it handles exception itself always.

Tuesday, June 30, 2009

Find Average from datatable column using LINQ and Compute Method

--Using LINQ

var v = (from o in dt.Rows.Cast()
select o.Field("Grand Total")).Average();

--Using Datatable Compute Method

Object objAvg;
objAvg = dt.Compute("Avg([Grand Total])", "[Grand Total] > 0");

--Find Standard Deviation using Datatable Compute method

Object objStDev;
objStDev = dt.Compute("StDev([Grand Total])", "[Grand Total] > 0");

Thursday, June 11, 2009

Regualr expressions for password

Regular expression for Password must be 8 or more characters long, including a capital letter and a number or symbol.

^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=\d]).*$


Regular expression for Password must be 8 or more characters long, including a capital letter and a number and symbol.

^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$


Like wise you can create your own Regular expression.

Monday, May 25, 2009

Enable/Disable Link Button in Java script on Checked Changed Event

<asp:CheckBox ID="chkPermission" runat="server"
Text="I have permission / rights to upload these files and use it in public."
AutoPostBack="false" OnClick="JavaScript:EnableDisableSaveFile();" />


<asp:LinkButton ID="lbtnSaveFiles" runat="server"
Text="Save Files" OnClick="lbtnSaveFiles_Click"
Enabled="true"></asp:LinkButton>


<script type="text/javascript">

function EnableDisableSaveFile()
{

var checked=document.getElementById('<%= chkPermission.ClientID %>').checked;
document.getElementById('<%= lbtnSaveFiles.ClientID %>').disabled = !checked;
document.getElementById('<%= lbtnSaveFiles.ClientID %>').onclick =
function() { return checked };

}

</script>

Thursday, September 25, 2008

SQL Server 2005 : Generate Sequence number and delete rows with top

Generate Sequence Number in SQL 2005

Select ROW_NUMBER() OVER(ORDER BY Column_Name) As ID,* From Table_Name



Delete First Row in SQL 2005

WITH T1 AS (Select Id,FirstName,LastName, ROW_NUMBER()
OVER (PARTITION BY Id,FirstName,LastName Order By Id) AS NUMBER From TEMP)
Delete From T1 Where Number > 1



The Most easiest way to delete first row in SQL 2005 is,


Delete top (1) From Table_Name

Monday, September 22, 2008

Java script Confirm with Yes No buttons

You can write javascript with diffrent button options like YesNo, YesNoCancel etc.
You can change the code 4132 and see the O/P.
To Complete this task, just write following java script in your code,
< script language=javascript >

function window.confirm(str)
{
  execScript('n = msgbox("'+str+'","4132","Title")', "vbscript");
  return(n == 6);
}

</script>

In this script, the line will execute vbScript's Message box withYesNo Option.
execScript('n = MsgBox("Yes Or No?",vbYesNo,"Title")', "vbscript");

Thursday, September 11, 2008

SQL Stuff

--- Database transactions
begin tran
rollback tran
Save Transaction tran_name

--Deletes last row inserted in table Employees

declare @topN int
set @topN = 1
set rowcount @topN
Delete From Employees


--Makes ROWCOUNT Off

--Once the rowcount is set , it is set until you explicitly make off
Set ROWCOUNT 0

Important :
When a transaction begins,
resources used during the transaction are held until the completion of the transaction
(namely locks).
When part of a transaction is rolled back to a savepoint, resources
continue to be held until the completion of the transaction
(or a rollback of the complete transaction).


@@TRANCOUNT
Returns the number of active transactions for the current connection.

@@ROWCOUNT
Returns the number of rows affected by the last statement.

@@IDENTITY
Returns the last-inserted identity value.

@@FETCH_STATUS
Returns the status of the last cursor FETCH statement issued against any cursor currently opened by the connection.

Return value Description
0 FETCH statement was successful.
-1 FETCH statement failed or the row was beyond the result set.
-2 Row fetched is missing.

@@ERROR
Returns the error number for the last Transact-SQL statement executed.

@@DBTS
Returns the value of the current timestamp data type for the current database. This timestamp is guaranteed to be unique in the database.

Creates a user-defined data type.
sp_addtype [ @typename = ] type,
  [ @phystype = ] system_data_type
  [ , [ @nulltype = ] 'null_type' ]
  [ , [ @owner = ] 'owner_name' ]