19 Jul 2017

17 Jul 2017

How to pass query string in MVC controller

How to pass query string in MVC controller




File => New Project
Templates => Visual C# => ASP.NET MVC Web Application

Right click on Models => Add => Class =>School.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace QueryStringsinAsp.netMVC.Models
{
public class School
{
public int ID { get; set; }
public string Name { get; set; }
public int age { get; set; }

public List<School> StudentList = new List<School>();

public List<School> school()
{
StudentList.Add(new School() { ID = 1, Name = "Yapheth", age = 12 });
StudentList.Add(new School() { ID = 2, Name = "John", age = 12 });
StudentList.Add(new School() { ID = 3, Name = "Tom", age = 12 });
StudentList.Add(new School() { ID = 4, Name = "Levi", age = 12 });

return StudentList;
}
}

}
==================================================================================================
Controllers => Add Controller=> HomeController => Add
using QueryStringsinAsp.netMVC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace QueryStringsinAsp.netMVC.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}

public ActionResult Search( string searchWord)
{
School s = new School();
var model = s.school().Where(x => x.Name.StartsWith(searchWord));
return View(model);
}

}
}
==================================================================================================
Right Click on Controller => Add View => Index => Add

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>
@using (Html.BeginForm("Search", "Home", FormMethod.Get))
{
@Html.TextBox("searchWord", null, new { @class = "form-control" });
<input type="submit" value="Search" class="btn btn-primary"/>
}
=================================================================================================
Right Click on search Controller => Add View =>Template List and model Class set to School => Add
@model IEnumerable<QueryStringsinAsp.netMVC.Models.School>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.age)
</th>
<th></th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.age)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}

</table>
<a href="/Home/index">
<input type="button" class="btn btn-danger" value="Back" />
</a>



Only one instance of a ScriptManager can be added to the page in asp.net C#

Only one instance of a ScriptManager can be added to the page in asp.net C#



Solution :

It says it right there...when you have added the script manager in page as well master page, you have to use only One Script manager.

Master page and current page both contains scriptmanager. Remove extra script managers and there should only be one script manager object on one page and child pages.

We can use one script manager on a single page only. If we want to utilize script manager at master page then use proxy script manager at master page, this will make you to not mention script manager at each page. As per my concern you can use a single script manager on one page not multiple. Within which you can use ur content, update panel etc Ajax tools.

16 Jul 2017

How to do animation with ng-hide & ng-show, not using angular-animate.js?

How to do animation with ng-hide & ng-show, not using angular-animate.js?


@keyframes grow {
0% {
display: none;
opacity: 0;
}
1% {
display: block;
opacity: 0;
transform: scale(0);
}
100% {
opacity: 1;
transform: scale(1);
}
}

12 Jul 2017

Import CheckBox value not changing in react-native.

Import CheckBox value not changing in react-native.

Guest Post

Import CheckBox from 'react-native-checkbox'
and i am using it this way
<CheckBox
label='Show Password'
checked={false}
onChange={(checked) => console.log('i am checked')}/>
Trouble i am having is , i am not been able to change it's value.

Solution :

constructor (props) {
super(props)
this.state = {
value:false
}
}
valueChange(value){
if (this.state.value==true) {
this.setState({
value:false
});
}
else{
this.setState({
value:true
});
}
}

<CheckBox
label='Show Password'
checked={this.state.value}
onChange={(checked) => this.valueChange(checked)}/>

================================================

 state = {
checked: false
}

<CheckBox
label='Show Password'
checked={this.state.checked}
onChange={(checked) => this.setState({ checked }) }/>


Users Please post your solution.

Does react native has a navigation drawer menu, Which is best ?

Does react native has a navigation drawer menu React Native

Guest Post :

React-native-router-flux  or  React-native-navigator

Library for Push Notification in React Native

Library for Push Notification in React Native

React-Native-Push-notification and Onesignal..

Guest Post :

Should I manage push notifications.. which library do you recommend?

Solution :

React Native push notification is the client side library to manage events and record the devicetoken, while we will have to have a backend somewhere (Firebase, one signal, parse server or custom made) where you will get the certificates (IOS) certificates and Apikey for gcm (Android) in addition to saving the devicetoken that react native push notification recovered.

Users Please post your solution.

9 Jul 2017

Retrieving images from SQL Server database without using Path in Asp.net MVC

Retrieving images from SQL Server database without using Path in Asp.net MVC

Guest Post :
I want to retrieve image from the database into asp MVC file.I searched on google everyone has stored relative path in db and they are retrieving that but I want to retrieve the image that is stored in db.I am using razor view engine.

Soluton:
Store your image in binary format and retrieve and deserialize it then. Use that encrypted code on image src with javascript syntax. Your image will be visible.

@{
var base64 = Convert.ToBase64String(item.Photo);
var imgSrc = String.Format("data:image/gif;base64,{0}", base64);
}
<td>
<img src="@imgSrc" /> 
</td>

Users Please post your solution.

7 Jul 2017

XMLHttpRequest cannot load. No 'Access-Control-Allow-Origin' header is present on the requested resource. Console error in Node JS

XMLHttpRequest cannot load. No 'Access-Control-Allow-Origin' header is present on the requested resource. Console error in Node JS

Guest Post :
Console error in Node JS
As nodejs Server is running on 3000 port, how to send data to angular app which is running in 9000 port. Server and client are both in my local machine.


XMLHttpRequest cannot load. No 'Access-Control-Allow-Origin' header is present on the requested resource. 

Solution :

Add Cors to express server because your trying to access the server on a different port than the client it will through a cors error. Install cors and then app.use(cors())

npm install cors -- save
Add this to server.js
const cors = require ('cors');
app.use(cors);

Users Please post your solution.

How to send push notification from asp.net core app to android app?

How to send push notification from asp.net core app to android app?

Guest Post :

How to send push notification from asp.net core app to android app?

Solution :

You need a messaging just like "azure messaging" ,  all you need is just subscription to azure service bus and do some integration with your apps. 

Users Please post your solution.

How to create API authentication header using sha256 and base64 in Asp.Net Core

How to create API authentication header using sha256 and base64 in Asp.Net Core

Guest Post :

How to create API authentication header using sha256 and base64 in Asp.Net Core?

Users Please post your solution.

The name 'model' does not exist in current context Asp.net MVC

The name 'model' does not exist in current context



1. Check your reference system.web.mvc and your webconfig if you reference these namespaces system.web.mvc and system.web.mvc.html

2. Check all packages successfully restored when you build it?

3. Check your class files. Whether reference correctly? also check the namespace and access modifiers of your class.

Users Please post your solution too.

5 Jul 2017

Best architecture to be followed for an Asp.Net MVC web application

Best architecture to be followed for an Asp.Net MVC web application

Guest Post :

I would like to know what is the best architecture to be followed for an Asp.Net MVC web application. Will creating a 3 tier architecture a good choice or it does not matter at all? Is having a business layer good choice or will business layer make the application look complex?

Solution :

Prefer to have a project with the Entity Framework model and "Manager" classes that have static methods to access the database through EF, then have another project that is the MVC web site. Bootstrap with KnockoutJS for the front, so it's talking to WebAPI controllers, which are "exposing" the managers from the business layer as needed. Some people like IoC patterns or dependency injection, your mileage may vary.

Depends on the size and complexity of the project. Domain driven design is suited for dealing with a lot of complexity. Check out the onion and hexagonal architectures. Microservices are something else to think about. I would say that TDD (test-driven development) should be a requirement for ALL non-trivial projects... just my opinion.

TDD is fine as long as people commit to maintain the associated test project. Some people forget that TDD is not a replacement for web site testing, users can find every error you left in. TDD is fine for the back-side code that is interfaced from the web site. Unit/integration testing are for developers. UAT should be left to program managers and stakeholders.

Clean coding, IMHO, is having good naming standards, project structures, proper error handling, and proper isolation/elimination of duplicate code. You can apply these techniques to any language and any coding model.

Users Please post your solution too.

An error occurred while signing SignTool.exe not found - Asp.net MVC

An error occurred while signing SignTool.exe not found - Asp.net MVC

Guest Post :

An error occurred while signing SignTool.exe not found - Asp.net MVC

Solution :

1. Right click on the solution go in properties click on signin tab then disable it and rebuild the solution.

2. You need to fix signtool.exe from the VC Installer by installing the clickonce tools.

Users Please post your solution too.

The development server returned response error code: 500 - React Js

The development server returned response error code: 500

Guest Post :

I am facing "The development server returned response error code: 500" error after installing a package. I tried Uninstall that package, Change port 8081 to 8088, Recreated the project But no use. Please make suggestion how can I get rid of this error?

Users Please post your solution too.

3 Jul 2017

Difference between Angularjs and jQuery ?

Difference between Angularjs and jQuery ?

 jQuery -> Library
Angular -> Framework

jquery is a bit of shortcut in javascript. its more of an extension library that extends core javascript language functionalities. Angular on the other hand is a framework designed to simplify the development process through special methodology.

jQuery is library use for DOM manipulations while on the other hand AngularJS is different beast full fledged Framework modeled on MVC.

jquery is a small piece inside the big box of angularjs..jquery working only small events or functions, but angularjs doing the whole DOM.

AngularJS is a JavaScript frameworks which allows us to develop single page application.Where jQuery is a library used for manipulating DOM.We can use Jquery with all JavaScript frameworks..it makes things simpler than JavaScript code.


Users Please post your answer too.

29 Jun 2017

How to form client side authentication through angular 1

How to form client side authentication through angular 1 


Guest post :

Can anybody tell me how to form client side authentication through angular 1 so that we can call an API after.

Solution :

oAuth or Json Web Token. I used both and the second one seems to be more friendly.

In JWT(Json web token) you can use angular-jwt directive.


26 Jun 2017

Improve SQL server query performance on table with millions of records.

Improve SQL server query performance on table with millions of records.


Guest post : 

Hi I have a table with 1+ Million records. The Query Is very slow when I use a where.
For Paging I am using ROW_NUMBER() OVER (ORDER BY CreatedOn DESC) AS ROW_NUM
Can some one help me with best practices while creating table also best way to create ROW_NUM for Paging.

Solution :

Indexing the table is a good option.

If your table is not dyamic load table using Ajax in jquery datatable. It can handle rows efficiently.

Use a parameterized store procedure in parameter take the number of record and last starting that will optimize your code.

Users please post your solution too.

24 Jun 2017

whats the difference between asynchronous and multithreading

whats the difference between asynchronous and multithreading


You just have to look at the word "asynchronous". Synchronous means that all of the things are done at once. So asynchronous, as its opposite, means that everything is not done at once, but may occur at any time, rather than in a specific order.

Multithreading is asynchronous, because each thread is working independently, and may call for a certain response from the main thread at any time.

Threading is about 'workers', asynchrony is about tasks. 
A greate example I have read somewhere else: 

Synchronous: you 'cook' the eggs then you 'cook' the toast

Asynchronous single threaded: you start the eggs cooking and set a timer. You start the toast cooking, and set a timer. While they are both cooking, you clean the kitchen. When the timers go off you take the eggs off the heat and the toast out of the toaster and serve them.

Asynchronous multi threaded: you hire two more cooks, one to cook eggs and one to cook toast. Now you have the problem of coordinating the cooks so that they do not conflict with each other in the kitchen when sharing resources. And you have to pay them.

"synchronous" means that you block on the call until it finishes executing. Asynchronous means you do not block. You can't say that synchronous means "at once" because that implies that everything is happening simultaneously. If I fire off 5 web requests synchronously, then they each happen one after another, and I don't continue on with other code until all 5 return--again, one after another. If I make those same 5 requests asynchronously, then they most certainly can happen at the same time. Now, those may not finish at the same time, but they (more than likely) are being processed at the same time. I can even continue on with other code, and expect those 5 results at a later time should I so desire. That's the beauty of async/await.

In the async/await world, we are typically using async to avoid blocking on I/O logic. When the hardware is busy doing stuff outside of the CPUs purview, then the CPU accomplishes nothing meaningful while it sits there waiting for I/O to complete. We use async code to allow the CPU to continue on with meaningful work while the hardware finishes its tasks. When the hardware is done, it signals the CPU using an I/O completion port (or crudely, the hardware signals the CPU/raises an event with the CPU).

Also, you cannot say that multi-threading is asynchronous. It can be. I can kick off a thread to make one of those web requests I mentioned above. But creating a thread incurs a bit of overhead. You can certainly have synchronous threads. You can force one thread to wait until some other thread reaches some arbitrary point. Now you have to do this using shared resources, which must be protected from corruption. This protection is part of what makes multi-threading code so difficult.

Changing DIV value using jquery Asp.net MVC

Changing DIV value using jquery Asp.net MVC

Guest post 
I have one div division

<div id="myname" name="myname">myvalue</div>

i am changing value of "myvalue" with jquery 
how can i pass myvalue to my controller.

Solution
create a controller get the value by $("#myname").text(); 
and pass it into the controller like this 

for example this is my controller 

[HttpPost]
    public void UpdateTask(TaskModel tmdl)
    {
        sDBSEntities dbOBj = new sDBSEntities();
        Task tObj = dbOBj.Tasks.Single(x => x.ID == tmdl.ID);
        tObj.Name = tmdl.Name;
        tObj.Description = tmdl.Description;
        tObj.DateUpdated = DateTime.Now;
        dbOBj.SaveChanges();
    }


my ajax call would be

var tmdl = {
ID: $("#hdnId").val(),
Name: $("#txtName").val(),
Description: $("#txtDesc").val()
};
$.ajax({
type: 'POST',
url: '/Task/UpdateTask',
data: tmdl,
cache: false,
success: function (result) {
clearAll();
alert("Updated Successfully");
location.reload();
},
error: function () {
alert('Err');
}
});
}


you can post your solution below.

21 Jun 2017

Online examination system project In Asp.Net with c#, SQL Database including Admin Panel - Download Part 3

Online examination system project In Asp.Net with c#, SQL Database including Admin Panel - Download Part 3





StartExam.aspx page code


<%@ Page Title="" Language="C#" MasterPageFile="~/MainPage.Master" AutoEventWireup="true" CodeBehind="StartExam.aspx.cs" Inherits="OnlineExam.StartExam" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script language="javascript" type="text/javascript">
      function validate() {
          if (document.getElementById("<%=disclaimer.ClientID%>").Checked == false) {
              alert("Please check Terms & Conditions");
            
              return false;
          }
      }
    
      }
    </script>
 <link href="bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"
        type="text/css" />
   
   


        <link href="bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>



<div id="divFirst" runat="server">
<table align="center" cellspacing="1" >
        <tr>
               
                <td class="style15">
                                        &nbsp;</td>
            </tr>
            <tr>
           
               
                <td>
                                        <table align="center" style="width: 650px; height: 450px;" cellpadding="10px" cellspacing="3px">
                                            <tr>
                                               <td align="right" class="style13" style="font-weight: bold">
                                                    Student Id :
                                                </td>
                                                <td align="left" class="style11">
                                                    <asp:TextBox ID="txt_stdId" runat="server" CssClass="textbox" Width="135px"
                                                        ReadOnly="True"></asp:TextBox><%--onkeydown="&#13;&#10;   if ( !isAlpha ( event ) ) {&#13;&#10;      alert ( 'Oops! Alphabets only please.' );&#13;&#10;      return false;&#13;&#10;   }"--%>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td align="right" class="style13" style="font-weight: bold">
                                                    Select Subjuct :
                                                </td>
                                                <td align="left" class="style11">
                                                    <asp:DropDownList ID="DdlProgrm" runat="server" Height="23px" Width="133px"
                                                      
                                                       >
                                                    
                                                    </asp:DropDownList>
                                                    <asp:RequiredFieldValidator ID="rfvlname0" runat="server" ControlToValidate="DdlProgrm"
                                                       ToolTip="program Required!" ValidationGroup="valid"><img src="images/question.gif" width="15px" height="15px"/></asp:RequiredFieldValidator>
                                                </td>
                                            </tr>
                                        
                                           
                                            <tr>
                                                <td align="right" class="style13" style="font-weight: bold">
                                                    &nbsp;</td>
                                                <td align="left" class="style11">
                                                    <asp:ImageButton ID="ImgBtnStartExm" runat="server"
                                                        ImageUrl="~/IMAGES/button copy.PNG" onclick="ImgBtnStartExm_Click" />
                                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                                    <br />
                                                </td>
                                            </tr>
                                           
                                            <tr>
                                                <td align="right" class="style14">
                                                </td>
                                                <td align="left" class="RadioButton"  valign="middle" class="style12">
                                                 
                                                    &nbsp;&nbsp;
                                                 &nbsp;</td>
                                               
                                            </tr>
                                            <tr>
                                              
                                               
                                                <td align="left" class="style14">
                                                    &nbsp;&nbsp; &nbsp;</td>
                                            </tr>
                                        </table>
                                    </td>
            </tr>
        </table>
        </div>

        <div id="divSecond" runat="server">
                           <div id="firstPage" style="overflow: hidden; border-bottom: 1px solid rgb(204, 204, 204); padding-left: 20px; >
                                  <span style="float:right;display:none;padding:2px;"><br>
                           <div class="sysInstText1"
                        style="height: 99%; width: 100%; overflow: auto; text-align: left;"><div> <br>
<br>
<center style="font-size: large; color: #663300"><b>Please read the instructions carefully
    </b></center> </div>
<p style="text-align: left"><strong><u>General Instructions:</u></strong></p>
<ol style="TEXT-ALIGN: left; LIST-STYLE-TYPE: decimal; PADDING-LEFT: 4%; PADDING-TOP: 3px">  <li>Total duration of examination is <span class="completeDuration"></span> </li>  <li>The clock will be set at the server. The countdown timer in the top right corner of screen will display the remaining time available for you to complete the examination. When the timer reaches zero, the examination will end by itself. <table class="instruction_area" style="FONT-SIZE: 100%">  <tbody>  <tr>  <td><span class="not_visited" title="Not Visited">
    <asp:Button ID="Button2" runat="server"    Text="" class="btn btn-default"  Width="40px" /></span></td>  <td> &nbsp; &nbsp;You have not visited the question yet.</td>
     </tr>  <tr>  <td><span class="not_answered" title="Not Answered">
      <asp:Button ID="Button3" runat="server" Text="" class="btn btn-info"  Width="40px" /></span></td>
       <td>  &nbsp; &nbsp;You have not answered the question.</td>  </tr>  <tr>  <td><span class="answered" title="Answered">
       <asp:Button ID="Button4" runat="server"   Text="" class="btn btn-success"  Width="40px" /></span></td>
        <td>  &nbsp; &nbsp;You have answered the question.</td>  </tr>  <tr>  <td><span class="review" title="Marked for Review">
        <asp:Button ID="Button5" runat="server"    Text="" class="btn btn-warning"  Width="40px" /></span></td>
         <td>  &nbsp; &nbsp;You have NOT answered the question, but marked for review.</td>  </tr>  <tr>
          <td><span class="review_answered" title="Answered &amp; Marked for Review">
          <asp:Button ID="Button6" runat="server"    Text="" class="btn btn-danger"  Width="40px" /></span></td>
           <td>  &nbsp; &nbsp;You have answered the question, but marked for review.</td>  </tr>  </tbody>  </table>  </li>
            <li style="LIST-STYLE-TYPE: none">The Marked for Review status for a question simply indicates that you would like to look at that question again.</li>
                    </ol>
                    <div style="text-align: left">
                        <br> <strong><u>Navigating to a Question:</u></strong><br>
                    </div>
<ol start="4" style="TEXT-ALIGN: left; LIST-STYLE-TYPE: decimal; PADDING-LEFT: 4%; PADDING-TOP: 3px">  <li>
    To answer a question, do the following<ol style="TEXT-ALIGN: left; PADDING-LEFT: 4%; PADDING-TOP: 3px" type="a">  <li>Click on the question number in the Question Palette at the right of your screen to go to that numbered question directly. </li>  <li>Click on <b>Save &amp; Next</b> to save your answer for the current question and then go to the next question.</li>  <li>Click on <b>Mark for Review &amp; Next</b> to save your answer for the current question, mark it for review, and then go to the next question.</li>
    </ol>
    </li>
                    </ol>
                    <p style="text-align: left"> <b><u>Answering a Question : </u></b></p>
<ol start="5" style="TEXT-ALIGN: left; LIST-STYLE-TYPE: decimal; PADDING-LEFT: 4%; PADDING-TOP: 3px">  <li>Procedure for answering a multiple choice type question:<ol style="TEXT-ALIGN: left; PADDING-LEFT: 4%; PADDING-TOP: 3px" type="a">  <li>To select your answer, click on the button of one of the options</li>  <li>To mark the question for review, click on the<b> Mark for Review &amp; Next</b> button.</li>
    </ol>
    <br>
    </li>
                    </ol>
<p style="text-align: left"> <b><u>Navigating through sections:</u></b></p>
<ol start="6" style="TEXT-ALIGN: left; LIST-STYLE-TYPE: decimal; PADDING-LEFT: 4%; PADDING-TOP: 3px</ol>
       
        <p>
     
                                        
                                                  
                                                <span ></span><span ><span style="" class="cusInstText1"><input runat="server" type="checkbox" id="disclaimer" onclick="linkDisp();" style="margin-top:2px;margin-right:10px">I have read and understood the instructions. </span></span></p>
                <p>
     
                                        
                                                &nbsp;</p>
        <p>
            <asp:Button  class="btn btn-primary btn-primary-blue" ID="Button1"
             OnClientClick="return validate();"   runat="server" Text="I am ready to begin" onclick="Button1_Click" /></p>
                <p>
                    &nbsp;</p>
        </div></div></div>
</asp:Content>

 ===============================================================

StartExam.aspx.cs page code


 using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.IO;


namespace OnlineExam
{
    public partial class StartExam : System.Web.UI.Page
    {
        DataSet ds = new DataSet();
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConOnlineExam"].ConnectionString);
        SqlDataAdapter adp ;
        SqlCommand cmd ;
        SqlCommand cmd1;
        Dal info = new Dal();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["Username"] == null)
                {
                    Response.Redirect("index.aspx");

                }
                bindSubjucts();
                txt_stdId.Text = Session["Username"].ToString();
                divFirst.Visible = true;
                divSecond.Visible = false;
            }
        }
        private void WriteLog(string strError)
        {
            try
            {
                string AppPath = AppDomain.CurrentDomain.BaseDirectory;
                string strLog = @"LOGS\";
                string strFilePath = AppPath + strLog;

                if (!(Directory.Exists(strFilePath)))
                {
                    Directory.CreateDirectory(strFilePath);
                }
                string fn = string.Format("{0}{1}.txt", strFilePath, DateTime.Now.ToString("ddMMyyyy"));
                FileStream fs = new FileStream(fn, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                StreamWriter writer = new StreamWriter(fs);
                writer.WriteLine(string.Format("[ {0} ] {1}", DateTime.Now.ToString("HH:mm:ss"), strError));
                writer.Close();
                fs.Close();
            }
            finally
            {
                //nothing
            }


        }
        private void bindSubjucts()
        {
            try
            {
                adp = new SqlDataAdapter("select sid,sname  from Subjects order by sname", con);
                ds = new DataSet();
                adp.Fill(ds);
                DdlProgrm.DataSource = ds;
                DdlProgrm.DataTextField = "sname";
                DdlProgrm.DataValueField = "sid";
                DdlProgrm.DataBind();
                DdlProgrm.Items.Insert(0, "--Select--");
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message);
            }
        }

        protected void ImgBtnStartExm_Click(object sender, ImageClickEventArgs e)
        {
            if (DdlProgrm.SelectedIndex == 0)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Please Select Subjuct', ' Please Select Subjuct', 'Please Select Subjuct ')", true);
                return;
            }
            divFirst.Visible = false;
            divSecond.Visible = true;



       
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (disclaimer.Checked == false)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Please check Terms & Conditions', 'Please check Terms & Conditions', 'Please check Terms & Conditions ')", true);
                return;
            }
            if (Session["Username"] != null)
            {
                string user = Session["Username"].ToString();
                DataSet ds = info.GetQuestions(Convert.ToInt32(DdlProgrm.SelectedValue));
                cmd1 = new SqlCommand("select isnull(max(ExamId)+1,1) from ExamHistory where Sid = '" + Convert.ToInt32(DdlProgrm.SelectedValue) + "' and StId ='" + Session["Username"].ToString() + "' ", con);
                con.Open();
                cmd1.CommandType = CommandType.Text;
                int j = Convert.ToInt32(cmd1.ExecuteScalar());
                Session["ExamId"] = j;
                if (ds.Tables[0].Rows.Count > 0)
                {
                    Session["questionpaper"] = ds;
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        cmd = new SqlCommand("insert into ExamHistory(Sid, StId, ExamId, Qid, CreatedDate, Ans, Choise) values ('" + Convert.ToInt32(DdlProgrm.SelectedValue) + "' , '" + user + "', '" + j + "',  '" + Convert.ToInt32(ds.Tables[0].Rows[i]["qid"]) + "', getdate(), '" + Convert.ToInt32(ds.Tables[0].Rows[i]["cans"]) + "' , 0) ", con);
                        cmd.CommandType = CommandType.Text;
                        cmd.ExecuteNonQuery();
                    }
                    con.Close();
                    Response.Redirect("Exam.aspx?p=" + Convert.ToInt32(DdlProgrm.SelectedValue));
                }
            }
            else
            {
                //logout page
            }
        }
    }
}
==================================================================

Result.aspx page code


<%@ Page Title="" Language="C#" MasterPageFile="~/MainPage.Master" AutoEventWireup="true" CodeBehind="Result.aspx.cs" Inherits="OnlineExam.Result" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
  



<table style="width: 930px;border:1px dotted #808080;">

<tr>
<td class="style13">




    <asp:Image ID="Image1" runat="server" Height="331px" Width="293px"
        ImageUrl="~/img/result.jpg" /></td>
<td class="style12">


<table style="width: 426px" >
<tr>

<td class="style16">
    &nbsp;</td>
<td class="style15"> <tr>
            <td  align="left" class="style16">
                Student ID:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            </td>
            <td align="left" class="style15">
                <asp:Label ID="lblID" runat="server" Text=""></asp:Label></td>
        </tr>
         <tr>
            <td align="left" class="style16">
                Subject:
            </td>
            <td align="left" class="style15">
                <asp:Label ID="lblSUb" runat="server" Text=""></asp:Label></td>
        </tr>
        
        
        <tr>
            <td align="left" class="style16">
                Starting Time :
            </td>
            <td align="left" class="style15">
                 <asp:Label ID="lblStart" runat="server" Text=""></asp:Label></td>
        </tr>
       
        <tr>
            <td align="left" class="style16">
                End Time :
            </td>
            <td align="left" class="style15">
                <asp:Label ID="lblEnd" runat="server" Text=""></asp:Label></td>
        </tr>
       
                <tr>
            <td align="left" class="style16">
                No. of Questions :
            </td>
            <td align="left" class="style15">
                <asp:Label ID="lblNoq" runat="server" Text=""></asp:Label></td>
        </tr>
       
                <tr>
            <td align="left" class="style16">
                Answered :
            </td>
            <td align="left" class="style15">
                <asp:Label ID="lblAns" runat="server" Text=""></asp:Label></td>
        </tr>

        <tr>
            <td align="left" class="style16">
                Correct Answers :
            </td>
            <td align="left" class="style15">
                <asp:Label ID="lblCans" runat="server" Text=""></asp:Label></td>
        </tr>
         <tr>
            <td align="left" class="style16">
                Un-Answered :
            </td>
            <td align="left" class="style15">
               <asp:Label ID="lblUnans" runat="server" Text=""></asp:Label></td>
        </tr>
        <tr>
            <td align="left" class="style16">
                Wrong :
            </td>
            <td align="left" class="style15">
              <asp:Label ID="lblWrong" runat="server" Text=""></asp:Label> </td>
        </tr>
         <tr>
            <td align="left" class="style16">
                Un-Answered :
            </td>
            <td align="left" class="style15">
               <asp:Label ID="Label3" runat="server" Text=""></asp:Label></td>
        </tr>
            <td align="left" class="style16">
             
            </td>
            <td align="left" class="style15">
               
                    <a href="" id ="Nav" runat="server">VIEW YOUR ANSWERS</a>
        </tr></td></tr></table>
        </td>
</tr></table>

</asp:Content>

=========================================================================================

Result.aspx.cs page code

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Collections;
using System.Configuration;

namespace OnlineExam
{
    public partial class Result : System.Web.UI.Page
    {        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConOnlineExam"].ConnectionString);
        SqlDataAdapter adp;
        DataSet ds;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
             DataSet ds2 = new DataSet();
            ds2 = (DataSet)Session["questionpaper"];
            adp = new SqlDataAdapter("select * from Exams left join Subjects on Exams.sid=Subjects.sid where  Exams.examid ='" + Convert.ToInt32(Request.QueryString["p"]) + "'", con);
            ds = new DataSet();
            adp.Fill(ds);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        lblID.Text=Session["Username"].ToString();
                        lblSUb.Text=(ds.Tables[0].Rows[0]["sname"]).ToString();
                        lblNoq.Text=(ds.Tables[0].Rows[0]["noq"]).ToString();
                        lblAns.Text=(ds.Tables[0].Rows[0]["Answered"]).ToString();
                        lblCans.Text=(ds.Tables[0].Rows[0]["nocans"]).ToString();
                        lblUnans.Text=(ds.Tables[0].Rows[0]["unans"]).ToString();
                        lblWrong.Text=(ds.Tables[0].Rows[0]["wrong"]).ToString();
                     
                        lblStart.Text = (Session["Stoptime"]).ToString();
                        lblEnd.Text = (Session["Etime"]).ToString();
                    }
                    Nav.HRef = "ViewPaper.aspx?id=" + Convert.ToInt32(ds.Tables[0].Rows[0]["ExamHistid"]);
            }
        }
    }
}
 =====================================================================


 


ViewPaper.aspx page code

<%@ Page Title="" Language="C#" MasterPageFile="~/MainPage.Master" AutoEventWireup="true" CodeBehind="ViewPaper.aspx.cs" Inherits="OnlineExam.ViewPaper" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
       
   <table>
<tr>
<td align="center">
<asp:ImageButton ID="btnExcel" runat="server" ImageUrl="~/img/Excel-icon.png"
onclick="btnExcel_Click" Height="48px" Width="81px" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/img/word.png"
onclick="btnWord_Click" Height="50px" Width="77px" />
</td>
</tr>
<tr>
<td>
<asp:GridView runat="server" ID="gvdetails"
        AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False"
        Width="954px"  style="margin-right: 13px"
        onpageindexchanging="gvdetails_PageIndexChanging">
<RowStyle BackColor="#EFF3FB" />
    <Columns>
        <asp:TemplateField>
        <HeaderTemplate>
            <h2 style="width: 292px; margin-bottom: 0px">
                Review Questions</h2>
          
        </HeaderTemplate>
        <ItemTemplate>
       
         <pre style="color:Red;background-color:#eeeeee"><%# DataBinder.Eval(Container.DataItem, "question")%></pre>
            <pre>1.<%# DataBinder.Eval(Container.DataItem, "option1")%></pre>
            <pre>2.<%# DataBinder.Eval(Container.DataItem, "option2")%></pre>
            <pre>3.<%# DataBinder.Eval(Container.DataItem, "option3")%></pre>
            <pre>4.<%# DataBinder.Eval(Container.DataItem, "option4")%></pre>
            <pre>Correct Answer :<%# DataBinder.Eval(Container.DataItem, "Ans")%></pre>
            <pre>Your Answer    :<%# DataBinder.Eval(Container.DataItem, "Choise")%></pre>
        </ItemTemplate>
        </asp:TemplateField>
    </Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</td>
</tr>
</table>
</asp:Content>

==========================================================================================

ViewPaper.aspx.cs page code

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using System.Data.SqlClient;
using System.Data;
using System.IO;

namespace OnlineExam
{
    public partial class ViewPaper : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConOnlineExam"].ConnectionString);
      
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    if (Session["UserName"] == null)
                    {
                        Response.Redirect("index.aspx");
                    }
                }
                catch
                {

                  
                }
                bindgrid();
            }



        }
        private void bindgrid()
        {
            SqlDataAdapter adp = new SqlDataAdapter("select * from ExamHistory left join Questions on ExamHistory.Qid = Questions.qid where   StId = '" + Session["Username"].ToString() + "' and  ExamId = '" + Convert.ToInt32(Request.QueryString["id"]) + "'   ", con);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                gvdetails.DataSource = ds;
                gvdetails.DataBind();
            }

        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */
        }

        protected void btnExcel_Click(object sender, ImageClickEventArgs e)
        {
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
            Response.ContentType = "application/ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gvdetails.AllowPaging = false;
            gvdetails.DataBind();
            //Change the Header Row back to white color
            gvdetails.HeaderRow.Style.Add("background-color", "#FFFFFF");
            //Applying stlye to gridview header cells
            for (int i = 0; i < gvdetails.HeaderRow.Cells.Count; i++)
            {
                gvdetails.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
            }
            int j = 1;
            //This loop is used to apply stlye to cells based on particular row
            foreach (GridViewRow gvrow in gvdetails.Rows)
            {
                gvrow.BackColor = System.Drawing.Color.White;
                if (j <= gvdetails.Rows.Count)
                {
                    if (j % 2 != 0)
                    {
                        for (int k = 0; k < gvrow.Cells.Count; k++)
                        {
                            gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
                        }
                    }
                }
                j++;
            }
            gvdetails.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }
        protected void btnWord_Click(object sender, ImageClickEventArgs e)
        {

            gvdetails.AllowPaging = false;
            gvdetails.DataBind();
            Response.ClearContent();
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.doc"));
            Response.Charset = "";
            Response.ContentType = "application/ms-word";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gvdetails.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }
        protected void gvdetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvdetails.PageIndex = e.NewPageIndex;
            bindgrid();
        }
    }
}