Redirecting to other page ? In asp.net? - asp.net

In web application [asp.net], i write the code to redirect to other page with in the solution, but it is giving exception.
Response.Redirect("abc.aspx");
can you help me, thank you.
WeeklyAttendanceMailStatusBE obj = new WeeklyAttendanceMailStatusBE();
obj.CreatedBy = Session["xxx"].ToString();
obj.Sesssionid = Session.SessionID.ToString();
obj.StatusDate = Convert.ToDateTime(DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day.ToString() + " " + DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString());
obj.Types = "Insert";
if (radLastWeek.Checked == true)
{
obj.Flags = 1;
obj.LastWeekStatus = 1;
int result = new WeeklyAttendanceMailStatusBL().InsertWeeklyAttendanceMailStatus(obj);
if (result > 0)
{
Response.Redirect("abc.html");
}
else
{
DateTime dt = DateTime.Now;
ScriptManager.RegisterStartupScript(this, GetType(), "message", "<script> alert('Not Submited Mail Status')</status>", false);
}
}
else
{
}

May be this is because of "thread is being aborted" exception, handle exception with try catch statements or specific catch class called ThreadAbortException
Please refer this for more information.

Try this :
Response.Redirect("abc.aspx",false);
Add a second argument (boolean value) that indicates whether to stop running the current page.
Reference :
HOW TO: Use Response.Redirect in ASP.NET with Visual Basic .NET

Related

Getting different date in database record after insert client date

I need help please,
I've problem when I insert client datetime using DateTime.Now.ToString() , I got the server date instead
try
{
c.SP_Introduction("SP_INS_INVOICE");
c.cmd.Parameters.AddWithValue("#InvoiceDate", Convert.ToDateTime(DateTime.Now.ToString()));
c.cmd.Parameters.AddWithValue("#RequestId", int.Parse(txtRequestId.Text));
c.cmd.Parameters.AddWithValue("#CreatedBy", int.Parse(Session["UserId"].ToString()));
SqlParameter parm = new SqlParameter("#InvoiceId", SqlDbType.Int);
parm.Direction = ParameterDirection.Output;
c.cmd.Parameters.Add(parm);
int i = c.cmd.ExecuteNonQuery();
string _InvoiceId = c.cmd.Parameters["#InvoiceId"].Value.ToString();
c.conn.Close();
c.cmd.Parameters.Clear();
if (i >= 1 || i == -1)
{
Session["InvoiceId"] = _InvoiceId;
Response.Redirect("InvoicePayment.aspx");
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "Error", "AlertError('Error..!','Somthing went wrong....!');", true);
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, GetType(), "Error", "AlertError('Error..!','" + ex.Message.ToString() + "');", true);
}
You need to replace this line:
c.cmd.Parameters.AddWithValue("#InvoiceDate", Convert.ToDateTime(DateTime.Now.ToString()));
with
c.cmd.Parameters.AddWithValue("#InvoiceDate", Convert.ToDateTime(dateFromClientApp));
Depending on the calling application, you will need to make sure the date isn't culture-specific if you're looking to store the date based on the region the application is used in. Also, if you're looking to save the time portion of the date, consider using UTC, take a look at this article.

Why does R# tell me, "Not all code paths return a value" in a click handler?

At the end of my submit button click handler, Resharper warns that, "Not all code paths return a value."
What value would it be expecting from an event handler?
In deference to full disclosure, this is that event handler:
$("#submit_button").click(function() {
// http://stackoverflow.com/questions/18192288/how-can-i-compare-date-time-values-using-the-jqueryui-datepicker-and-html5-time
var begD = $.datepicker.parseDate('mm/dd/yy', $('#BeginDate').val());
var endD = $.datepicker.parseDate('mm/dd/yy', $('#EndDate').val());
if (begD > endD) {
alert('Begin date must be before End date');
$('#BeginDate').focus();
return false;
}
else if (begD.toString() == endD.toString()) {
var dteString = begD.getFullYear() + "/" + (begD.getMonth() + 1) + "/" + begD.getDate();
var begT = new Date(dteString + " " + $('#BeginTime').val());
var endT = new Date(dteString + " " + $('#EndTime').val());
if (begT > endT) {
alert('Begin date must be before End date');
$('#BeginTime').focus();
return false;
}
}
$("#NumberOfResults").css("visibility", "visible");
$("#NumberOfResults").html("Please wait...");
EnableButton("submit_button", false);
// If all are selected, don't enumerate them; just set it at "All" (change of case shows that the logic did execute)
var deptsList = $('#depts').checkedBoxes();
if (deptsList.length < deptsArray.length) {
$('#deptHeader span').html(deptsList.join(", "));
}
else if (deptsList.length == deptsArray.length) {
$('#deptHeader span').html("All");
}
// " "
var sitesList = $('#sites').checkedBoxes();
$('#sitesHeader span').html(sitesList.join(", "));
if (sitesList.length < sitesArray.length) {
$('#sitesHeader span').html(sitesList.join(", "));
}
else if (sitesList.length == sitesArray.length) {
$('#sitesHeader span').html("All");
}
$('#hiddenDepts').val(deptsList);
$('#hiddenSites').val(sitesList);
var UPCs = $('#UPC').val();
if (UPCs == "All") {
$('#UPC').val("1"); // take everything (1 and greater)
}
var resultsText = jQuery.trim($("#spanNumberOfResults").text());
if (resultsText != "") {
$("#NumberOfResults").css("visibility", "visible");
if (resultsText == "0") {
$("#NumberOfResults").css("color", "red");
} else {
var href = '/#ConfigurationManager.AppSettings["ThisApp"]/CCRCriteria/LoadReport';
// report_parms (sic) is referenced from LoadReport
var report_parms = {
GUID: "#Model.GUID",
SerialNumber: "#Model.SerialNumber",
ReportName: "#Model.ReportName"
};
window.open(href, "report_window", "resizable=1, width=850, left=" + (screen.width / 2 - 425));
}
}
}); // end of submit button click
Resharper isn't aware of event handlers.
It sees that your function will sometimes return false and sometimes won't return anything, and it complains.
It doesn't realize that this pattern is perfectly fine for event handlers.
Ignore it. Click handlers "can" return a boolean value indicating whether to process the click normally (true) or ignore it (false).
Resharper sees any return in the function as a clue that it should always return something.

RadGrid Custom Filter

I'm trying to add a custom filter to my RadGrid. I have a column, vendNum, which I want to allow users to filter on multiple vendNums with a comma-separated list. Basically, I want the same functionality as an "in" statement in SQL (where vendNum in (X,Y,Z)).
I followed the tutorial on this site and came up with the following code to place in my RadGrid1_ItemCommand event.
protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
{
if (e.CommandName == RadGrid.FilterCommandName)
{
Pair filterPair = (Pair)e.CommandArgument;
switch (filterPair.Second.ToString())
{
case "vendNum":
TextBox tbPattern = (e.Item as GridFilteringItem)["vendNum"].Controls[0] as TextBox;
if (tbPattern.Text.Contains(","))
{
string[] values = tbPattern.Text.Split(',');
if (values.Length >= 2)
{
e.Canceled = true;
StringBuilder newFilter = new StringBuilder();
for (int i = 0; i < values.Length; i++)
{
if (i == values.Length - 1)
newFilter.Append("[vendNum] = " + values[i]);
else
newFilter.Append("[vendNum] = " + values[i] + " OR ");
}
if (RadGrid1.MasterTableView.FilterExpression == "")
RadGrid1.MasterTableView.FilterExpression = newFilter.ToString();
else
RadGrid1.MasterTableView.FilterExpression = "((" + RadGrid1.MasterTableView.FilterExpression + ") AND (" + newFilter.ToString() + "))";
RadGrid1.Rebind();
}
}
break;
default:
break;
}
}
}
Doing this, though, keeps giving me an error "Expression Expected" when I try to filter with a comma separated list. I'm still able to filter a single vendNum. My FilterExpression does come out as expected. The code is failing on the RadGrid1.Rebind() statement. Has anyone dealt with this before? Any help is greatly appreciated.
Thanks,
Aaron
Forgot to Edit This
I solved this problem weeks ago...I had to set the "EnableLinqExpressions" property to false under the RadGrid.
I saw this as a fix for this question somewhere.
Try adding:
RadGrid1.EnableLinqExpressions = false;

Nhibernate in asp,net ISession help

We're using nhibernate in and asp.net MVC application.
We are implementing the Session per Request pattern, via a httpModule.
It looks pretty straight forward, but when we run with NHibernate Profiler, it clearly shows that the
sessions are never getting closed.
the pattern seems straight forward...but I don't understand why the sessions are never closing.
here's the code i think is important.
set up the event handler:
context.EndRequest += new EventHandler(this.context_EndRequest);
in the handler dispose the Session
private void context_EndRequest(object sender, EventArgs e)
{
netLogHdl.ArchDebug("NHibernateHttpModule.context_EndRequest() ");
Dispose(0);// we are hitting 2 dbs and thus keep one session for each.
Dispose(1);
HttpContextBuildPolicy.DisposeAndClearAll();
}
private void Dispose(int sessionIndex)
{
netLogHdl.ArchStart("NHibernateHttpModule.Dispose", "int sessionIndex=\" + sessionIndex + \")");
try
{
//close the DB session
string sessManagerName = "";
string jcdcManager = "JCDC Manager";
string spamisManager = "Spamis Manager";
if (sessionIndex == 0)
sessManagerName = jcdcManager;
else
{
sessManagerName = spamisManager;
}
ISession oneSession = sessionPerDB[sessionIndex];
if (oneSession != null)
{
if (sessManagerName == jcdcManager) netLogHdl.ArchDebug(sessManagerName + " oneSession is NOT null");
if (oneSession.IsOpen)
{
// Don't flush - all saves should use transactions and calling Commit does the flush.
if (sessManagerName == jcdcManager) netLogHdl.ArchDebug(sessManagerName + " Closing the session");
//This will overrite it with the exact same session, if they don't match something weird is going on - EWB
oneSession = CurrentSessionContext.Unbind(factoryPerDB[sessionIndex]);
oneSession.Close();
}
else
{
if (sessManagerName == jcdcManager) netLogHdl.ArchDebug(sessManagerName + " Session is NOT open");
}
//if ( sessManagerName == jcdcManager ) netLogHdl.ArchDebug( sessManagerName + " Session got Dispose()-ing" );
//oneSession.Dispose();
}
else
{
if (sessManagerName == jcdcManager) netLogHdl.ArchDebug(sessManagerName + " Session is NULL");
}
sessionPerDB[sessionIndex] = null;
}
catch (Exception)
{
throw;
}
netLogHdl.ArchEnd();
}
Can anyone point me in the right direction? What shoud I look at, is the pattern not implemented correclty?
I'm flummoxed
Thanks!
E-
You should call dispose and not disconnect or close. System.IDisposable implementing objects should always be disposed by calling the dispose method, or by a using block.
You also might want to have a look at the code on Ben Day's blog post about session management.

JSON WebService in ASP.NET

How do I create an ASP.NET web service that returns JSON formatted data?
The most important thing to understand is to know how to represent data in JSON format.
Please refer http://www.json.org/ to know more about it.
Once you understand this, then the rest part is pretty straight forward.
Please check the following URL for an example of the same.
http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=264
http://code.msdn.microsoft.com/JSONSampleDotNet
http://www.phdcc.com/xml2json.htm
I recommend Jquery library for this. It's a lightweight rich library which supports calling web services, handle json data format output etc.
Refer www.jquery.com for more info.
.NET 3.5 has support built-in. For .NET 2.0, extra libraries are needed. I used the Jayrock library.
I recently delivered an application that uses pure Javascript at the browser (viz. using AJAX technology, but not using Microsoft AJAX or Scriptaculous etc) which marries up to Microsoft webservices at the back end. When I started writing this I was new to the world of .NET, and felt overwhelmed by all the frameworks out there! So I had an urge to use a collection of small libraries rather than very large frameworks.
At the javascript application, I call a web service like this. It directly reads the output of the web service, cuts away the non JSON sections, then uses https://github.com/douglascrockford/JSON-js/blob/master/json2.js to parse the JSON object.
This is not a standard approach, but is quite simple to understand, and may be of value to you, either to use or just to learn about webservices and JSON.
// enclosing html page has loaded this:
<script type="text/javascript" src="res/js/json2.js"></script>
// Invoke like this:
// var validObj = = callAnyWebservice("WebServiceName", "");
// if (!validObj || validObj.returnCode != 0) {
// alert("Document number " + DocId + " is not in the vPage database. Cannot continue.");
// DocId = null;
// }
function callAnyWebservice(webserviceName, params) {
var base = document.location.href;
if (base.indexOf(globals.testingIPaddr) < 0) return;
gDocPagesObject=null;
var http = new XMLHttpRequest();
var url = "http://mywebserver/appdir/WebServices.asmx/" + webserviceName;
//alert(url + " " + params);
http.open("POST", url, false);
http.setRequestHeader("Host", globals.testingIPaddr);
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http.setRequestHeader("Content-Length", params.length);
// http.setRequestHeader("Connection", "close");
//Call a function when the state changes.
http.onreadystatechange = function() {
if (http.readyState == 4 ) {
if (http.status == 200) {
var JSON_text = http.responseText;
var firstCurlyQuote = JSON_text.indexOf('{');
JSON_text = JSON_text.substr(firstCurlyQuote);
var lastCurlyQuote = JSON_text.lastIndexOf('}') + 1;
JSON_text = JSON_text.substr(0, lastCurlyQuote);
if (JSON_text!="")
{
//if (DEBUG)
// alert(url+" " +JSON_text);
gDocPagesObject = eval("(" + JSON_text + ")");
}
}
else if (http.readyState == 4)
{alert(http.readyState + " " + http.status + " " + http.responseText)}
}
}
http.send(params);
if (gDocPagesObject != null) {
//alert(gDocPagesObject.returnCode + " " + gDocPagesObject.returnString);
return gDocPagesObject;
}
else
return "web service unavailable: data not ready";
}
In our project the requirements were as follow -- ASP.NET 2.0 on the server, and pure Javascript on the browser (no JQuery libs, or .NET AJAX)
In that case on the server side, just mark the webmethod to use JSON. Note that both input and output params are json formatted
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public String Foo(String p1, String p2)
{
return "Result: p1= " + p1 + " p2= " + p2;
}
On the javascript side, use the regular XmlHttpRequest object, make sure you format your input params as JSON and do an 'eval' on output parms.
var httpobj = getXmlHttpRequestObject();
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject()
{
if (window.XMLHttpRequest)
return new XMLHttpRequest();
else if(window.ActiveXObject)
return new ActiveXObject("Microsoft.XMLHTTP");
}
CallService()
{
//Set the JSON formatted input params
var param = "{'p1' : 'value1', 'p2' : 'value2'}";
//Send it to webservice
if(httpobj.readyState == 4 || httpobj.readyState == 0)
{
httpobj.open("POST", 'service.asmx/' + 'Foo', true);
//Mark the request as JSON and UTF-8
httpobj.setRequestHeader('Content-Type','application/json; charset=utf-8');
httpobj.onreadystatechange = OnSuccess;
httpobj.send(param);
}
}
OnSuccess()
{
if (httpobj.readyState == 4)
{
//Retrieve the JSON return param
var response = eval("(" + httpobj.responseText + ")");
}
}

Resources