Check Validity for a QueryString using Entity Framework - c#

I use C# Asp.Net and EF 4.
I have a scenario like MasterPage and DetailsPage.
So from my MasterPage I pass a variable as a QeryString to the DetailsPage, the DetailsPage will show up details for a specifc item in my DataBase.
I need to check the validity for my QueryString, in details I need:
Check if is Null, Empty or White Spaces.
Check if is NOT of type INT (just numbers not any letters).
Check if the Object NOT exists in my DB.
In case if Check result True, I will redirect the User.
At the moment I wrote this script. It is works but I would like to know if you know a better approch/code to solve this.
Also I would like to know if make sense to have this logic on every time the page Load, or would be enought us just on !Page.IsPostBack.
Thanks once again for your support guys!
protected void Page_Load(object sender, EventArgs e)
{
#region Logic Check Query String.
// Query String is Null or Empty.
if (string.IsNullOrWhiteSpace(ImageIdFromUrl))
RedirectToPage();
// Query String is not valid Type of INT.
int ImageId;
bool isInt = Int32.TryParse(ImageIdFromUrl, out ImageId);
if (isInt)
{
// Check if a valid Object request exist in Data Source.
using (CmsConnectionStringEntityDataModel context = new CmsConnectionStringEntityDataModel())
{
if (!context.CmsImagesContents.Any(x => x.ImageContentId == ImageId))
{
RedirectToPage();
}
}
}
else
RedirectToPage();
#endregion
}

You don't need to check it on every postback, only on a full page load. The query string is not sent to the server on postbacks.
I suggest you move all the query string validation logic to separate functions.

Related

Acumatica- Update Sales Order from Purchase Order

I am trying to update a custom field on the SOLine (UsrPOPromisedDate) when the POLine promised date is changed. Below is my graph extension, however SOLine is always null.
When I convert the BQL to T-SQL, I get the expected results returned. Why is my view always returning a null value?
using PX.Data;
using PX.KWW.MyProject.DAC;
using PX.Objects.PO;
using PX.Objects.SO;
namespace MyProject.Graph
{
public class POOrderEntryExt : PXGraphExtension<POOrderEntry>
{
public PXSelectJoin<
SOLine,
InnerJoin<SOLineSplit,
On<SOLineSplit.orderType, Equal<SOLine.orderType>,
And<SOLineSplit.orderNbr, Equal<SOLine.orderNbr>,
And<SOLineSplit.lineNbr, Equal<SOLine.lineNbr>>>>>,
Where<SOLineSplit.pOType, Equal<Current<POLine.orderType>>,
And<SOLineSplit.pONbr, Equal<Current<POLine.orderNbr>>,
And<SOLineSplit.pOLineNbr, Equal<Current<POLine.lineNbr>>>>>>
SalesOrderLine;
protected virtual void _(Events.FieldUpdated<POLine, POLine.promisedDate> eventHandler, PXFieldUpdated baseHandler)
{
baseHandler?.Invoke(eventHandler.Cache, eventHandler.Args);
POLine pOLine = eventHandler.Row;
if (pOLine is null) return;
SOLine sOLine = SalesOrderLine.Current;
SOLineExtension sOLineExtension = sOLine.GetExtension<SOLineExtension>();
if (sOLine is null || sOLineExtension is null) return;
sOLineExtension.UsrPOPromisedDate = pOLine.PromisedDate;
SalesOrderLine.Update(sOLine);
}
}
}
If you mean SalesOrderLine.Current is null, I don't believe the Current field is populated by default unless the user has selected a specific record within the view(or you manually set it).
If you are just trying to get the records within the view you would need to use SalesOrderLine.Select().
foreach(SOLine line in SalesOrderLine.Select()){
//Do Something Here
}
Looks like a mistake in your code.
And<SOLineSplit.pONbr, Equal<Current<POLine.orderType>>,

Get Search Queries from UrlReferer

I'm developing a website in ASP.Net 4. One of the requirements is to log search queries that people use to find our website. So, assuming that a URL parameter named "q" is present in Referrer, I've written the following code in my MasterPage's Page_Load:
if (!CookieHelper.HasCookie("mywebsite")) CookieHelper.CreateSearchCookie();
And my CookieHelper class is like this:
public class CookieHelper
{
public static void CreateSearchCookie()
{
if (HttpContext.Current.Request.UrlReferrer != null)
{
if (HttpContext.Current.Request.UrlReferrer.Query != null)
{
string q = HttpUtility.ParseQueryString(HttpContext.Current.Request.UrlReferrer.Query).Get("q");
if (!string.IsNullOrEmpty(q))
{
HttpCookie adcookie = new HttpCookie("mywebsite");
adcookie.Value = q;
adcookie.Expires = DateTime.Now.AddYears(1);
HttpContext.Current.Response.Cookies.Add(adcookie);
}
}
}
}
public static bool HasCookie(string cookiename)
{
return (HttpContext.Current.Request.Cookies[cookiename] != null);
}
}
It seems ok at the first glance. I created a page to mimic a link from Google and worked like a charm. But it doesn't work on the host server. The reason is that when you search blah blah you see something like www.google.com/?q=blah+blah in your browser address bar. You expect clicking on your link in the results, will redirect to your site and you can grab the "q" parameter. But ,unfortunately, it is not true! Google, first redirects you to an address like:
http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CCgQFjAA&url=http%3A%2F%2Fwww.mywebsite.com%2F&ei=cks5Uof4G-aX0QXKhIGoCA&usg=AFQjCNEdmmYFpeRRRBiT_MGH5a1x9wUUlg&bvm=bv.52288139,d.d2k&cad=rja
and this will redirect to your website. As you can see the "q" parameter is empty this time! And my code gets an empty string and actually doesn't create the cookie (or whatever).
I need to know if there is a way to solve this problem and get the real "q" value. The real search term user typed to find my website. Does anybody know how to solve this?
Google stopped passing the search keyword:
http://www.searchenginepeople.com/blog/what-googles-keyword-data-grab-means-and-five-ways-around-it.html

Saving Username into session property to help secure site

Edit Some have expressed their dislike for my particular solution presented in this problem, but please don't waste my time suggesting completely alternative methods. I have no control over the requirements of what I am working on. If you disagree with it and don't have an answer, just move along. Thanks.
For starters, this is a practice project and will not be used by the general public. I need to secure some pages in my website using session properties for username. This occurs (the username saved into session) when a correct username and password combo is entered. My boss reviewed my implementation and said that "storing the username value into the HttpSessionState directly is wrong, you should set the username property of the session, and store the session object into the HttpSessionState". Now I think I understand what parts of my code he is referring to, but changing this breaks the security (anyone can use a direct link to a page once a single user has logged in).
Make sure to read the comments in code, I added them to describe the lines in question.
What worked in terms of security, but username is stored directly into HttpSessionState:
//login.ascx.cs
private void Login_Click(object sender, EventArgs e)
{
if (sender == null || e == null)
{
throw new ArgumentNullException("Null Exception: Login_Click");
}
User user = new User();
user.Login(_username.Text, _password.Text);
if (user.IsValid() && user.GetIsUser() != false)
{
user.Save();
//the line below is what I used to make the secure pages work properly.
//but based on what my boss says, I think this is what should be changed.
Session["Username"] = _username.Text;
//What i tried instead was to set 'MySession.Current.Username = _username.Text;'
//which allowed successful login, but the pages became insecure once again.
Response.Redirect("Secure/Default.aspx");
}
else
{
DisplayErrors(user._validationErrors);
}
_errors.Text = errorMessage;
}
and MySession.cs
public string Username
{
get
{
if (HttpContext.Current.Session["Username"] == null)
{
return string.Empty;
}
else
{
return HttpContext.Current.Session["Username"].ToString();
}
}
set
{
//when the line below is uncommented, the secure pages are vulnerable
//but if I comment it out, they work properly.
//HttpContext.Current.Session["Username"] = value;
}
}
So how can I Set the username property of the session, and store the session object into the HttpSessionState while still maintaining a secure site?
EDIT: #Win, within Secure/Default.aspx.cs
private void Page_load(object sender, System.EventArgs e)
{
...
if((string)Session["Username"] != _labelusername.Text)
{
Response.Redirect(redirectLogin); //to login page
}
else {} //success
}
You should look into FormsAuthentication. There are many examples online like this one:
http://bradkingsley.com/securing-asp-net-pages-forms-authentication-c-and-net-4/

How can I keep my variable all the time without global variables?

I have two GridViews. I've got method GetGeneralDiagnosis which returns a list of all diagnosis:
CODE DIAGNOSIS
F50 Eating disorders
F51 Nonorganic sleep disorders
and method GetSpecificDiagnosis which returns more specific list:
CODE DIAGNOSIS
F50.0 Anorexia nervosa
F50.1 Atypical anorexia nervosa
F51.0 Nonorganic insomnia
F51.1 Nonorganic hypersomnia
Now I've got method which bind SPECIFIC DIAGNOSIS to second GridView according to GENERAL DIAGNOSIS from first GridView.
protected void gvGeneralDiagnosis_SelectedIndexChanged(object sender, EventArgs e)
{
string generalDiagnosis = gvGeneralDiagnosis.DataKeys[gvGeneralDiagnosis.SelectedIndex].Values["ICD10Code"].ToString();
var ICD10 = Visit.GetSpecificDiagnosis(); // here I'm getting data from database
gvSpecificDiagnosis.DataSource = ICD10.Where(i => i.ICD10Code.Contains(generalDiagnosis)).Select(i => new { i.ICD10Name, i.ICD10Code });
gvSpecificDiagnosis.DataBind();
}
I don't want to connect to database each time selected index is changed.
How can i get my list var ICD10 = Visit.GetSpecificDiagnosis() only once? I heard that global variables are very bad idea, so how can I do that in another way?
You can use a private member variable. This one "lives" as long as the class containing it lives. Wrap it with a property to access it and automatically read it from the database, if necessary.
private TypeOfICD10 _icd10;
private TypeOfICD10 ICD10
{
get
{
if (_icd10 == null) { // Get from database.
_icd10 = Visit.GetSpecificDiagnosis();
}
return _icd10;
}
}
Now you can use it like this and it will be read from the db only at the first call
protected void gvGeneralDiagnosis_SelectedIndexChanged(object sender, EventArgs e)
{
string generalDiagnosis = gvGeneralDiagnosis.DataKeys[gvGeneralDiagnosis.SelectedIndex].Values["ICD10Name"].ToString();
gvSpecificDiagnosis.DataSource = ICD10
.Where(i => i.ICD10Code.Contains(generalDiagnosis))
.Select(i => new { i.ICD10Name, i.ICD10Code });
gvSpecificDiagnosis.DataBind();
}
You can have your Visit class cache the returned data.
When GetSpecificDiagnosis is called, it will check whether this data was already retrieved from the database, and return it if it was. If it wasn't, it'll retrieve it from the database and save it to its cache.
One thing you should pay attention to is whether this data is static (i.e. never changes throughout the application's lifetime) or is it dynamic. In the first case, you won't have to do any special handling, but if it's the latter, you'll have to invalidate the cache one the information in the database has changed.
I recommend you to have a look here to see how to get started with caching in ASP.NET.
I don't know much about the Visist class from your question but why not cache ICD10 this way you will be using the cached object and the Database call will made only if the Cache Key ICD10 has a value of null
Example :
if(Cache["ICD10"] == null)
{
var ICD10 = Visit.GetSpecificDiagnosis();
Cache["ICD10"] = ICD10;
}
else
{
var ICD10 = Cache["ICD10"];
}

MVC 2.0 C# ModelUpdate wont update

I'm having trouble getting a ModelUpdate or TryModelUpdate to work in my code.
I'm using the default Role Manager and Login system created by MVC when running the ASP.Net configuration tool. What I'm trying to do is add another column to the Users table so I can record if my users are also customers. So I want to record their CustomerID there.
I used the ADO Entity Data Model to generate all my model code based off my database. The code it created for the field I want to update is here:
public string CustomerID
{
get
{
return this._CustomerID;
}
set
{
this.OnCustomerIDChanging(value);
this.ReportPropertyChanging("CustomerID");
this._CustomerID = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
this.ReportPropertyChanged("CustomerID");
this.OnCustomerIDChanged();
}
}
private string _CustomerID;
partial void OnCustomerIDChanging(string value);
partial void OnCustomerIDChanged();
In my controller Im trying to update the CustomerID field with this code:
var userToUpdate = dbu.aspnet_Users.First(u => u.UserName == User.Identity.Name);
UpdateModel(userToUpdate, new string[] { "CustomerID"}, txtID);
dbu.SaveChanges();
But I get an error saying the overload method has some invalid arguments.
I get that the issue is in assigning txtID to CustomerID based off the error, but whats the correct way to do it?
If I need to add more info please let me know.
I figured it out. Apparantly ModelUpdate won't let me pass in custom data and it needs to be passed in from the Form Collection. So using UpdateModel(userToUpdate, new string[] {"CustomerID"}, form.ToValueProvider()); worked.

Categories

Resources