Using Session[] with Page Load - c#

I want to load the data into session so that when the next button is clicked in crystal report viewer then in should load the data from the datatable instead retrieving the data again from the database. Here goes my code...
ReportDocument rpt = new ReportDocument();
DataTable resultSet = new DataTable();
string reportpath = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString.Get("id") == "5")
{
string publication = Request.QueryString.Get("pub");
DateTime date = DateTime.Parse(Request.QueryString.Get("date"));
int pages = int.Parse(Request.QueryString.Get("pages"));
int sort = int.Parse(Request.QueryString.Get("sort"));
if (sort == 0)
{
reportpath = Server.MapPath("IssuesReport.rpt");
rpt.Load(reportpath);
DataTable resultSet1 = RetrievalProcedures.IssuesReport(date, publication, pages);
Session["Record"] = resultSet1;
}
DataTable report = (DataTable)Session["Record"];
rpt.SetDataSource(report);
CrystalReportViewer1.ReportSource = rpt;
I am trying this code but when i clicked the next button it gives me the error that invalid report source..i guess the session is null thats why its giving me this error.
Any sugesstions how can I solve this...

I think you'd want to use the Cache object with a unique key for each user instead of Session here.
Pseudo code:
var data = Cache["Record_999"] as DataTable;
if (data == null) {
// get from db
// insert into cache
}
SetDataSource(data);

The problem lies not in with using Session, it lies with the logic used to determine when to retrieve data. Session is the correct approach to use here as Cache is shared across requests - that is, User A would see the report User B just configured if User B was the first user to execute code that used Cache instead of Session.
if (!Page.IsPostBack)
{
if (Request.QueryString.Get("id") == "5")
{
string publication = Request.QueryString.Get("pub");
DateTime date = DateTime.Parse(Request.QueryString.Get("date"));
int pages = int.Parse(Request.QueryString.Get("pages"));
int sort = int.Parse(Request.QueryString.Get("sort"));
// fixed the statement below to key off of session
if (Session["Record"] == null)
{
reportpath = Server.MapPath("IssuesReport.rpt");
rpt.Load(reportpath);
Session["Record"] = RetrievalProcedures.IssuesReport(date, publication, pages);
}
rpt.SetDataSource((DataTable)Session["Record"]);
CrystalReportViewer1.ReportSource = rpt;
// ....
}
}

`Could it be that sort is not 0? If sort is not 0 and the user is accessing the page for the first time(Session["Record"] has not been set before) he might get the error.
might want to try:
if(sort==0 || Session["Record"] == null)
{
// do your magic
}

Related

Copy Records to another Screen in acumatica

I have 2 screen, inquiry and data entry.
and i want to copy Record from Screen1 to screen2, see picture below.
scree1 and Screen2
I use the following code:
public PXAction<FuncLocFilter> CreateFuncLoc;
[PXButton]
[PXUIField(DisplayName = "Create Functional Location")]
protected virtual void createFuncLoc()
{
FuncLocFilter row = Filter.Current;
BSMTFuncLoc FnLc = new BSMTFuncLoc();
FunLocEntry graph = PXGraph.CreateInstance<FunLocEntry>();
graph.FunLocations.Current.FuncLocCD = row.FuncLocCD;
graph.FunLocations.Current.StructureID = row.StructureID;
graph.FunLocations.Current.HierLevels = row.HierLevels;
graph.FunLocations.Current.EditMask = row.EditMask;
if (graph.FunLocations.Current != null)
{
throw new PXRedirectRequiredException(graph, true, "Functional Location");
}
}
but i encountered an error like the following:
Error
can someone please help solve this seemingly stupid question?
im sorry my english is bad.. :)
Thanks!
Below is a common pattern to create data records via code/programming in Acumatica
public PXAction<FuncLocFilter> CreateFuncLoc;
[PXButton]
[PXUIField(DisplayName = "Create Functional Location")]
protected virtual void createFuncLoc()
{
FuncLocFilter row = Filter.Current;
// 1. Create an instance of the BLC (graph)
FunLocEntry graph = PXGraph.CreateInstance<FunLocEntry>();
// 2. Create an instance of the BSMTFuncLoc DAC, set key field values (besides the ones whose values are generated by the system),
// and insert the record into the cache
BSMTFuncLoc FnLc = new BSMTFuncLoc();
FnLc.FuncLocCD = row.FuncLocCD;
FnLc = graph.FunLocations.Insert(FnLc);
// 3. Set non-key field values and update the record in the cache
FnLc.StructureID = row.StructureID;
FnLc.HierLevels = row.HierLevels;
FnLc.EditMask = row.EditMask;
FnLc = graph.FunLocations.Update(FnLc);
// 4. Redirect
if (graph.FunLocations.Current != null)
{
throw new PXRedirectRequiredException(graph, true, "Functional Location");
}

C# Viewstate - cant retrieve table

I have a datatable containing file paths which I am passing via viewstate (referencing, via a linkbutton, an index in this table), wanting to then use the path from the table to construct a HTTP filetransfer. (So 3 cols; name, path and index)
I am unable to successfully retrieve the datatable once saved in viewstate;
ViewState["varFiles"] = filedata;
(When page is originally constructed, then after postback:)
if (!IsPostBack) { SetupSession(); newpopfiles(); }
else { { if (ViewState["varFiles"] != null) { DataTable filedata = new DataTable(); filedata = (DataTable)Session["varFiles"]; } } }
From what I understand this should pull back filedata as a table in exactly the same form as before postback. Is this correct?
When subsequently referencing the table I get a null reference exception. Any ideas?
Many thanks,
Dan
It sounds like you're almost there, just need to be a bit more consistent with using the same storage mechanism :)
The bit to save the DataTable into your session, probably in OnInit() or PageLoad():
DataTable myDataTable = //... fill it in somehow
Session["varFiles"] = myDataTable;
The bit to read the DataTable after postback:
if (!IsPostBack)
{
SetupSession();
newpopfiles();
}
else
{
DataTable filedata = Session["varFiles"] as DataTable;
if (filedata != null)
{
//... do something
}
}

How I can get specific values from URL in ASP.NET

How I can get specific values from the following URL I need to get only 3 values
http://earnprofitclickint.com/UserWorking/Successfull.aspx?lr_paidto=U9925362&lr_amnt=2.00&lr_currency=LRUSD&lr_store=http%3A%2F%2Fwww.earnprofitclickint.com&lr_merchant_ref=&lr_paidby=U3563444&lr_fee_amnt=0.00&lr_transfer=143636187&lr_timestamp=2013-12-05+18%3A31%3A33&ctl00%24contentplaceholder1%24amount=&ctl00%24contentplaceholder1%24id=70&ctl00%24contentplaceholder1%24txtamount=+2&ctl00%24contentplaceholder1%24username=networker&lr_encrypted=04E20ADA982A2AF9C1C64DB3C1601BA596373E22D7B4D21813A51C43DC0198CD&lr_encrypted2=59C8269D431F915360F3B8179EC95181D8C458AB91D72AF3DFC1DC0DFDAC4F64
I want to get 3 values from the above URL return from Liberty Reserve Website and want to insert these three values to database using LINQ TO SQL
I need to get the following values
r_amnt=2.00 ID=70 username=networker
I have written the code in page load to get the above values when the response come and Redirect to my successful page:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ID.Value = Request.QueryString["id"].ToString();
UserName.Value = Request.QueryString["username"].ToString();
Amount.Value = Request.QueryString["lr_amnt"].ToString();
SaveLocalHistory();
Divmessage.Visible = true;
}
}
public void SaveLocalHistory()
{
MLMDataContext db = new MLMDataContext();
UsersInvestement pd = new UsersInvestement();
pd.Amount = Convert.ToDouble(Amount.Value);
pd.UserId = Convert.ToInt32(ID.Value);
pd.UserName = UserName.Value;
pd.Description = "This amount has been received From LR";
pd.IncomeTypeId = 4;
pd.CreatedDate = DateTime.Now.Date;
db.UsersInvestements.InsertOnSubmit(pd);
db.SubmitChanges();
}
This is a manual change in the URL:
http://earnprofitclickint.com/UserWorking/Successfull.aspx?lr_paidto=U9925362&lr_amnt=2.00&lr_currency=LRUSD&lr_store=http%3A%2F%2Fwww.earnprofitclickint.com&lr_merchant_ref=&lr_paidby=U3563444&lr_fee_amnt=0.00&lr_transfer=143636187&lr_timestamp=2013-12-05+18%3A31%3A33&ctl00%24contentplaceholder1&amount=&ctl00%24contentplaceholder1&id=70&ctl00%24contentplaceholder1%24txtamount=+2&ctl00%24contentplaceholder1&username=networker&lr_encrypted=04E20ADA982A2AF9C1C64DB3C1601BA596373E22D7B4D21813A51C43DC0198CD&lr_encrypted2=59C8269D431F915360F3B8179EC95181D8C458AB91D72AF3DFC1DC0DFDAC4F64
If I change it manually then it works. Any idea?
Your parameter names are not username and id, they are ctl00$contentplaceholder1$username for username and ctl00$contentplaceholder1$id for id
Since %24 when URLDecode gives $ , you need to do the corresponding replacements too.
Try this:
ID.Value = Request.QueryString["ctl00$contentplaceholder1$id"].ToString();
UserName.Value = Request.QueryString["ctl00$contentplaceholder1$username"].ToString();
Amount.Value = Request.QueryString["r_amnt"].ToString();
and it should work. Let me know otherwise! :)
I am fairly certain that the query string values are case sensitive, meaning that this code
ID.Value = Request.QueryString["ID"].ToString();
UserName.Value = Request.QueryString["UserName"].ToString();
Amount.Value = Request.QueryString["lr_amnt"].ToString();
should probably be in this form
ID.Value = Request.QueryString["id"].ToString();
UserName.Value = Request.QueryString["username"].ToString();
Amount.Value = Request.QueryString["r_amnt"].ToString();
if you wanted to pull out "r_amnt=2.00 id=70 username=networker"
As an aside, note that you never dispose of your database context. This can be dangerous in that it is possible your connection will not close for a very long time, I would suggest doing this instead:
using( MLMDataContext db = new MLMDataContext() )
{
UsersInvestement pd = new UsersInvestement();
pd.Amount = Convert.ToDouble(Amount.Value);
pd.UserId = Convert.ToInt32(ID.Value);
pd.UserName = UserName.Value;
pd.Description = "This amount has been received From LR";
pd.IncomeTypeId = 4;
pd.CreatedDate = DateTime.Now.Date;
db.UsersInvestements.InsertOnSubmit(pd);
db.SubmitChanges();
}
The using statement ensures that Dispose is called on the DataContext (which inherits from IDisposable) and will properly close the connection once the actions complete.

Out of Memory at line XXXX

can anyone help me how to resolve the out of memory error on my asp page? im using linq to sql.. after adding data several data.. like more than 10 rows. in the grid. an out of memory error occurs.. attached herewith is my add function..
public ServiceDetail checkservicedetailid()
{
string ServiceName = ViewState["Tab"].ToString();
ServiceDetail checkservicedetailid = ServiceDetails_worker.get(a => a.ServiceName == ServiceName && a.MarginAnalysisID == checkmarginanalysisid().MarginAnalysisID).SingleOrDefault();
return checkservicedetailid;
}
public IEnumerable<ServiceDetail> get(Expression<Func<ServiceDetail, Boolean>> express)
{
return ServiceDetailsDB.ServiceDetails.Where(express);
}
protected void btnSaveEmptyOC_Click(object sender, EventArgs e)
{
try
{
if (checkservicedetailid() != null)
{
CashExpense tblCashExpenses = new CashExpense();
Guid CashExpensesID = Guid.NewGuid();
tblCashExpenses.CashExpensesID = CashExpensesID;
tblCashExpenses.ServiceDetailsID = checkservicedetailid().ServiceDetailsID;
tblCashExpenses.Description = txtDescriptionEmptyOC.Text;
tblCashExpenses.Quantity = Decimal.Parse(txtQTYEmptyOC.Text);
tblCashExpenses.UnitCost = Decimal.Parse(txtUnitCostEmptyOC.Text);
tblCashExpenses.CreatedBy = User.Identity.Name;
tblCashExpenses.DateCreated = DateTime.Now;
tblCashExpenses.CashExpensesTypeID = "OTHER";
CashExpenses_worker.insert(tblCashExpenses);
CashExpenses_worker.submit();
//Clear items after saving
txtDescriptionEmptyOC.Text = "";
txtQTYEmptyOC.Text = "";
txtUnitCostEmptyOC.Text = "";
ValidationMessage.ShowValidationMessage(MessageCenter.CashExpenseMaintenace.InsertOC2, "SaveEmptyOC", this.Page);
MyAuditProvider.Insert(this.GetType().ToString(), ViewState["MarginAnalysisID"].ToString(), MessageCenter.Mode.ADD, MessageCenter.CashExpenseMaintenace.InsertOC2, Page.Request, User);
divOtherCost.Visible = false;
grd_othercost.Visible = true;
btnaddothercost.Visible = true;
}
else
{
//Displays a Message on the Validation Summary (Service Id does not exist)
ValidationMessage.ShowValidationMessage(MessageCenter.CashExpenseMaintenace.SaveServiceDetailOC, "SaveEmptyOC", this.Page);
}
}
catch
{
//Displays a Message on the Validation Summary (Error on Saving)
ValidationMessage.ShowValidationMessage(MessageCenter.CashExpenseMaintenace.InsertOCError, "SaveEmptyOC", this.Page);
}
finally
{
//Rebinds the Grid
populategrd_othercost();
}
}
I'm guessing from your code here:
ServiceDetail checkservicedetailid = ServiceDetails_worker.get(
a => a.ServiceName == ServiceName &&
a.MarginAnalysisID == checkmarginanalysisid().MarginAnalysisID
).SingleOrDefault();
that .get() is taking a Func<SomeType, bool>, and you are doing something like:
var row = dbCtx.SomeTable.Where(predicate);
(please correct me here if I'm incorrect)
This, however, is using LINQ-to-Objects, meaning: it is loading every row from the table to the client and testing locally. That'll hurt memory, especially if a different db-context is created for each row. Additionally, the checkmarginanalysisid() call is being executed per row, when presumably it doesn't change between rows.
You should be testing this with an Expression<Func<SomeType, bool>> which would be translated to TSQL and executed at the server. You may also need to remove untranslatable methods, i.e.
var marginAnalysisId = checkmarginanalysisid().MarginAnalysisID;
ServiceDetail checkservicedetailid = ServiceDetails_worker.get(
a => a.ServiceName == ServiceName &&
a.MarginAnalysisID == marginAnalysisId
).SingleOrDefault();
where that is get(Expression<Func<SomeType, bool>>).
I tried all of the solution given to me both by my peers as well as the solution provided here, from GC.Collect, to disposing linq datacontext after use etc. however the error keeps on occurring, i then tried to remove the update panel, Ive read a site that showed how ridiculous update panel when it comes to handling data esp when a function is done repeatedly. And poof! the memory problem is gone!

Why do I get "Object reference not set to an instance of an object." when changing pages in asp.net

I have a master page that set ups some variables that I want to use across the site..
protected void Page_Load(object sender, EventArgs e)
{
//Get users name from AD
str_DomainName = HttpContext.Current.User.Identity.Name;
str_CurrentLogin = str_DomainName.Substring(5);
//Display current user information
DirectorySearcher search = new DirectorySearcher("LDAP://DCHS");
search.Filter = String.Format("(SAMAccountName={0})", str_CurrentLogin);
SearchResult result = search.FindOne();
DirectoryEntry entry = result.GetDirectoryEntry();
lbl_CurrentUser.Text = result.Properties["givenName"][0].ToString() + ' ' + result.Properties["sn"][0].ToString();
// Get SID
IntPtr logonToken = WindowsIdentity.GetCurrent().Token;
WindowsIdentity windowsId = new WindowsIdentity(logonToken);
//Set session variabls
this.CurrentFirstName = result.Properties["givenName"][0].ToString();
//this.CurrentEmail = result.Properties["mail"][0].ToString();
//this.CurrentSID = windowsId.User.ToString();
//this.CurrentUserName = str_CurrentLogin;
//this.CurrentFullName = lbl_CurrentUser.Text;
//this.CurrentDomain = str_DomainName;
this.Session.Add("currentEmail", result.Properties["mail"][0].ToString());
}
public String CurrentFirstName
{
get { return (String)ViewState["currentFirstName"]; }
set { ViewState["currentFirstName"] = value; }
}
I then call them in my defalut.aspx page as follows:
protected void Page_PreRender(object sender, EventArgs e)
{
//try
//{
lbl_FullName.Text = Master.CurrentFullName;
lbl_SID.Text = Master.CurrentSID;
testLabel.Text = Master.CurrentEmail;
//}
//catch (Exception ex)
//{ }
}
This works fine.. If I however navigate away from the default page, then I get the following error..
Object reference not set to an instance of an object.
One the lbl_FullName.Text = Master.CurrentFullName; line
If I uncomment the try catch then it works fine, but I don't believe that this is the correct method of avoiding the fault..
I'm only new to ASP, so be nice..
EDIT:
The variabes are being set in Master.cs as follows.
public String CurrentUserName
{
get { return (String)ViewState["currentUserName"]; }
set { ViewState["currentUserName"] = value; }
}
A few questions:
Which side of the expression is generating the error: this.lbl_FullName or this.Master?
If it's the former, then there's something funky going on in your page.aspx.designer.cs file. Make sure the label control has been declared in there (this file is automatically generated by visual studio, but can sometimes not update properly). You should see a single line like this:
protected
global::System.Web.UI.WebControls.Label
lbl_FullName;
If it's the this.Master property then your page is obviously not referencing your masterpage. Check the page directive (the top line of your .aspx file) and make sure that the DynamicMasterPage value is set and that the path is correct.
On a design note, the masterpage isn't the best place to "store variables". The masterpage should literally just be used to initialise the common parts of the page across your site.
If you need to gather information from a user and use it across several pages, use session variables. This is a method of storing objects "in memory" for as long as the user's browser is open.
Items can be added to the session as follows:
this.Session.Add("fullName", fullName);
Items can then be retrieved later from any other page / usercontrol in your site as follows:
string fullName = (string)this.Session["fullName"];
ViewState is per-page. When you navigate to the new page, it isn't set.
Your master page should put these into Session instead.

Categories

Resources