inputbox in C#
I wanted to add a input box in my new windows program which is in C#.Net, suddenly I realised that there is no input dialog box with C#.Net but I found a link to do a input dialog box, which was really helpfull. I think it would be really helpfull you guys as well.
http://www.knowdotnet.com/articles/inputbox.html
SQL LIKE THAN YOU LIKE
Do not confuse with the title, let me explain what it is. Consider about the following table,
(Persons)
One might need to get only the FirstName that starts with letter ‘W’
in this case we can write our query as follows
SELECT * FROM Persons WHERE FirstName LIKE 'W%'
Result would be
OK cool , what if you need to get all the records that FirstName starts
with letter ‘W’ and letter ‘R’, in this case I am sure most of developes
query would be as follows.
SELECT * FROM Persons WHERE FirstName LIKE 'W%' OR FirstName LIKE 'R%'
Fine, you got the result what you expected but there is another way to do this
without using OR FirstName LIKE ‘R%’
SELECT * FROM Persons WHERE FirstName LIKE '[WR]%'
Don’t you think this is better? Keep in mind you can use this not only for the first letter
you can use this for last letter even you can use with negation ( LIKE ‘[^WR]%’)
Get percentage of records from a table
Have you ever come across a situation where you need to get top 25%
records from a table. Here is the SQL that returns first 25% of records from a table.
SELECT TOP 25 PERCENT *
FROM dbo.yourtable
This will return what you want, the 25% of records from the table. What if you want the second 25% of records.
SELECT TOP 50 PERCENT *
FROM ( SELECT TOP 50 PERCENT *
FROM dbo.yourtable) results ORDER BY 1 DESC
On the above query by descending the records by first column, assuming that it is the primerykey or the records we need to filter by, you will get the top 25% which is the second 25% of the records.
Think how to get the third and the last 25% records leisurely.
ConnectionStringBuilders
Connection string is a string variable which include many properties and values (InitialCatelog, uid, pwd , Data Source) needs to connect to a database.
SqlConnection cn = new SqlConnection();
cn.ConnectionString ="uid=sa;pwd=Initial Catalog=ADO; Data Source=(local); ConnectTimeout = 30";
cn.Open();
Creating connection string is bit tedious as it’s a string and could be error prone.
ADO.Net providers support connection string builder objects which allow you to create connection string , and establish the name/value pairs using strongly typed properties.
SqlConnectionStringBuilder cnStrBuilder = new SqlConnectionStringBuilder();
cnStrBuilder.UserID = "sa";
cnStrBuilder.Password = "";
cnStrBuilder.InitialCatalog = "ADO";
cnStrBuilder.DataSource = "(local)";
cnStrBuilder.ConnectTimeout = 30;
SqlConnection cn = new SqlConnection();
cn.ConnectionString = cnStrBuilder.ConnectionString;
Here on above example , creates a SqlConnectionStringBuilder variable and passing values for
ConnectionStringBuilder properties and then the ConnectionStringBuilder’s ConnectionString value been assigned to cn.ConnectionString instead directly passing ConnectionString string
as follows.
cn.ConnectionString ="uid=sa;pwd=Initial Catalog=ADO; Data Source=(local); ";
C# File.WriteAllText, File.ReadAllText & File.WriteAllLines
Most of the times as developers we have to work with text files, as it’s a very simple way to store some data. There are very valuable methods available in File class that we are not using most often.
Look at the following example which writes a formatted string to a text file with new lines.
This is more readable than WriteLine() method. If you use WriteLine() Method then you will have to write line by line most probably you may have to use a loop.
protected void btnTextManipulation_Click(objectsender, EventArgs e)
{
//gets the file path
stringfilePath = Server.MapPath("Files/test.txt");
StringBuilder content = new StringBuilder();
//note the end of this line i.e \r\n this says enter a new line
content.Append("This is the first line. \r\n");
content.Append("This is the secont line. \r\n");
//Environment.NewLine this says enter a new line too
content.Append("This is the last line."+ Environment.NewLine);
//Writes to test.txt
WriteText(filePath, content.ToString());
//reads from test.txt and asssing to a variable
stringreadTxt = ReadText(filePath);
filePath = Server.MapPath("Files/test2.txt");
//Writes to test2.txt
WriteText(filePath, readTxt);
}
public void WriteText(stringpath, stringcontent)
{
//this file method writes all test you pass
File.WriteAllText(path, content);
}
public string ReadText(stringpath)
{
//this file method reads whole content of the text file.
returnFile.ReadAllText(path);
}
I will show another example which writes array items in new lines.In the following example WriteAllines() method writesall the items in an array as a new line. With using WriteAllLines() method you can avoid a loop, hich needs to loop through the array and WriteLine to the text file.
protected void btnTextManipulation_Click1(object sender, EventArgs e)
{
//get the file path
string filePath = Server.MapPath("Files/test.txt");
//declare and assign a string array
string[] content = { "This is the first line.", "his is the secont line.", "This is the last line." };
WriteArrayText(filePath, content);
}
public void WriteArrayText(string path, string[] content)
{
//this file method writes all test you pass
File.WriteAllLines(path, content);
}
Enable session state on a Web Methods, Web service
By default each web method session state is disabled.
Example:
Declare and assign a session variable in Global.asax Session_Start.
void Session_Start(objectsender, EventArgs e)
{
Session["Overhead"] = 3;
}
Access this session variable (Session["Overhead"] ) in Add Web Method.
[WebMethod(Description = "adds x , y and Overhead session")]
public int Add(int x, int y)
{
return (x + y) + (int)Session["Overhead"] ;
}
This will not work and throws an error. To avoid this needs to enable session state in each web metods.
Example:
[WebMethod(EnableSession = true, Description = "adds x , y and Overhead session")]
public int Add(int x, int y)
{
return(x + y) + (int)Session["Overhead"] ;
}
In this above example in the [WebMethod] attribute EnableSession property has explicitily set to true. Now the Add web method is retrieving Session["Overhead"] variable’s value. All you have to do is just enable the session in [WebMethod] attribute.
WebService Method Overloading
Thursday, July 30, 2009
WebService Method Overloading
First of all what is method overloading ?
Method means having more than one method with the same name but different signature is the simple definition.
Example:
private int Add(int x, int y)
{
return x + y;
}
private int Add(int x)
{
return x + 3;
}
private float Add(float x, float y)
{
return x + y;
}
Above three methods have the same name but different signature.
The following table shows the signature difference among Add methods.
Though method overloading allowed in .Net, it's not allowed in web services as to comply with a rule (WSI BP 1.1 is that each method within a WSDL document must be unique), This clearly emphasis on method overloading. But by using [WebMethod] attribute we can use method overloading. With [WebMethod] pass the MessageName then web service uniquely identifies the overloaded methods.
Example:
[WebMethod(Description = "Adds two integers.",MessageName = "AddInts")]
private int Add(int x, int y)
{
return x + y;
}
[WebMethod(Description = "Adds 3 on an int value.",MessageName "AddThree")]
private int Add(int x)
{
return x + 3;
}
[WebMethod(Description = "Adds two floats.", MessageName = "AddFloats")]
private float Add(float x, float y)
{
return x + y;
}
Here on above three Add methods have unique MessageName as to allow method overloading in web services
VS2010 Beta C# 4.0 Optional parameters, named arguments A feature I was waiting for..
What is an optional argument?
Arguments must be provided when calling a method if it is not an optional parameter, but can omit arguments for optional parameters.
Example:
VB6.0
Public Function PurchaseOrder(ByVal vPurOrdNo As String, Optional vNotes As Variant)
''Coding....
End Function
on the above example PurchaseOrder function can be called in both ways as follows,
call PurchaseOrder("2010", "passing value to optional argument")
or
call PurchaseOrder("2010")
I was wondering why Microsoft dosn't introduce this feture in visual c# as it's provide such a richness for the language. I heard a good news, .Net 4.0 framework has this feture with named arguments.
* Each optional parameter has a default value as part of its definition
* If argument not passed for optional parameter then the default value will be used.
* Optional parameters must be declared after all the normal parameters (most right side)
Here is the above example PurchaseOrder method is C#
public class OptionalArgumentExample
{
static void Main(string[] args)
{
// Instance anExample does not send an argument for the constructor's
// optional parameter.
PurchaseOrder("2010", "passing value to optional argument");
PurchaseOrder(("2010");
}
// optional parameters needs to be defined with default values. in this
// example "notes" paramete has a default value, so the here the "notes"
//parametes is optional.
public void PurchaseOrder(string purordno, string notes= "default string")
{
//coding here..
}
}
What is a named argument?
Named arguments allows you to pass an argument for a parameter with the parameter's name rather than with the parameter's position in the parameter list.
Example:
C# .Net4.0
public class NameArgumentExample
{
static void Main(string[] args)
{
// Calling normal way
Console.WriteLine(CalculateInterest(5000, 10));
// passing with named arguments any order
Console.WriteLine(CalculateInterest(capitol: 5000, interestRate: 10));
Console.WriteLine(CalculateInterest(interestRate: 10, capitol: 5000));
}
static int CalculateInterest(int capitol, int interestRate)
{
return (( capitol / 100) * interestRate );
}
}
Rare validation
validation control to achieve this but www.asp.net has recommended a validation
control i.e CheckValidator which is a .dll (AT.Web.UI.Validators.dll
) and can be added to the tool panel. I added this to my validation controls section .
Can be used as normal validation control to validate checkboxes and radio boxes.
<"asp:checkbox ID="chkAgreement" runat="server" Text="I have read the agreement" /">
<"asp:Button ID="btnSubmit" runat="server" Style="z-index: 100; left: 129px; position: absolute; top: 77px" Text="Submit" /">
<"at:CheckValidator ID="_checkValidator" runat="server" ControlToValidate="chkAgreement" Text="Please accept the agreement" style="z-index: 102; left: 15px; position: absolute; top: 47px"">
<"/at:CheckValidator">
A personal belief
in Sri Lanka. I personally believe we are not yet independent though Mr. Bandaranayake
spelled it several times. As declaring Sinhalese as the official language he created a gap between poor and rich, conflict between Tamils and Sinhalese and a opportunity to learn English which could have bring most success to our country,
Watch this video and feel free to comment my personal vision.
http://www.youtube.com/watch?v=rbL5E5naR6s
Session variable lifetime
Before I talk about session variable's life time, Ill just brief why a session variable comes in to play with a web application.
A session is a mechanism to maintain state on a web application, as HTTP protocol is a stateless protocol. What does it means by stateless? this protocol (HTTP) serves as the request comes and destroys all the data (information) on a request. Pages are destroyed and recreated with each round trip to server. Session variables comes in to play when there is a requirement to maintain the state of a web application. Do not misunderstand that session is not the only mechanism to available to maintain state of a web application. Ok, will get back to the topic.
On an ASP.Net application session variable's expiry time decides the life time of a Session
set in the web.config configuration section under
Example:
< sessionState mode="InProc" timeout="20" >
In the above example the timeout = "20" sets the
expiry time of session variables to 20 minutes.
A tip to avoid SQL injection
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(
"select * from Orders where OrderID= '" + passOrderID + "'";
An user can pass anything to passOrderID , this leads a hacker to easily replace
string with something malicious. As shown in the above bad example do not build
dynamic strings, instead use parameters. Anything passed to a parameter considered
as field data and not as part of SQL statement, This avoids above malicious scenario.
Following code snippet demos a parametrized querying steps,
//define SQLCommand object
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(
"select * from Orders where OrderID= @OrderID", conn);
//define parameters used in SQLCommand object
SqlParameter para = new SqlParameter();
para.ParameterName = "@OrderID";
para.Value = passOrderID;
// add parameter to SQLCommand object
cmd.Parameters.Add(para);
or in one line
cmd.Parameters.Add(new SqlParameter("@OrderID",passOrderID));
This makes the application more secure.
Early and Late Binding
Example:
' Create a variable to hold a new object of type File Stream.
Dim fs As System.IO.FileStream
Declaring an variable with type object called Late Binding,
later this variable can hold any object type.
' Create a variable to hold a new object
Dim anyObject As Object
or
Dim fs
' Later you can assign any object type to this variable
anyObject = CreateObject("Excel.Application")
or you can use the anyObject to hold any other your object type
anyObject = CreateObject("Define.Start")
maintain scrollposition after post back?
By default a web page will be returned to the top of the page, after a postback. What if you want to take back to the position where user was before the postback , it's simple. You can do one of the followings.
In the web.config add the attribute to the pages node.
In the HTML (.ASPX)
< %@ Page Language="C#" MaintainScrollPositionOnPostback = "true"
and you can set this in
3.CODE (ASPX.SC)
Page.MaintainScrollPositionOnPostBack = true;
That's all you have to do. You will be back to where you were.
static Vs instance methods
So there might be a slight performance issue and this can be ignored as it's not make much impact on performance.
Choosing your method to be static or instance will depend upon the design. If the method going to be used as an object then it should be an instance method. If it doesn't depend on an instance of an object, it should be static. Static methods belong to a type and instance methods belong to instance of a type.
example
Public Class Car
{
// this is a static method
public static void staticMethod()
{
//your code
}
// this is an instance method
public void instanceMethod()
{
//your code
}
}
Accessing static method
Car.staticMethod();
Accessing instance method
Car car = new Car();
car.instanceMethod();
Deployment Project - Cannot open the file 'ASPNETCOMPILER'
"Cannot open the file 'ASPNETCOMPILER'. The document cannot be opened. It has been renamed,deleted or removed".
The solution is, take your deployment project folder out from the site folder (root).
For example : if your project path is "D:\Projects\Ads" then have the deployment folder in "D:\Projects\Deployment". Don't have the deployment folder in site's folder itself as "D:\Projects\Ads\Deployment".
32-Bit application on 64-Bit server with IIS7
Guys, I had to configure a website which is 32 bit, on a 64 bit server with IIS 7. As you know 64 bit servers doesn’t support 32 bit applications but lucky me, IIS has a feature to enable this
It's so easy. In IIs go to Application Pool Right click on your web site and then go to "Advance Settings" , You will get a property called "Enable 32-Bit Applications" change its value to "True". That's all you have to do .
Scared on OOP.....
Hay guys, You might be thinking why I am back on my blog after a long time. It's simply b'cause the encourage I got from one of my friends called Gogula and I use to call him gogus most of the time. Thanks man. Ok, here I start it again with OOP & C# .
Before I start anything on this topic let me explain what is an object.
What is an object?
Ha, that could be anything around you in real world. For example your CPU.
What we should consider of an object as a programmer? It's state and the behavior.
I wil just take a scenario that would helpfull you to understand as a programmer, what is an object?. If you were asked to develop a student enrolment application what would you conside as your objects in this application. I will point two objects Student and the Course but there are many more, I will leave you to point after reading this blog.
As I have mentioned above we bothered about state and the behavior of an object.
An object's state is the data and information it contains. For example, If you have a CPU object, it's state could be RAM speed and hard disck capacity. An object's bahavior represeted by it's methods. For example, in your CPU object play movie could be a method.
There are three underline concepts
Encapsulation
Inheritance
Polymorphism
Encapsulation
Encapsulation is a process of binding both data and methods together inside of an object.
Protection and information hiding are techniques used to accomplish encapsulation of an
object. Conside the following Class.
public class Box{
public Box()
{
}
protected double height;
protected double width;
protected double length;
public double GetVolume()
{
double volume = height*width*length;
if(volume<0)>
return volume;
}
}
Classic ASP debugging
use <'% stop %''>it will break the execution on the stop statement and u can debug in VSInterDev.
Classic ASP debugging
"<%Stop%>" this will do the magic
... <% stop %>it will break the execution on the stop statement and u can debug in VSInterDev.
Blog Archive
Important Blogs
-
-
BDD with Rails and Cucumber11 years ago
-
-
Watch Live Cricket Online Free16 years ago
-
BBC and Mahinda Rajapakshe17 years ago
-
-
