Object reference not set to an instance of an object.#HttpContext - nullreferenceexception

hi i'm trying to get the current context with httpContext, but i get a System.NullReferenceException exception, don't know why cos every thing seem clear on the code
here is my property:
private static string ShoppingCartId
{
get
{
//on obtient le HttpContext actuel
HttpContext context = HttpContext.Current;
//on essaie d'extraire l'id stockés dans le cookie de l'utilisateur actuel
string cartId = context.Request.Cookies["LUP_CartID"].Value;
//si l'id du Cart n'est pas dans le cookie
{
//on vérifie si l'id du cart existe en tant que cookie
if (context.Request.Cookies["LUP_CartID"] != null)
{
//on retourne l'id
return cartId;
}
the Exception comes from this line : "string cartId = context.Request.Cookies["LUP_CartID"].Value;"

the cookie LUP_CartID doens't exist. context.Request.Cookies["LUP_CartID"] is returning null, when you call context.Request.Cookies["LUP_CartID"].Value you're trhying to ivnvoke null.Value . Check if context.Request.Cookies["LUP_CartID"] is not null.

Related

Correct Implementation of Forgot Password AspNetBoilerPlate

Im using aspnetboilerplate (MVC) and wanted to implement a forgot password feature to allow the user to reset their own passwords using a link on the login screen.
I imagine this to work by generating a password reset code which is then emailed to the user.The user follows the link and is taken to a screen allowing them to reset the password.
Im stuck at the initial stage. i started with a copy of the login action after noticing that when attempting to log in the user object was returned. From here i attempt to set a password reset code.
[HttpPost]
[UnitOfWork]
public virtual async Task<JsonResult> ForgotPassword(ForgotPasswordViewModel forgotPasswordModel, string returnUrl = "", string returnUrlHash = "")
{
returnUrl = NormalizeReturnUrl(returnUrl);
if (!string.IsNullOrWhiteSpace(returnUrlHash))
{
returnUrl = returnUrl + returnUrlHash;
}
var loginResult = await _logInManager.LoginAsync(forgotPasswordModel.UsernameOrEmailAddress, "ForgotPassword", GetTenancyNameOrNull());
loginResult.User.SetNewPasswordResetCode();
switch (loginResult.Result)
{
case AbpLoginResultType.Success:
return Json(loginResult);
default:
throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(loginResult.Result, forgotPasswordModel.UsernameOrEmailAddress, GetTenancyNameOrNull());
}
}
Checking the AbpUser table after the
loginResult.User.SetNewPasswordResetCode();
i cannot see any password reset code for the user, they are all null.
Could someone point me in the right direction.
Thanks in advance
Thanks to answer below for being correct, just for completion below is exactly what worked. Obviously ignore the json return at the end
public virtual async Task<JsonResult> ForgotPassword(ForgotPasswordViewModel forgotPasswordModel, string returnUrl = "", string returnUrlHash = "")
{
//var user = await GetUserByChecking(emailAddress);
var user = await _userManager.FindByEmailAsync(forgotPasswordModel.UsernameOrEmailAddress);
if (user == null)
{
throw new UserFriendlyException("User not found!");
}
user.SetNewPasswordResetCode();
//Send an email to user with the below password reset code
/* Uri.EscapeDataString(user.PasswordResetCode) */
return Json("");
}
public class AccountAppService: IAccountAppService
{
public UserManager UserManager {get; set; }
public async Task SendPasswordResetCode(string emailAddress)
{
var user = await UserManager.FindByEmailAsync(emailAddress);
if (user == null)
{
throw new UserFriendlyException("User not found!");
}
user.SetNewPasswordResetCode();
//Send an email to user with the below password reset code
/* Uri.EscapeDataString(user.PasswordResetCode) */
}
}

How I can use InvoiceShipment Delegate PXOverride in ShipmentEntry acumatica

I was implemented a delegate process of InvoiceShipment to validate the updated inventory after creating an invoice, in version 6.1 of acumatica, but in version 18.117.0016 the method isn't executed
I tried in two different forms, but the method isn't executed
1.
public delegate void InvoiceShipmentDelegate(SOInvoiceEntry docgraph, SOShipment shiporder, DateTime invoiceDate, DocumentList<ARInvoice, SOInvoice> list);
[PXOverride]
public void InvoiceShipment(SOInvoiceEntry docgraph, SOShipment shiporder, DateTime invoiceDate, DocumentList<ARInvoice, SOInvoice> list, InvoiceShipmentDelegate baseMethod)
{
SOOrderShipment envio = PXSelect<SOOrderShipment, Where<SOOrderShipment.shipmentNbr, Equal<Required<SOOrderShipment.shipmentNbr>>>>.Select(Base, shiporder.ShipmentNbr);
if (string.IsNullOrEmpty(envio.InvtRefNbr))
{
throw new PXException("No se puede preparar la factura, el inventario no ha sido actualizado");
}
baseMethod?.Invoke(docgraph, shiporder, invoiceDate, list);
}
2.
public void InvoiceShipment(SOInvoiceEntry docgraph, SOShipment shiporder, DateTime invoiceDate, DocumentList<ARInvoice, SOInvoice> list,
Action<SOInvoiceEntry, SOShipment, DateTime, DocumentList<ARInvoice, SOInvoice>> baseInvoiceShipment)
{
SOOrderShipment envio = PXSelect<SOOrderShipment, Where<SOOrderShipment.shipmentNbr, Equal<Required<SOOrderShipment.shipmentNbr>>>>.Select(Base, shiporder.ShipmentNbr);
if (string.IsNullOrEmpty(envio.InvtRefNbr))
{
throw new PXException("No se puede preparar la factura, el inventario no ha sido actualizado");
}
baseInvoiceShipment(docgraph, shiporder, invoiceDate, list);
}
How I can Execute this delegate method
It looks like the signature of that method changed (added PXQuickProcess.ActionFlow). Because you are overriding the old unused signature it does not get called. Use this signature and it should call into your override:
public virtual void InvoiceShipment(SOInvoiceEntry docgraph, SOShipment shiporder, DateTime invoiceDate, DocumentList<ARInvoice, SOInvoice> list, PXQuickProcess.ActionFlow quickProcessFlow)
{ //... }
You can look at the SOShipmentEntry source code for any reference to InvoiceShipment to see this change. I am looking at 18.120.0006 for this example.

MVC 5 Roles Out-of-the-box

Grettings. I see a thousand of questions and i lost on every one of them... So... Basically i start a new project on VS (WebAPI) with Authentication. I put the token on the header and the methods with
[Authorize]
works fine. Later i add a two roles into the table dbo.AspNetRoles (admin and users) and to one user i add the relationship in the table dbo.AspNetUserRoles like this:
USER ID | Roleid
-----------------------
1d156e98-fc8b-4dcb-8dba-f7c66131f488 | 1001
So, when i try to put this:
[Authorize(role="admin")]
Dont work... The request is denied.
What i need to do exactly?
Thanks
It's not "Authentication" but "Authorize". Try this:
[Authorize(Roles = "admin")]
But first you've to create your roles:
context.Roles.Add(new IdentityRole { Name = "admin" });
context.SaveChanges();
And assign role to the user:
var role = context.Roles.SingleOrDefault(m => m.Name == "admin");
user.Roles.Add(new IdentityUserRole { RoleId = role.Id });
Database initialization code can be put anywhere you want, it depends on you:
when the application starts - check if roles are there, if no then create them
generate migration and update the migration script by custom role inserts
put them manually in the database - BUT YOU HAVE TO DO IN PROPER WAY - add roles from the code and check what has been changed in the database
So at the end i use this following code to resolve this:
public class DAO
{
public static void addRoleToUser(ApplicationUser user, string role)
{
// EL SIGUIENTE CODIGO AGREGA AL USUARIO UN ROL
ApplicationDbContext context = new ApplicationDbContext();
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
userManager.AddToRole(user.Id,role);
}
}
This sync the role to the user and the context db.
In the controller after register a new user automatically adds the rol "User" with the code:
// POST api/Account/Register
[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
// Codigo de Ali para agregar el rol "User" al usuario inmediatamente es creado
DAO.addRoleToUser(user, "User");
return Ok();
}
Thanks to dawidr to help me to go deep on this.

Multiple form submition in spring mvc 3.0

i want to show entered data of user in a registration form (like preview page) to confirm correctness of entered data and if they accept, then that data should go into the database.
here is my controller code:
#RequestMapping( value="/catalogue/FormPreview.action", method=RequestMethod.POST)
public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,CatalogueBase catalogueBase) throws Exception {
if(catalogueBase.getTitleNumber()!= null)
{
request.setAttribute("titleNo", catalogueBase.getTitleNumber());
request.setAttribute("title", catalogueBase.getTitle());
request.setAttribute("name", catalogueBase.getName());
request.setAttribute("address", catalogueBase.getAddress());
request.setAttribute("email", catalogueBase.getEmail());
.....
return new ModelAndView("catalogue/catalogueFormPreview","catalogueBase",catalogueBase);
}
else
{
return create(catalogueBase);
}
}
#RequestMapping( value="/catalogue/create.action", method=RequestMethod.POST)
public ModelAndView create(#ModelAttribute CatalogueBase catalogueForm) throws Exception {
ModelAndView mvc = null;
try{
List<CatalogueBase> catalogueBases = new ArrayList<CatalogueBase>(); //getCatalogueBase(request);
catalogueBases.add(catalogueForm);
List<CatalogueBase> catalogueBaseList = catalogueService.create(catalogueBases);
mvc = new ModelAndView("catalogue/catalogueList");
} catch (Exception e) {
e.printStackTrace();
}
return mvc;
}
and I show the preview page as jsp using EL like:
Title NO : ${titleNo}
Title : ${title}
......
......
<a onclick="doAjaxPost();">Confirm Data<span class="icon icon44"></a>
and in the head section of the jsp I am calling ajax like:
<script>
function doAjaxPost() {
var name = $('#name').val();
var education = $('#education').val();
var str = $("#form").serialize();
$.ajax({
type: "POST",
url: "../catalogue/create.action",
data: str,
success: function(response){
alert("Record Added Successfully");
},
error: function(e){
alert('Error: ' + e);
}
});
};
it is showing data on preview page, but after clicking on confirm data, (hyperlink in preview page)
it sends null values to the create method(Second method) please can anyone tell why it's sending nulls and how I can solve this
thanks.
In Preview Page, you are only displaying the text, you need to get your data there as well in preview page either as hidden(or by any other means, like saving in session if much entries are there then etc). so that when you submit after confirmation, you can read all parameters.

Serialization PhoneApplicationPage Windows Phone

i hace a class named "Conexion" an i keep all the info of my app there, what i want its to save the object of the class to a file when the user presses the windows key, but the app crashes because it says the obect "delegado" has a problem reflecting his type. The type of this object is "PhoneApplicationPage" , it seems it cannot be serialized. The object keeps track of what page did the request.
so im requesting your help to see if theres a solution, that doesn make me redo the app, because i dont have time.
heres the code of the methods i use to save and load the data.
public void save() {
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream stream = storage.CreateFile(fileName);
DateTime currTime = DateTime.Now;
this.timeOff = currTime.ToString();
XmlSerializer xml = new XmlSerializer(this.GetType());
xml.Serialize(stream, this);
stream.Close();
stream.Dispose();
}
public Conexion load() {
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
Conexion conn;
if (storage.FileExists(fileName))
{
IsolatedStorageFileStream stream = storage.OpenFile(fileName, System.IO.FileMode.Open);
XmlSerializer xml = new XmlSerializer(typeof(Conexion));
conn = xml.Deserialize(stream) as Conexion;
stream.Close();
DateTime currTime = DateTime.Now;
DateTime checkTime = DateTime.Parse(timeOff).AddMinutes(lapso);
if (DateTime.Compare(checkTime, currTime) >= 0)
{
Console.WriteLine("sesion valida");
}
else {
conn.reseteaSingletonConexion();
}
stream.Dispose();
}
else
{
conn= new Conexion();
}
return conn;
}
thanks in advance
Edit:
Well ignoring the object "delegado" stopped the app from crashing, but now , when i load the info , the object cannot be deserialized , it seems it marks 2 details in the same error:
There is an error in XML document (2, 2).
Conexion cannot be serialized because it does not have a parameterless constructor.
but the class does have a parameterless constructor.
any idea?
You could use the [XmlIgnore] attribute against the objects that won't serialize (chances are you don't want to serialize the entire XAML page.
Place this attribute above a property in your Conexion class. Eg,
public class Conexion
{
public string MyPropertyToSerialize { get;set; }
[XmlIgnore]
public string MyPropertyToIgnore { get;set; }
}
Hope that helps.

Resources