Saturday, October 16, 2010

Validating a decimal number of specified integers and factional points; using a regular expression.

It’s often the case where we stick to a specified number of integer and fractional number in decimal numbers. But some times the requirement arises to validate the decimal numbers which we specify the number of integers and fractions in it.

Here is a solution to such a problem.

Following is a regular expression I wrote will validate 0 to i number of integers and 0 to f number of fractional points.

string sTest = @"^\d{0," + i + @"}\.\d{0," + f + "}$";

string i = iNumericLength.ToString();
string f = iDecimalPoints.ToString();
 
string sTest = @"^\d{0," + i + @"}\.\d{0," + f + "}$";
 
Regex ex = new Regex(sTest);
string st = txtEnteredValue.Text;
 
if (!ex.IsMatch(st))
{
MessageBox.Show("This is a decimal field which supports max. of " + i + " numbers and max. of " + f+ " decimal numbers.");
}

How To Use FreeTextBox in Asp .Net

Download Source:

FreeTextBox Installation :

In this article I will explain you how easy it is to add an open source HTML editor in your ASP .Net application. If you are creating your own content management system and you want your user to give capabilities to express their thoughts in formatted way, FreTextBox is your available open source solution. If you are creating a discussion forum and want your users to give high end content editing capabilities this is a very good option.

Step - 1
So very first thing that you have to do is to get latest version of FreeTextBox editor from its web site http://freetextbox.com/download/ Once you download the latest you will find the latest assembly for using in your application. Get this dll file copy this file to locally to your project folder inside Bin folder. Once this is done you are half way done.

Step - 2
            Next thing is to add a reference to your web.config file. Simply add following line in your web.config file inside <httpHandlers> section.

<add verb="GET" path="FtbWebResource.axd" type="FreeTextBoxControls.AssemblyResourceHandler, FreeTextBox" />

Step - 3
            Next thing is to add a reference to your web page where you want to use this editor. Simply add following line to your web page after page directive.

<%@ Register TagPrefix="FTB" Namespace="FreeTextBoxControls" Assembly="FreeTextBox" %>


Step - 4
            Now before you actually add this control on your page and start using it a very important task has to be done is adding a support folder to your application. Usually when you download the source from the link above you will get a folder named aspnet_client/ FreeTextBox. Simply copy the FreeTextBox folder inside your application. Make sure you know the exact path where you are placing this folder as we will use it while we actually declare this control on our page. This folder contains supporting JavaScript files and images files and css files.

Step - 5
            And the last step is to declare this control on your page and start using it. It can be done by code below.
<FTB:FreeTextBox ID="FreeTextBox1"  Focus="true" SupportFolder="FreeTextBox/"
                                    JavaScriptLocation="ExternalFile" ButtonImagesLocation="ExternalFile" ToolbarImagesLocation="ExternalFile"
                                    ToolbarStyleConfiguration="OfficeXP" ToolbarLayout="ParagraphMenu,FontFacesMenu,FontSizesMenu,FontForeColorsMenu,                                   
FontForeColorPicker,FontBackColorsMenu,FontBackColorPicker|Bold,
Italic,Underline,Strikethrough,Superscript,Subscript,RemoveFormat|JustifyLeft,
JustifyRight,JustifyCenter,JustifyFull;BulletedList,NumberedList,Indent,Outdent;
CreateLink,Unlink,InsertImage|Cut,Copy,Paste,Delete;Undo,Redo,Print,Save|SymbolsMenu,
StylesMenu,InsertHtmlMenu|InsertRule,InsertDate,InsertTime|InsertTable,EditTable;
InsertTableRowAfter,InsertTableRowBefore,DeleteTableRow;InsertTableColumnAfter,InsertTableColumnBefore,
DeleteTableColumn|InsertForm,InsertTextBox,InsertTextArea,InsertRadioButton,
InsertCheckBox,InsertDropDownList,InsertButton|InsertDiv,EditStyle,
InsertImageFromGallery,Preview,SelectAll,WordClean,NetSpell"

runat="Server" GutterBackColor="red" DesignModeCss="designmode.css" ButtonSet="Office2000" />


And that’s it, your cool and powerful HTML editor is ready in your users’ service. Before we close this topic let’s discuss how we can use this control to store the content to your database, catch while storing and accessing these value.

The value of your editor can be easily access using line below.
Output.Text = FreeTextBox1.Text;

Here the Output is the literal control which can easily decode your values from HTML editor and show your users for just viewing purpose. This control can be defined as below. You can also store this data into database and retrieve back upon user’s request on to similar literal control.

<asp:Literal id="Output" runat="server"   />

Catch:-
Now when you actually start using this you will get an error as below.

A potentially dangerous Request.Form value was detected. This screen will look something like below.

Simply add this to your page directive and this error will disappear
ValidateRequest="false".


This is what you have to do to use a fully functional HTML editor in your web application.

Thanks you.

Short Cut Keys.


Here are some short cut keys that will be useful in working with VS 2005.
Guess its no point introducing some thing common, only the uncommon ones are listed here. Most of you may already be familiar, but for the ones who don't know...hope its useful.
Format a line : Ctrl + K + D
Delete a line : Ctrl + L
If you need to delete or format a code segment, you may select the expected area of code before going for the key combination.
Get a blank line on top of a line of code : Ctrl + Enter
Search for a line number : Ctrl + G
Find and replace : Ctrl + F
Obtain full screen mode : Alt + Shift + Enter
Build the solution : Ctrl + Shift + B
Comment a block of code : Ctrl + K + C
Un-comment a block of code :  Ctrl + K + U

Thursday, October 14, 2010

Difference Between C Sharp and VB.NET

Advantages VB.NET:
Has support for optional parameters which makes COM interoperability much easy.
With Option Strict off late binding is supported.Legacy VB functionalities can be used by using Microsoft.VisualBasic namespace.
Has the WITH construct which is not in C#.
The VB.NET part of Visual Studio .NET compiles your code in the background.
While this is considered an advantage for small projects, people creating very large projects have found that the IDE slows down considerably as the project gets larger.
Advantages of C#
XML documentation is generated from source code but this is now been incorporated in Whidbey.
Operator overloading which is not in current VB.NET but is been introduced in Whidbey.
Use of this statement makes unmanaged resource disposal simple.
Access to Unsafe code. This allows pointer arithmetic etc, and can improve performance in some situations. However, it is not to be used lightly, as a lot of the normal safety of C# is lost (as the name implies).This is the major difference that you can access unmanaged code in C# and not in VB.NET.
System exceptions and application exceptions:
All exception derives from Exception Base class. Exceptions can be generated programmatically or can be generated by system. Application Exception serves as the base class for all application specific exception classes. It derives from Exception but does not provide any extended functionality.
You should derive your custom application exceptions from Application Exception. Application exception is used when we want to define user defined exception, while system exception is all which is defined by .NET.
Preventing de compilation of dot net DLL:
By design .NET embeds rich Meta data inside the executable code using MSIL. Any one can easily decompile your DLL back using tools like ILDASM (owned by Microsoft) or Reflector for .NET which is a third party. Secondly there are many third party tools which make this decompiling process a click away.
So any one can easily look in to your assemblies and reverse engineer them back in to actual source code and understand some real good logic which can make it easy to crack your application.
The process by which you can stop this reverse engineering is using "obfuscation". It's a technique which will foil the decompilers. There are many third parties (XenoCode, Demeanor for .NET) which provide .NET obfuscation solution. Microsoft includes one that is Dotfuscator Community Edition with Visual Studio.NET.

What is the difference between C and C Sharp?

#1) C is unmanaged code, and C# is managed by the .NET CLR (Common Language Runtime)

Managed code means that many of the low-level activities that one has to worry about with C, such as memory management, garbage collection, pointers, etc, are automatically handled for you.

#2) C# is an object orienated language. C is a structed language. However, if you were referring to C++, then both C# and C++ have similar (although not identical) object orienated capabilities.


C is a procedural programming language developed in AT&T-Bell labs. It has been in use for about four decades for system and application programming. It has been ported to lots of CPUs and operating systems.
C-sharp (C#) is an object oriented programming language developed by Microsoft for use in its .NET framework. It is much newer, and only works on Microsoft operating systems. C#, like many other programming languages, is a descendant of C - they share some syntactic conventions. 

Difference between c and c++

History of C Language

The C programming language was designed by Dennies Ritchie in the early 1970s at Bell Laboratories. It was first used system implementation language for the nascent Unix operating system. The main reason to devised C was to overcome the limitations of B.  It was Derived from the type-less language BCPL ((Basic Combined Programming Language). C was was the evolution of B and BCPL by incorporating type checking. It was originally intended for use in writing compilers for other languages.

History of C++

C++ was devised by Bjarne Stroustrup in 1983 at Bell Laboratories. It is an extension of C by adding some enhancements to C language. Bjarne combined the simula's(a language designed for making simulations, created by Ole-Johan Dahl and Kristen Nygaard) features of object oriented and the efficiency of C. The new features added to language are templates, namespaces, exception handling and use of standary library.

Difference between c and c++

C++ is an extension of C language. This means that you can not only use the new features introduced with C++ but can also use the power and efficiency of C language. C and C++ are no more language for writing compilers and other languages, these general purpose languages are used worldwide in every field.
Here is a list of differences between c and c++.
The main difference between C and C++ is that C++ is object oriented while C is function or procedure oriented. Object oriented programming paradigm is focused on writing programs that are more readable and maintainable. It also helps the reuse of code by packaging a group of similar objects or using the concept of component programming model.  It helps thinking in a logical way by using the concept of real world concepts of objects, inheritance and polymorphism. It should be noted that there are also some drawbacks of such features. For example using polymorphism in a program can slow down the performance of that program.
On the other hand, functional and procedural programming focus primarily on the actions and events, and the programming model focuses on the logical assertions that trigger execution of program code.

Introduction to SQL Triggers

SQL trigger is an SQL statements or a set of SQL statements which is stored to be activated or fired when an event associating with a database table occurs. The event can be any event including INSERT, UPDATE  and DELETE.
Sometimes a trigger is referred as a special kind of stored procedure in term of procedural code inside its body. The difference between a trigger and a stored procedure is that a trigger is activated or called when an event happens in a database table, a stored procedure must be called explicitly. For example you can have some business logic to do before or after inserting a new record in a database table.
Before applying trigger in your database project, you should know its pros and cons to use it properly.

Advantages of using SQL trigger

  • SQL Trigger provides an alternative way to check integrity.
  • SQL trigger can catch the errors in business logic in the database level.
  • SQL trigger provides an alternative way to run scheduled tasks. With SQL trigger, you don’t have to wait to run the scheduled tasks. You can handle those tasks before or after changes being made to database tables.
  • SQL trigger is very useful when you use it to audit the changes of data in a database table.

Disadvantages of using SQL trigger

  • SQL trigger only can provide extended validation and cannot replace all the validations. Some simple validations can be done in the application level.  For example, you can validate input check in the client side by using javascript or in the server side by server script using PHP or ASP.NET.
  • SQL Triggers executes invisibly from client-application which connects to the database server so it is difficult to figure out what happen underlying database layer.
  • SQL Triggers run every updates made to the table therefore it adds workload to the database and cause system runs slower.
Triggers or stored procedures? It depends on the the situation but it is practical that if you have no way to get the work done with stored procedure, think about triggers.

Some of the difference between MSSQL and MYSQL Syntax are as follows:

1) MSSQL support UDD(User Defined DataTypes), MYSQL does not support UDD

2) Use of -- for comment a line purpose in MSSQL, in otherside use /* */ or -- comments

3) Use prefix @symbol for variable in MSSQL, whereas in MYSQL remove @symbol.
e.g. declare @test int -- MSSQL Syntax
declare test int; --MYSQL Syntax

4) End marker(;) not required in MSSQL but in MYSQL all statement end with marker (;)

5) In MSSQL use SELECT getdate() for getting today's date , in MYSQL use SELECT now()

6) All queries should be available in Begin tran and Commit(Rollback) tran loop in MSSQL,
whereas MYSQL Start transaction and commit(Rollback) transaction.

7) Getting Top most record in MSSQL, Use SELECT TOP1 from Table_Name where
In MYSQl SELECT from Table_Name where limit 1;

8) For viewing table information use Sp_help Table_name in MSSQL, but in MYSQL use show table_name;

9) Use of + for concatenate two stings in MSSQLL whereas MYSQL SELECT concat('a','/','b')

10)In MSSQL SP_HELPTEXT for viewing the content of sp in otherside use the following syntax.
select routine_definition from information_schema.routines
where specific_name =
and routine_schema = ;

11)For assigning value to variable use Set @variable1 = 'test' in MSSQL,
but in MYSQL use Set variable =1 or set 1 into variable1;

12)In MSSQl, use of IF statement syntax,
if
Begin
Statement
end
Else
Begin
Statement
end
Whereas in MYSQL,
if Then
Statement;
leave sp_label;
end if;

13) In MSSQL Use RETURN Statement for returning values but in MYSQL use leave sp_level;

14) The convert datatype Syntax in MSSQL is select convert(type,expression) whereas in MYSQL select convert(expression,type);

15) In MSSQL the Dynamic SQL statement is
SELECT @a ='SELECT * from Table_Name where
execute (@a)
otherside
Prepare stmt1 from 'select * from Table_Name where column_name =?'
Set @a ='Value';
execute stmt using @a;

Wednesday, October 13, 2010

Validation - CustomValidator

If none of the other validators can help you, the CustomValidator usually can. It doesn't come with a predefined way of working; you write the code for validating your self. This is of course very powerful, since the possibilities are basically endless. A common way of using the CustomValidator is when you need to make a database lookup to see if the value is valid. Since this tutorial hasn't treated database access yet, we will do a simpler example, but hopefully you will see that you can do just about everything with the CustomValidator. The control allows you to validate both clientside and serverside, where the serverside approach is probably the most powerful. Of course, doing serverside validation requires a postback to validate, but in most cases, that's not really a problem.

In this example, we will simply check the length of the string in the TextBox. This is a very basic and that useful example, only made to show you how you may use the CustomValidator.

Custom text:<br />
<asp:TextBox runat="server" id="txtCustom" />
<asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtCustom" onservervalidate="cusCustom_ServerValidate" errormessage="The text must be exactly 8 characters long!" /> 
 
 
As you can see, it's pretty simple. The only unknown property is the onservervalidate
 event. It's used to reference a method from CodeBehind which will 
handle the validation. Switch to our CodeBehind file and add the 
following method: 
 
protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
    if(e.Value.Length == 8)
        e.IsValid = true;
    else
        e.IsValid = false;
}  
This is very simple. The validator basically works by setting the 
e.IsValid boolean value to either true or false. Here we check the 
e.Value, which is the string of the control being validated, for it's 
length. If it's exactly 8 characters long, we return true, otherwise we 
return false. 


Saturday, October 2, 2010

validation

Custom Validator Sample

This sample demonstrates how to use Custom Validator for both server- and client-side validation.
Run Custom Validator Sample
In this sample my custom validator checks your credit card expiration date. Firstly, look to the validator:
<vlvalidator name="ExpDate" type="custom" errmsg="Something wrong" function="phpExpDateCheck" clientfunction="jsExpDateCheck">
Note that my validator doesn't have control attribute. If you add controll attribute to your custom validator you will get this control value from the parameter of custom validation function. In this example I will validate two input fields, so, anyway I need to get values by myself.

Client-side Validation

As you can see client-side validation function name is jsExpDateCheck. Client-side validation function must be javascript function defined on the same page as the validated form. It should have the following prototype:
void validationFunctionName(oStatus)
where oStatus parameter is javascript object with the following properties:
isvalid - you must set here result of validation. If you do not set it, validator evaluated to true value - validation passed.
errmsg - used to customize error message, will be displayed in the Summary.
value - contains current value of input element being validated. If input element (control attribute) is not defined it contains null.
Now look at my jsExpDateCheck function (find it in the code bellow). It fully conforms to prototype - have one and only one parameter. My code retrieves current control values using HTML DOM:
year = document.forms["Custom"].elements["ExpYear"].value;
month = document.forms["Custom"].elements["ExpMonth"].value;

Then my code decides is this data valid or not. If valid then I do not need to do anything. Invalid status can be set this way:
oStatus.isvalid = false;
oStatus.errmsg = "The credit date entered is not valid";

Client-side validation is optional and very often can't be implemented (when you need access to database for example). In most cases you will not write client-side custom validation function.

Server-side Validation

You must always implement server-side validation for a custom validator. Server-side validation function must be php function defined on the action page (page specified in the form action attribute). This function should have the following prototype:
void validationFunctionName($sValue, &$oStatus)
where string parameter $sValue contains value of input element being validated. If input element is not defined it contains null.
$oStatus is object of CVDValidatorStatus type (declared in vdaemon.php file). It has the following properties:
bValid - you must set here result of validation. If you do not set it, validator evaluated to true value.
sErrMsg - used to customize error message, will be displayed in the Summary.
My server-side custom validation function name is phpExpDateCheck (again find it bellow in the code of custom_p.php file). It has exactly two parameters (second parameter passed by reference) as prototype requires. My code gets values for validation from $_POST array:
$nMonth = $_POST['ExpMonth'];
$nYear = $_POST['ExpYear'];

and then decides is this data valid or not. If valid then I do not need to do anything. Invalid status can be set this way:
$oStatus->bValid = false;
$oStatus->sErrMsg = "The credit date entered is not valid";

Conclusion: it is not recomended to do any output from custom validation function (echo, print, etc).
Run Custom Validator Sample