Tuesday, September 6, 2011

Time out

Dear readers,

I will stop posting for a while because of my job situation has changed, I have taken a position as a GIS developer. using more silverlight, so I need to decide how to handle it.
Osama

Tuesday, January 25, 2011

ASP.Net: Bind data into a template column

Suppost that we have a Grid View, with the property "AutoGenerateColumns" sat to false, when we declare a set of bound columns, it is easy to fill the data into the right column by giving each column the matching field name using the property "DataField". and just bind the data like this:

gridview1.DataSource = OurCollection
gridview1.DataBind()




But what if we needed to give a template column contains a check box or maybe a DropDownList a value from the database. in the same way. well no it is not so right to loop on each row and set the value manually.


the correct way is so simple just give the checked value a binded value like this:




Checked='< % # Bind("property or database field name") % > '

Thursday, January 20, 2011

Java script Random Draw

If you need to draw randomly from a group of options, and remove the winner from the options; this is the right choice for you.!

Although this example is not that hard if it was applied on any "code behind" language; I decided to increase my javascript skills doing this example; and I wanted to share it with you.

The simple example conaint an input control to display the result and a button to perform the draw; in addition to 16 inputs to enter the results; the user will right up to 16 options or less; and on pressing the button the selected option will be removed.


function PickRandomly( ){

var Array= [ ]; // We will need an array to hold the options in.
var controlID;

var i =1;

while (i<=16) // Check on all the inputs if it is not empty; add the ID to the array.
{
controlID = "var" + i; // Control ID
if (document.getElementById(controlID).value != "")
{
Array.push(controlID);
}
i = i+1;
}

// We have an array filled with the IDs of the available

if (Array.length > 0)
{
var randomnumber=Math.floor(Math.random()*Array.length); // Generate a random number from zero to the maximum length of the array
document.getElementById("result").value = document.getElementById(Array[randomnumber]).value ; // Show the result.
document.getElementById(Array[randomnumber]).value = ""; // and remove it from the available options
}



Please find a running sample here.

Sunday, January 16, 2011

Countdown javascript timer

After being desperate from finding any piece of javascript code to implement a countdown timer online, I tried to inhance an ordinary counter to fullfill my specific need.

I needed a countdown timer, to appear to students in an online exam, the exam will be automatically closed when the time runs out.

Although I could have used the same javascript timer to end the exam, I prefered to use a server-side ajax timer to check if the time of the exam had expired and finish it, the reason behind using the server-side is to prevent the manipulation of the exam time since the javascrip code depends on the local clock of the client, if they changed the time; the period will be expanded :D.

function sivamtime() {

' 1. retrieve and keep the current time from the client side clock.
now=new Date();

hour=now.getHours();
min=now.getMinutes();
sec=now.getSeconds();

' Retrieve exam period and exam starting time from a field on the web page. (Save and calculate the values on the page load; the values must be the total seconds on the time span for example if the start time is 09:27:05 the value will be [09*60*60 + 27*60 + 05 = 293225])
var examTime=document.getElementById('txtExamTime').value;
var startexamTime=document.getElementById('txtStartTime').value;

'Calculate how many seconds has passed from the beginning of the exam; and which equals [current time in seconds] - [start time of the exam in seconds] and substract the result from the [exam total duration in seconds].
var currentTime;
var SecondsFromStart;
var timeLeft;
var hours=0;
var minuts=0;
var seconds=0;
var h=0;
var m=0;
var s=0;
var time;
currentTime=0;
currentTime=hour*60*60;
currentTime=currentTime+(min*60);
currentTime=currentTime+sec;
SecondsFromStart=currentTime-startexamTime;
timeLeft=examTime-SecondsFromStart;

' check if the exam has finished.
if (SecondsFromStart > examTime)
{
document.getElementById('txtTime').value="00:00:00";
}
else
'otherwise calculate and show the remaining time.
{
hours=Math.floor(timeLeft/3600);
m=(timeLeft/3600)-hours;
minuts=Math.floor(m*60);
s=((m*60)-minuts);
seconds=Math.floor(s*60);

if (hours<=9) { hours = "0" + hours; } if (minuts<=9) { minuts = "0" + minuts; } if (seconds<=9) { seconds = "0" + seconds; } time = hours + ":" + minuts + ":" + seconds; document.getElementById('txtTime').value=time; ' recall this function every 500 millisecond
setTimeout("sivamtime()", 500);
}
}

' The following function will be called onload to save the start time.
function SetDateTime()
{
now=new Date();
hour=now.getHours();
min=now.getMinutes();
sec=now.getSeconds();
currentTime=0;
currentTime=hour*3600;
currentTime=currentTime+(min*60);
currentTime=currentTime+sec;
document.getElementById('txtStartTime').value=currentTime;
sivamtime();
}

One last thing, do not forget to end the exam, from the code behind ajax timer at the end of the time.

happy coding!

Monday, January 4, 2010

Integration with active directory..

Yesterday I had a task to integrate a web application with the active directory of the company.

On the load of the login page a check has to be done to insure that:
  • the user is logged to the right domain. (compare the user current domain with the company's domain).
  • the user has an account in application.
if so the login page will be skipped and the user will log in automatically to the application, otherwise the user will stay in the login page.


so here are the steps i followed to solve the problem

1. Set the authentication mode in the web.config to "Windows"

2. On the load of the page, add the call of the following function:



Sub CheckUserOnActiveDirectory()



If Application.Item("CheckOnActiveDirectory") Then


If User.Identity.IsAuthenticated Then


Dim strFulName As String

Dim strUsername As String = String.Empty

Dim strDomainName As String = String.Empty

Dim intUserID As Integer = 0



strFulName = Page.User.Identity.Name 'This will rturn Domain\User


strUsername = strFulName.Substring(strFulName.IndexOf("\") + 1, strFulName.Length - strFulName.IndexOf("\") - 1)


strDomainName = strFulName.Substring(0, strFulName.IndexOf("\"))




' Add some code to take the user name and check if its available on the database, and return any information needed.




Me.Session("UserID") = intUserID

Me.Session("UserName") = strUserName

Me.Session("UserRole") = intUserRole

Me.Session("UserStatus") = intUserStatus

Me.Session("EmployeeID") = intEmplyeeId


System.Web.Security.FormsAuthentication.RedirectFromLoginPage(strUserName, False)


End If

End If

End If

End Sub



and we done :)

Saturday, May 31, 2008

[Uploading documents to SQL server database]

A few months ago, I had a task asking me to build a page to upload a PDF files, and another page to show those uploaded files, in that time it was urgent case with no time dead line, so I had to switch from uploading those files to the SQL server database, to uploading them to the server folders.

Anyway in my opinion saving those files on the folders is not the perfect solution for many reasons such as the saving size, security reasons, naming conflict, and saving references to those files in our database in case we'll need to delete this file.

UploadFileControl.PostedFile.SaveAs(Server_
.MapPath("FileToUpload.PDF"))

Of course in this case you must give your application the privilege (permissions) to write on this folder, and obviously to read from, you can give those privileges from your server IIS.

Anyway uploading the file to the database is totally another story, first of all you need a HTML upload control, after adding the control to the page, right click on it and check on "Run as server control".

Add the parameter (encType="multipart/form-data") to the form tag of your page so your form tag will appear like this:

Don't forget to check on two things, before saving the file:

  1. if the user did select any file?
  2. if the user selected file is an allowed type document.
  3. and maybe if you want to control the max size of selected document to upload.

After that to save the file, you will need to store some information about this file, to get it out in the same shape as you stored it, the first thing store the data field which will hold your actual file as a [byte array], the data type is "image", also you need to save the type of the file, if its PDF or Word document file, save it as VarChar field. Those two fields could be enough to upload and to show the file to the user, but extra information like the file name, or the file length could be useful for you later.

Next you'll need to translate the file into an understandable format for your database which is here Image type, after you get this value, send it straight to the database using the regular ADO.NET code.

And now how to do that, you can only use the following ready to use code:


Byte[] File2Upload = new byte[UploadFileControl.PostedFile.InputStream.Length];
String TypeFile;

To get the extension:

extension=System.IO.Path.GetExtension(UploadFileControl_
.PostedFile.FileName.ToLower());


switch (extension){

case ".gif":

TypeFile = "image/gif";

break;

case ".jpg":

TypeFile = "image/jpeg";

break;

case ".png":

TypeFile = "image/png";

break;

case ".pdf":

TypeFile = "application/pdf";

break;


case ".txt":

TypeFile = "text/plain";

break;


default:

lblWarning.Text = "Not a Valid file format";

return;
break;
}

UploadFileControl.PostedFile.InputStream.Read(File2Upload, 0, File2Upload.Length);

And now you can store File2Upload into the data field and the TypeFile into the type field, using regular ADO.NET code.


After saving the file, you need to show the file to the user, to do that create a new page lets name it DownloadFile.aspx, in the code behind, use the following procedure which take the Data as Byte array, the file type as string, the length as integer, and the file name as string, retrieve these information from the database, and call the final,,


Public Sub DeliverFile(ByVal Data() As Byte, ByVal Type As String,_
ByVal Length As Integer, Optional ByVal DownloadFileName As String = "")


Response.Clear()

Response.ContentType = Type

Response.AddHeader("content-disposition", "attachment; filename=" & DownloadFileName)

Response.Charset = ""
esponse.Cache.SetCacheability(HttpCacheability.NoCache)
Response.BinaryWrite(Data)
Response.End()

End Sub

In the view page just insert a link to the DownloadFile.aspx and send the File Id for example using the QueryString,


lblPdf.Text = < href="'DownloadPdf.aspx?Id=">" + PdfNameHere ++"< / a >


Last thing, when the user selects a file with a big size, the application sometimes fail to upload the file, all what happens is the page just tells you: "Internet Explorer cannot display the webpage"

In this case just add the following parameter in the tag in the web config file:

The problem occur when the uploading process cross the timeout allowed by the application.


<httpRuntime executionTimeout="110" maxRequestLength="10096"/>

I think that’s it for now..

Have a nice coding!!
Osama Asa'ad