CrappyCoder 22 Light Poster

Any particular reason you want to set the timeout to an arbitary value of 200 or do you just want the session variables to remain indefinately?

If its indefinately then check that the user has been authenticated and populate the session variables accordingly

CrappyCoder 22 Light Poster

Essentially you need to start the timer server-side and then ensure that page refreshes do not alter the client-side countdown status (otherwise you just need to refresh constantly to reset the timer)

To invoke the timer I have the following:

protected void Page_Load(object sender, EventArgs e)
  {
    if (!Page.IsPostBack)
    { TimerStart(); }
  }

The TimerStart routine is defined as:

private void TimerStart()
   {
	if (Session["TimerStart"] == null)
	{		
	  Session["TimerStart"] = true;
 	  endDate = new BOL.Date();
	}
   }

The Session settings is to prevent the page refreshes as mentioned earlier and the class BOL.Date is a class I have created to return the date from my SQL server, it allows me to break the date format down into year, month, day, hour, minute, seconds - if you don't have access to an SQL server you can use various methods to return this information easily.

The user can move to the next item in my list of items displayed without waiting for a full count down by pressing the 'Next Button', the code for this is as follows:

protected void btnNext_Click(object sender, System.EventArgs e)
  {
	Session["TimerStart"] = null;
	TimerStart();
  }

To start the javascript timer, the following code needs to be added to the PreRender:

protected override void OnPreRender(EventArgs e)
  {
	if (Session["TimerStart"] != null)
	{		
	  string script = string.Format("javascript: countdownTimer({0}, {1}, {2}, {3}, {4}, {5}, {6});", endDate.Year, endDate.Month, endDate.Day, endDate.Hour, endDate.Minute, endDate.Second, <TimeValueInSeconds>);
	  ScriptManager.RegisterStartupScript(this, this.GetType(), "TimerStarted", script, true);
	}
	
	base.OnPreRender(e);
  }

The <TimeValueInSeconds> is exactly what it means - …

kvprajapati commented: Good post! :) +11
CrappyCoder 22 Light Poster

Ideally you should be using a virtual or relative path so using Server.MapPath is not to be recommended as it gives a hacker a chance to peruse your directory structure.

Have you tried...

<img src="Images/<imagename>" />

BTW what is the value of htmlOutPut AFTER you have assigned the image name to it?

CrappyCoder 22 Light Poster

It depends on what format you are receiving the data from the WebService but the syntax is as follows:

Dim reader As New System.IO.StringReader(<Webservice>) 

DataSet dataset = new DataSet(); 
dataset.ReadXml(reader); 

myDropDownList.DataSource = dataset.Tables[0]; 
myDropDownList.DataValueField = "value_field"         
myDropDownList.DataTextField = "text_field"
myDropDownList.DataBind();

The reader object is used to access the Webservice feed which and is expecting an XML string (for this example)

CrappyCoder 22 Light Poster

The code...

string image = "Images"; +"//" + fileName;

Should be..

string image = "Images" +"//" + fileName;

You have added an unnecessary semi-colon which will effectively terminate that statement so the filename never gets added.

Surprised your IDE did not flag up a warning on compilation - mine certainly did!

CrappyCoder 22 Light Poster

Louis,

Your problem will be whether you intend on having a 'real-time' look and feel to your application or whether you want to check the actual time spent on the question AFTER the user submits the request to the server.

What adatapost has suggested will offer you server-side processing which may not be what you require - the time is set on the server and checked when the processing returns to the server again (after the user submits his/her question response). This has the unfortunate side-effect of the user being able to spend as long as they like on the questions but only being told they have taken too long when they click a button to submit their response or move on to the next question.

I suspect what you are looking for is a client-side timer script which counts down and keeps a track of the total time spent on the questions - this is quite intricate and will require some time invested by you on understanding its operation. I have such a script and will post it here is its what you require.

Please let us know what solution you are looking for...

CrappyCoder 22 Light Poster

There is some debate whether its a good idea to store images in a database or on a file server.

If you insist on using a database then you'll need to set up a webhandler file which streams the image to your webpage.

Create a new item in your project of type of WebHandler and call it PhotoHandler

Then change the code to the following:

<%@ webhandler language="C#" class="PhotoHandler" %>
using System; 
using System.Web; 
using System.Data; 
using System.Data.SqlClient;
 
public class PhotoHandler : IHttpHandler 
{ 
    public bool IsReusable { get { return true; } } 
    
    public void ProcessRequest(HttpContext ctx) 
    { 
        string id = ctx.Request.QueryString["PhotoID"]; 

        SqlConnection con = new SqlConnection(<<INSERT CONNECTION STRING HERE>>); 
        SqlCommand cmd = new SqlCommand("SELECT [PhotoData] FROM [PhotoTable] WHERE PhotoID = @PhotoID", con); 
        cmd.CommandType = CommandType.Text; 
        cmd.Parameters.Add("@PhotoID", PhotoID); 
        
        con.Open(); 
        byte[] pict = (byte[])cmd.ExecuteScalar(); 
        con.Close(); 

        ctx.Response.ContentType = "image/bmp"; 
        ctx.Response.OutputStream.Write(pict, 0, pict.Length); 
    } 
}

then in your Web page you would do the following:

<img src="PhotoHandler.ashx?PhotoID=<%# Eval('PhotoID') %>" />
kvprajapati commented: Good option! +11
CrappyCoder 22 Light Poster

As we don't have access to yer data - what exactly is going wrong?

BTW would'nt it it easier to bind the DropDownLists to the ticketPrice - then you don't have to do your "If DropDownList2.SelectedValue = ..."

DropDownList.DataTextField="Ticket_Type"    
  DropDownList.DataValueField="Ticket_Price"
CrappyCoder 22 Light Poster

Try....

HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.AddTicks(500));

CrappyCoder 22 Light Poster

Bind more than 100 Grids - Are you displaying these all simultaneously (which would be highly inadvisable and downright madness)

Why not use a couple of placeholders and load the datagrid dynamically as and when the need arises.

Better still, let us know what you're trying to achieve and we may be able to point you in the right direction

CrappyCoder 22 Light Poster

Its better to retrieve the time from a server rather than use the local machine time (which can be easily amended) and compare the current server time with the duration time as held on the database.

Maintaining the duration time in a database will allow you greater flexibility as you can dynamically set this time without the need to release a web.config file or new code.

CrappyCoder 22 Light Poster

The following code...

SELECT	MAX(ACCT_BAL),
         [TelephoneNo]
FROM     [TableName]
GROUP BY [TelephoneNo]
HAVING COUNT(TelephoneNo)>1

Will return all the duplicate telephone numbers and the Largest account balance - you can then put the results of this in a temporary hash table and join onto your original table. Record with the same telephone number but lesser ACCT_BALs can then be deleted from your original table.

Other ways of doing this but really depends on yer SQL knowledge

CrappyCoder 22 Light Poster

How would you know which record to keep if the phone numbers are the same but the record information is different?

Do you have a timestamp on each record so you know whioh is the latest record?

CrappyCoder 22 Light Poster

Any particular reason you're using an HTML table?

Why don't you use a gridview to display the results from a datasource?

CrappyCoder 22 Light Poster

How do you intend to set/display this time for people accessing your site from different countries?

CrappyCoder 22 Light Poster

Do you know how to use a validator control or do you want to do the validation in code-behind?

<asp:RegularExpressionValidator 
   id="RegularExpressionValidator4" 
   runat="server" 
   ControlToValidate="txtPhoneNumber"
   ErrorMessage="Please enter a default 10 digit contact number (eg:111-111-1111)" 
   ValidationExpression="((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}">*</asp:RegularExpressionValidator>
CrappyCoder 22 Light Poster

If you are loading the pictures and labels proramtically them you must have an idea of which objects are being updated.

Do you know which obkjects you want to clear?

CrappyCoder 22 Light Poster

Why don't you just hide it and iterate through the grid for the hidden rows?

e.g to hide the row on 'deleting'

protected void gd_OnRowDeleting(object sender, GridViewDeleteEventArgs e)    
{
    gd.Rows[e.RowIndex].Visible=false;
}

Now iterate through the Gridview looking for the hidden rows

foreach (GridViewRow gvr in gd.Rows)
{
  if (gvr.Visible==false)			
  {
    some process...
    or         
    Debug.Print(gvr.RowIndex.ToString());
  }
}

I have tried it and it does work...

CrappyCoder 22 Light Poster

I think you've misunderstood what you should be doing:

This is how it should be done...

protected void gd_OnRowDeleting(object sender, GridViewDeleteEventArgs e)    {            
... Delete from Database
gd_Subjects.DataSource = DatabaseQuery;            
gd_Subjects.DataBind();     

}

Otherwise you will always have a false reading as the row will only be deleted from the UI and not the database.

CrappyCoder 22 Light Poster

Have you tried the following?...

SELECT T2.ID, T1.Date
FROM T2
LEFT JOIN T1
ON T2.ID = T1.ID

You will get everyting in table 2 (which has an ID but no date) and only the date from table 1 (which has an ID and a date)

The you can filter on the result as you see fit

CrappyCoder 22 Light Poster

Seems to be missing the following:

Main.master.cs
controls/SideMenu.ascx

Other that that it seems to be working (When you get build errors on compilation just click the 'Yes' button 'to continue and run the last successful build')

CrappyCoder 22 Light Poster

Presumably because its an invalid URL you're using?

Error 400: Requested URL invalid or incomplete

I have tried to use the website using the recommended example and it does not work - suspect the site has changed its policy for access

CrappyCoder 22 Light Poster

Hmmm,

I assuming that the 'other machine' is your web server and you've loaded the images to the relevant directory on that server but you are now working on a local machine and cannot find the images.

Or have I got it completely wrong?

CrappyCoder 22 Light Poster

Nitin Daphale: Not actually sure what you're trying to do - presumably the row deleting event is being fired because you are trying to delete the row?

So why do you need to remove the row programatically as the inbuilt delete function will take care of this - do you have more than one delete buttons?

Tell us abit more about your program design and we may be able to offer further assistance

CrappyCoder 22 Light Poster

Is there any reason why you aren't checking the username directly in your SQL query instead of iterating through the user table?

// don't ever do this!
String sql = "SELECT * FROM UserNew WHERE u_name = '" + uname + "'";

Ideally you should be doing this using the SQL Command, SqlParameter and SQLDataReader methods to prevent injection attacks.

SqlDataReader reader = null;
SqlCommand cmd = new SqlCommand("select * from UserNew where u_name = @uname", con);
cmd.Parameters.Add(new SqlParameter("@uname", uname));

// get data stream
reader = cmd.ExecuteReader();
while(reader.Read())
{
if (reader["u_pass"].ToString() == upass)         
 {return true;}
}

//Password does not match or the username cannot be found
return false;

This will return the exact match and you can then check if the password has been entered correctly.

CrappyCoder 22 Light Poster

Further to the above post you will need to add the following in your webconfig:

<connectionStrings>

add name="LocalSqlServer1" connectionString="Data Source=myServerAddress1;Initial Catalog=myDataBase1;User Id=myUsername1;Password=myPassword1;"/>

<add name="LocalSqlServer2" connectionString="Data Source=myServerAddress2;Initial Catalog=myDataBase2;User Id=myUsername2;Password=myPassword2;"/>

</connectionStrings>

And in your code-behind...

using System.Configuration;
.
.
.

string sqlServer;
if(LoginOption ==1){ 
sqlServer = ConfigurationManager.ConnectionStrings["LocalSqlServer1"].ConnectionString;}

elseif(LoginOption ==2)
{sqlServer = ConfigurationManager.ConnectionStrings["LocalSqlServer2"].ConnectionString;}

You now have different connection strings (which reside in the Webconfig file) being used for different Login Options

CrappyCoder 22 Light Poster

Also you may have the AutoPostBack set to 'true' in the HTML of your textbox in which case it will do a postback on the enter key.

Delete this option, create a seperate button and do the postback on that

In your HTML...

<asp:Label ID="Label1" runat="server" Text="Enter Value"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<asp:Button ID="btnContinue" runat="server" Text="Continue" onclick="btnContinue_Click" />

And in your code-behind...

protected void btnContinue_Click(object sender, EventArgs e)
{

// validate the textbox...

}
CrappyCoder 22 Light Poster

Visual Studio is the Development Envrionment and C# is the programming language.

Normally you would use the ViewState object to save page-specific information and the Session object to save Site-specific information.

//Page Specific 
ViewState["UrlReferrer"] = Request.UrlReferrer.ToString();   
ViewState["ValueEntered"] = TextBox1.Text;  


//Website specific
Session["UserName"] = "JohnThomas";
CrappyCoder 22 Light Poster

The only issue you will have is ensuring you can update the tables in your database using the logged-in user's identity (which is GUID based)

Otherwise the memebrship/roles will do nearly everything you need.

Be advised that the Membership data resides in your App_Data folder unless you specifically point to an external database - A few people I know have overwritten this membership data in a production environment when they FTP a new release of their web application with the local membership data

CrappyCoder 22 Light Poster

I've used DotNetNuke and its a very good system but to get the fun stuff you need to buy the commercial add-ons which is not always a good idea as DNN do very regular upgrades and the third-party stuff always lags several version behind.

You can easily run multiple sites off a single installation of DNN and the free stuuf should be more than enuff to give you a fairly robust out-of-box solution.

The source code is written in VB - not sure if they do a C# version

CrappyCoder 22 Light Poster

Have you tried the Modulas Operator (%) this will return a remainder if the textBox value is NOT a multiple of the saved value?

eg

decimal _Oldvalue ;

foreach (DataRow r in ds.Tables["Future"].Rows)            
{             
_Oldvalue = Convert.ToDecimal(r["Lot"].ToString());
textBox3.Text = r["Lot"].ToString();            
}

The in your validation you could use

if (_Oldvalue % Convert.ToDecimal(textBox3.Text) ==0) // is a multiple of the oldvalue

CrappyCoder 22 Light Poster

What language are you using for your code behind?

CrappyCoder 22 Light Poster

Hmmmm,

Assuming you have saved your images in the Images directory and you are storing the path in your SQL database as...

~/Images/Properties/Image1.gif

Then you should have no problem in using:

Image.ImageUrl=dr[6];

Please check the path that's being returned in dr[6]!

CrappyCoder 22 Light Poster

Your s.suppcode does not join with either a.suppcode or i.suppcode as it does in your previous query

CrappyCoder 22 Light Poster

If you dragged the table onto your form then a datasource will have been added automatically with the relevant INSERT, UPDATE and DELETE routines already created


http://www.asp.net/data-access/tutorials/querying-data-with-the-sqldatasource-control-vb

CrappyCoder 22 Light Poster

Not understanding your requirement.

You stated "If the value retrieved is 100, textbox should except 200, 300, 400..."

So where does the multiple of 2 mentioned in your previous statement come into play?

What should the textbox except for the following retrieved values:

1) 200
2) 300
3) 400

CrappyCoder 22 Light Poster

Hmmm,

Not a good idea to get the Max(IDColumnName) as previously suggested it will only get the last inserted record (not the record you have added) - and in a high transactional database you will get totally incorrect results.

Much better to return the ID added within the scope of the insert procedure which is why its preferable to use SCOPE_IDENTITY and assumes you have added an auto-incrementing Identity column in your database (if not why not?)

You have several methods to retrieve the Identity value depending on your knowledge.

You could use a dataset to return a column value (example shown), or you could use RETURN SCOPE_IDENTITY at the end of your procedure or you could include an OUTPUT parameter in your argument declaration:

BEGIN

INSERT INTO <TABLE>....
(Field1, Field2...)
VALUES
(Value1, Value2...)

SELECT [InsertedRecordID] = SCOPE_IDENTITY

END

ALternatively you could use

Using conn As New SqlConnection(connString)
Dim cmd As New SqlCommand(sql, conn)
...
...
...

int InsertedRecordID = (int)cmd.ExecuteScalar();

:

You would then need to change your SQL code...

BEGIN

INSERT INTO <TABLE>....
(Field1, Field2...)
VALUES
(Value1, Value2...)

RETURN SCOPE_IDENTITY

END

But please do NOT use the SELECT MAX() method!!!!