Wednesday, November 18, 2009

Windows 7 Virtual Wifi

Windows Virtual Wifi(abbreviated to VWiFi) is a new concept of Microsoft introduced in the version Windows 7.0.

Through this a sigle LAN Card acts as two network adapters.
One acts in STA (short for "station") mode and other acts in AP (Access Point) mode.

This is achieved through the drivers (softwares of Microsoft). Each connection act as a separate layer in the driver. Through this technology each machine will act as a wifi access-point. This facility is not provided in the beta version. In the network connection section “'Wireless Network Connection 2” will be available in Windows 7.

How to configuring the VWifi in the machine


In command prompt type the command in the following format to create a new access point say “APnew”
netsh wlan set hostednetwork mode=allow ssid=APnew key=password
New Access Point can be started directly from control panel


Thanks to Microsoft to share this knowledge
msdn.microsoft.com/en-us/library/dd445708.aspx

Tuesday, November 17, 2009

This article is a heads up to the cloud computing concept introduced in .NET 4.0

"Azure" is project name from Microsoft for Cloud Computing. They are going to introduce this from the upcoming version of .NET Framework 4.0. It might make a dramatic changes in the existing Web applications.

Through Cloud computing Microsoft targets for platform independency in their applications.
That is Each web can communicate to any other servers directly.

Advantages for ASP.NET applications:
Following are the advantages of ASP.NET applications by implementing Cloud computing.

1) Cost cutting - Both the small & large scall organizations can implement this.
2) More storage for Data.
3) Mobilitiy of Data - Data can be moved to any kind of servers(e.g Data can easily moved to Unix based machine from Windows).
4) More advantages on BCP(Disaster recoverty etc) plans

By the implementation of Cloud computing, the Web application will give the same level of performance even the traffic to the site is at the peak.

Disadvantages:

Following jobs will be very hectic by the implementation of Azure.

1) Implementation of session
2) Implementation of authentication
3) System Integration.
4) Migration of existing application

Nesting Gridview in Repeater

Once I have tried to nest Gridview in a Repeater, you might wondering why we require this.

The scenario was like that. Grid view has some limitations. Main thing is we can show the data in columns. But my rquirement was showing the first row as a heading.

As follows

-------------------Heading A category name from a query----------------------
-------------------Details about that category from the same query-----------
-------------------Details about that category from the same query-----------
-------------------Details about that category from the same query-----------
-------------------Details about that category from the same query-----------
-------------------Details about that category from the same query-----------
Slno name description Date
---- ------------ ------------------ -----------------
---- ------------ ------------------ -----------------
---- ------------ ------------------ -----------------
---- ------------ ------------------ -----------------

I hope the above example can give an outline about the scenario. I went for repeater with gridview.


<asp:UpdatePanel ID="updPanel" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:Repeater ID="rptid" runat="server" OnItemDataBound="rptid_RowDataBound" EnableViewState="false">
<ItemTemplate>
<table cellpadding="0" cellspacing="0" width="90%">
<tr>
<td>
 
</td>
</tr>
<tr>
<td id="tdid" class="style" align="left" runat="server" title="Click Here to expand/Collapse">
<asp:Label ID="lblCategory" CssClass="Header" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"CategoryID")%>' EnableViewState="false"></asp:Label>
<asp:HiddenField id="hidCategory" runat="server" value='<%#DataBinder.Eval(Container.DataItem," CategoryID")%>'/>
</td>
</tr>
<tr>
<td>
 
</td>
</tr>
<tr>
<tr>
<td>
<asp:GridView ID="grdDetails" runat="server" AllowPaging="false" EmptyDataText="No Data Available" SkinID="skinid " EnableViewState="false" Width="100%" style="display:none">
<Columns>
<asp:BoundField DataField="AgreementName" HeaderText=" Award Agreement Name" />
---------------------------Bind Code goes here-------------------------------
---------------------------Bind Code goes here-------------------------------
---------------------------Bind Code goes here-------------------------------
---------------------------Bind Code goes here-------------------------------
---------------------------Bind Code goes here-------------------------------
---------------------------Bind Code goes here-------------------------------
---------------------------Bind Code goes here-------------------------------
---------------------------Bind Code goes here-------------------------------
</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td>
 
</td>
</tr>
</ItemTemplate>
</asp:Repeater>

In code behind we need to use gridview from the rowdatabound of repeater itself as shown below.
protected void rptid_RowDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
---------------------------Bind Code goes here-------------------------------
---------------------------Bind Code goes here-------------------------------
GridView grdDetails = (GridView)e.Item.FindControl("grdDetails");
---------------------------Bind Code goes here-------------------------------
}

Main Differences between ASP.NET 3.5 and ASP.NET 4.0

Main Differences between ASP.NET 3.5 and ASP.NET 4.0
As we all know, ASP.NET 3.5 has introduced with the following main new features
1) AJAX integration
2) LINQ
3) Automatic Properties
4) Lambda expressions
I hope it would be useful for everyone to know about the differences about asp.net 3.5 and its next version asp.net 4.0
Because of space consumption I’ll list only some of them here.
1) Client Data access
ASP.NET 3.5: There is no direct method to access data from client side. We can go for any of these methods
1) Pagemethods of script manager
2) ICallbackEventHandler interface
3) XMLHttphanlder component
ASP.NET 4.0: In this framework there is an inbuilt feature for this. Following are the methods to implement them.
• Client data controls
• Client templates
• Client data context
i.e we can access the data through client data view & data context objects from client side.
2) Setting Meta keyword and Meta description
Meta keywords and description are really useful for the search engine listings.
ASP.NET 3.5: It has a feature to add meta as following tag
<meta name="keywords" content="These, are, my, keywords" />
<meta name="description" content="This is the description of my page" />

ASP.NET 4.0: Here we can add the keywords and description in Page directives itself as shown below.
<%@ Page Language="C#" CodeFile="Default.aspx.cs"
Inherits="_Default"
Keywords="Keyword1,Key2,Key3,etc"
Description="description" %>

2) Enableviewstage property for each control
ASP.NET 3.5: this property has two values “True” or “false”
ASP.NET 4.0: ViewStateMode property takes an enumeration that has three values: Enabled, Disabled, and Inherit.
Here inherit is the default value for child controls of a control.
3) Setting Client IDs

Some times ClientID property creates head ach for the programmers.

ASP.NET 3.5: We have to use ClientID property to find out the id which is dynamically generated
ASP.NET 4.0: The new ClientIDMode property is introduced to minimize the issues of earlier versions of ASP.NET.
It has following values.
AutoID – Same as ASP.NET 3.5
Static – There won’t be any separate clientid generated at run time
Predictable-These are used particularly in datacontrols. Format is like clientIDrowsuffix with the clientid vlaue
Inherit- This value specifies that a control's ID generation is the same as its parent.

Thursday, November 12, 2009

Threats to the websites

Following are the threats to a normal website(not a secured one).

1) Excess Privileges & Tampering : If a user gets more permission than required & Modification of resources/WebPages without authorization
2) Spoofing : Using another users credentials to login to the system and modify the contents
3) Backdoors : Use developer created maintenance hooks to logon to the system
4) Information Disclosure : Eg disclosure of users Credit card information

But Don’t feel like there is no solution for these threats.
Following are them.

1) Tampering:

These are very common with less secured sites. You have to cross verify all the security permissions. Most of them can be caught at the time of unit testing itself.

Following are the tips to avoid tampering in the application.
1) Don’t pass any sensitive information through query strings
2) Use encryption for all sensitive data
3) Don’t store any sensitive data in cookies.
4) 4) Check for cookies safety always.( add <httpCookies domain="String" httpOnlyCookies="true" requireSSL="false" /> in config file)
5) the application side vulnerabilities including SQL injection occurs when user input is not filtered for escape characters and is then passed into a SQL statement. This result in the potential manipulation of the statements performed on the database by the end user of the application. Another eg is an anonymous user is allowed to access privileged area in an application which is somehow bypassed while testing the application.
6) Run the application with minimum privileges

2) Spoofing.

Mostly spoofing is happened by the weak passwords. So the application should enforce the user to have a strong password. It should have a certain standard. E.g. 6charactered alphanumerical passwords with extra characters like #, $ * can consider as a strong one. Also alphabets and numeric should be in a combination mode.

3) Backdoors
Backdoors are being developer created holes to bypass the actual authentication and logon to the system easily for maintenance purposes. These vulnerabilities should be closed before making the application online.

4) Backdoors Information Disclosure: Information disclosure can happen in several ways including hacking activity, low application/server security; failure in using encryption for critical data, login information and another big element is humans. Most of the application/server securities issues can be mitigated by applying patches, implementing SSL etc.but the difficult part is humans associated with each project. When they move from one to another company some critical information like passwords/backdoors etc also goes with them. Even though completely removing the risk is impossible some of the things we can do to reduce the risk are: Non Disclosure Agreements when the employee leaving the organization. And Exit interview explaining the consequences of disclosing the information.
Disabling logins and changing all passwords whenever an employee terminate/leave

Things to consider:
1. Consider the security of the application from the initial stages of the project.
2. Testing of the software should include application side vulnerabilities and input text filtering capabilities which cause buffer overflows.
3. Change default passwords and remove unwanted accounts from the application before moving the system to production. Passwords policies should be enforced in the application.
4. Infra team should take care of server vulnerabilities. Update patches and antivirus patterns on a regular basis. Lock down files, directories, and other resources. The application should also run with minimum privileges
5. The application administrator should be careful about giving privileges to each user.
6. Implement SSL for critical data and passing credentials.
7. Limiting the application access by predefining IP Address or number of allowed connections at web server level.
8. Let the developers provide the installation docs to the Server admin team and let them deploy the application on the production server.
9. Periodic evaluation of security in all servers and applications.
10. Sign Non Disclosure Agreement when the employee leaving the organization.
11. Exit interview explaining the consequences of disclosing the information.
12. Disabling logins and changing all passwords whenever an employee terminate/leave

Connect to a MSSQL(SqlServer)

Even though LAMP is the most familiar compination we can try with other databases too in PHP. Here is a sample for connecting to SQLServer from PHP.

<?php
$myServer = "ServerName";
$myUser = "UserName";
$myPass = "Password";
$myDB = "DBName";


$dbhandle = mssql_connect($myServer, $myUser, $myPass) or die("Connection Failed");
$selected = mssql_select_db($myDB, $dbhandle) or die("Couldn't open the db");
$query = "SELECT postid, postname, time";
$query .= "FROM Revolution-of-web";
$query .= "WHERE label='PHP'";

$result = mssql_query($query);

$numRows = mssql_num_rows($result);
echo "<h1>" . $numRows . " Row" . ($numRows == 1 ? "" : "s") . " Returned </h1>";

while($row = mssql_fetch_array($result))
{
echo "<li>" . $row["postid"] . $row["postname"] . $row["time"] . "</li>";
}
mssql_close($dbhandle);
?>

Sending mails by PHP.

Most of the time people are struggling with mailing concept of PHP.
Here is an example to achieve this.

<form action="sendmail.php3" method="POST">
<input type="text" size="22" name="subject" value="MailContent">

< form action="sendmail.php3" method="POST">
< input type="text" size="22" name="subject" value="MailContent">


<?
$to = "Senderemail@revolution-of-web.blogspot.com";
$from_header = "From: $from";
if($contents != "")
{
mail($to, $subject, $contents, $from_header);
header("Location: $HTTP_REFERER");
}
else
{
print("<HTML><BODY>Error, no comments were submitted!");
print("</BODY></HTML>");
}
?>


Here header("Location: $HTTP_REFERER"); will redirect back to the same url that visitor has came from.

It can be modified, incase if you wish to show any other url as follows.

header("Location: mailsucceed.html");

Sending HTML Email: Content-Type: text/html needs to be mentioned in case if you require to send a html email.

AJAX handler for your application

We can have our own AJAX handler javascripts in our application.
Following are the steps to achieve them.

First create a callback object
this.XmlHttp;
var method = 'GET';
function CallBackObject()
{
this.XmlHttp = this.GetHttpObject();
}
CallBackObject.prototype.GetHttpObject = function()
{
var xmlhttp;

try
{
if ( window.XMLHttpRequest )
{
xmlhttp = new XMLHttpRequest();
}
else if ( window.ActiveXObject )
{
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e2)
{
xmlhttp = false;
}
}
}
}catch (e)
{
xmlhttp = false;
}


return xmlhttp;
}

Next step is creating a function which will send details to the server
Here eventTarget is the control raised ajax post back event and eventArgument is the argument to be passed with the data. data is the url query string and loadviewstate is a boolean denotes if need to send viewstate also.
Mirrorpage is alos a boolean if it is true all the values in the form will be send to the server

CallBackObject.prototype.DoCallBack = function(eventTarget, eventArgument, data, loadviewstate, mirrorpage)
{

var theData = data;
var theform = document.forms[0];
var thePage = window.location.pathname + window.location.search;
var myDateTime = new Date()

if(window.location.search == "")
thePage = thePage + "?tm=" + myDateTime.getMilliseconds();
else
thePage = thePage + "&tm=" + myDateTime.getMilliseconds();
var eName = '';
theData += '__EVENTTARGET=' + escape(eventTarget.split("$").join(":")) + '&';
theData += '__EVENTARGUMENT=' + eventArgument + '&';
if( loadviewstate == true )
{
theData += '__VIEWSTATE=' + escape(theform.__VIEWSTATE.value).replace(new RegExp('\\+', 'g'), '%2b') + '&';
}
theData += 'IsCallBack=true&';
if( mirrorpage == true )
{
for( var i=0; i<theform.elements.length; i++ )
{
eName = theform.elements[i].name;
if( eName && eName != '')
{
if( eName == '__EVENTTARGET' || eName == '__EVENTARGUMENT' || eName == '__VIEWSTATE' )
{
// Do Nothing
}
else
{
theData = theData + escape(eName.split("$").join(":")) + '=' + theform.elements[i].value;
if( i != theform.elements.length - 1 )
theData = theData + '&';
}
}
}
}
if(method.toUpperCase() == 'GET')
{

thePage += ((thePage.indexOf('?') == -1)?'?':'&') + theData;
}
else if(method.toUpperCase() == 'POST')
{
postData = postData?this._sFormData + "&" + postData:this._sFormData;
}

if( this.XmlHttp )
{
if( this.XmlHttp.readyState == 4 || this.XmlHttp.readyState == 0 )
{

try
{
var oThis = this;
this.XmlHttp.open(method, thePage, true);
this.XmlHttp.onreadystatechange = function(){ oThis.ReadyStateChange(); };
this.XmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
this.XmlHttp.send(theData);
}
catch(err)
{

}
}}}
CallBackObject.prototype.AbortCallBack = function()
{
if( this.XmlHttp )
this.XmlHttp.abort();
}
// Loading
CallBackObject.prototype.OnLoading = function(){}
// Loaded
CallBackObject.prototype.OnLoaded = function(){}
// Interactive
CallBackObject.prototype.OnInteractive = function(){}
// Complete
CallBackObject.prototype.OnComplete = function(responseText, responseXml)
{

}
// Abort
CallBackObject.prototype.OnAbort = function(){}
// Error
CallBackObject.prototype.OnError = function(status, statusText){}

CallBackObject.prototype.ReadyStateChange = function()
{
if( this.XmlHttp.readyState == 1 )
{
this.OnLoading();
}
else if( this.XmlHttp.readyState == 2 )
{
this.OnLoaded();
}
else if( this.XmlHttp.readyState == 3 )
{
this.OnInteractive();
}
else if( this.XmlHttp.readyState == 4 )
{

if( this.XmlHttp.status == 0 )
this.OnAbort();

else if( this.XmlHttp.status == 200 && this.XmlHttp.statusText == "OK" )
this.OnComplete(this.XmlHttp.responseText, this.XmlHttp.responseXML);
else
this.OnError(this.XmlHttp.status, this.XmlHttp.statusText, this.XmlHttp.responseText);
this.XmlHttp.close;

}
}

Download a file

While working with a scenario, I came across a situation to make the users to download a file. To download a file we can have the following code

try
{
string[] file = anrDownloadPdf.HRef.ToString().Split(Convert.ToChar("/"));


string strUpdPath = System.Configuration.ConfigurationManager.AppSettings["FileUploadPath"];
if (File.Exists(Server.MapPath(strUpdPath + file[file.GetUpperBound(0)])))
{

Response.ContentType = "Application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=application.pdf");
Response.TransmitFile(anrDownloadPdf.HRef);

// Response.End(); Don’t use Respons.End here since itcan have the thread abortion exception
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
catch (Exception ex)
{

}

Multiple selection in listbox

Most of the people find difficulty to save multiple data into database while selecting a listbox.
That’s possible by implementing the following method.

For example in an application there are several languages to be selected. The user can select any number of language from the list box.

We can add them into an collection called objColl

List<LanguageInfo> objColl = new List<LanguageInfo>();
for (int intCount = 0; intCount < lstLanguages.Items.Count; intCount++)
{
LanguageInfo objLanguages = new LanguageInfo();
if (lstLanguages.Items[intCount].Selected == true)
{
objLanguages.LanguageID = Convert.ToInt32(lstLanguages.Items[intCount].Value);
objColl.Add(objLanguages);
}
}

The next thing we can do is, we can append a comma to each languageid
IEnumerator<LanguageInfo> ILanguages = Languages.GetEnumerator();
while (ILanguages.MoveNext())
{
sbLanguages.Append(((LanguageInfo)ILanguages.Current).LanguageID.ToString());
sbLanguages.Append(",");
}
(Here Languages is the list that we passed to update in database)
In back-end just have a split method to split the data by comma. And it can be updated to the database.
CREATE function [dbo].[fn_Split](
@Languages nvarchar (1000),
@CustomerId int,
@Delimiter nvarchar (10)
)
returns @ValueTable table ([LanguageID] INT, [ProgramInfoId] INT)
begin
declare @NextString nvarchar(4000)
declare @Pos int
declare @NextPos int
declare @CommaCheck nvarchar(1)


set @NextString = ''
set @CommaCheck = right(@Languages,1)


set @Languages = @Languages + @Delimiter

set @Pos = charindex(@Delimiter,@Languages)
set @NextPos = 1

while (@pos <> 0)
begin
set @NextString = substring(@Languages,1,@Pos - 1)

insert into @ValueTable ( [LanguageID], [CustomerId]) Values (@CustomerId, @NextString)

set @Languages = substring(@Languages,@pos +1,len(@Languages))

set @NextPos = @Pos
set @pos = charindex(@Delimiter,@Languages)
end

return
end

...

Obstacles are those frightful things you see when you take your eyes off your goal.------> by Henry Ford